目录

微信小程序学习实录10轻松获取用户昵称头像与登录openid实战攻略

微信小程序学习实录10:轻松获取用户昵称、头像与登录openid实战攻略

https://i-blog.csdnimg.cn/direct/6cc752795e644f6fb4b80f601f009f49.png

在微信小程序开发中,获取用户的个人信息(如昵称和头像)以及用户的唯一标识OpenID是非常常见的需求。本文将详细介绍如何通过微信提供的API来实现这些功能,并提供一个完整的实战案例。

用户选择头像

微信提供了chooseAvatar组件,允许用户从相册或相机选择一张图片作为头像。我们可以使用这个组件来让用户选择并更新他们的头像。当小程序需要让用户完善个人资料时,可以通过微信提供的头像昵称填写能力快速完善。

wxml文件

<!--pages/user/index.wxml-->
<view class="page">
  <view class="weui-form container">
    <button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
      <image class="avatar" src="{{avatarUrl}}"></image>
    </button>
    <view class="weui-form__control-area">
      <view class="weui-cells__group weui-cells__group_form">
        <view class="weui-cells">
          <view class="weui-cell weui-cell_active">
            <view class="weui-cell__hd">
              <label class="weui-label">昵称</label>
              <view class="weui-cell__desc">必填项 *</view>
            </view>
            <view class="weui-cell__bd">
              <input type="nickname" class="weui-input" bindinput="bindPassInput" placeholder="请输入昵称" placeholder-class="weui-input__placeholder" value="{{newpass}}" />
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</view>

wxss文件

.page {
  height: 100vh;
  background-color: #fff;
}

.avatar-wrapper {
  padding: 0;
  width: 56px !important;
  border-radius: 8px;
  margin-top: 40px;
  margin-bottom: 40px;
}

.avatar {
  display: block;
  width: 56px;
  height: 56px;
}

.container {
  display: flex;
}

js文件

// pages/user/index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const utils = require("../../utils/util.js");
Page({
    data: {
        avatarUrl: defaultAvatarUrl,
    },
    onLoad() {
        //获取用户openid
        //this.userLogin();
    },
    onChooseAvatar(e) {
        const {
            avatarUrl
        } = e.detail
        console.log(avatarUrl)
        this.setData({
            avatarUrl,
        })
    },
    userLogin() {
        wx.login({
            success(res) {
                console.log(res.code)
                if (res.code) {
                    //发起网络请求
                    wx.request({
                        url: utils.host_domain + 'api/api.php?act=getUserInfo&token=3cab7ce4142608c0f40c785b5ab5ca24',
                        method: "POST",
                        data: JSON.stringify({
                            code: res.code
                        }),
                        header: {
                            'content-type': 'application/json' // 默认值
                        },
                        success(res) {
                            console.log(res.data.data);
                        }
                    })
                } else {
                    console.log('登录失败!' + res.errMsg)
                }
            }
        })
    }
})

获取用户授权

在微信小程序中,为了保护用户隐私,开发者需要先获得用户的授权才能获取其个人信息。我们可以通过wx.login接口获取用户的临时登录凭证code,然后使用该code向微信服务器换取用户的OpenID等信息。

php后端

获取用户信息

 public function getUserInfo() {
  $data = json_decode(file_get_contents('php://input'), true);

  if (!isset($data['code'])) {
    $response = [
      'code' => 0,
      'msg' => 'Missing code parameter',
      'data' => null
    ];
    die(json_encode($response));
  }

  $code = $data['code'];
  $appid = 'your_appid'; // 替换为你的小程序 AppID
  $secret = 'your_secret'; // 替换为你的小程序 AppSecret
  $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);

  $response = curl_exec($ch);

  if (curl_errno($ch)) {
    $error_msg = 'cURL error: ' . curl_error($ch);
    $response = [
      'code' => 0,
      'msg' => $error_msg,
      'data' => null
    ];
  } else {
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($httpCode == 200) {
      $jsonResponse = json_decode($response, true);
      if (json_last_error() === JSON_ERROR_NONE) {
        $response = [
          'code' => 1,
          'msg' => 'OK',
          'data' => $jsonResponse
        ];
      } else {
        $response = [
          'code' => 0,
          'msg' => 'JSON decode error: ' . json_last_error_msg(),
          'data' => null
        ];
      }
    } else {
      $response = [
        'code' => 0,
        'msg' => 'HTTP error: ' . $httpCode,
        'data' => null
      ];
    }
  }

  curl_close($ch);
  die(json_encode($response));
}

保存用户信息

public function saveUserInfo() {
  $data = json_decode(file_get_contents('php://input'), true);

  if (!isset($data['avatarUrl']) || !isset($data['nickname'])) {
    $response = [
      'code' => 0,
      'msg' => 'Missing required parameters',
      'data' => null
    ];
    die(json_encode($response));
  }

  $avatarUrl = $data['avatarUrl'];
  $nickname = $data['nickname'];

  // 这里可以将用户信息保存到数据库或其他存储系统
  // 示例:假设你有一个数据库连接 $conn
  // $stmt = $conn->prepare("INSERT INTO users (avatar_url, nickname) VALUES (?, ?)");
  // $stmt->bind_param("ss", $avatarUrl, $nickname);
  // $stmt->execute();

  $response = [
    'code' => 1,
    'msg' => 'User information saved successfully',
    'data' => null
  ];

  die(json_encode($response));
}

@漏刻有时