Helloworld

php后端获取用户openid 头像 昵称

php后端获取用户openid 头像 昵称

php

/**
 * 获取用户openid
 */
public function getOpenid()
{

    if (!isset($_GET['code']) || !isset($_GET['nick']) || !isset($_GET['avaurl']) || !isset($_GET['sex'])) {
        return false;
        header("Content-type: text/html; charset=utf-8");
        echo '参数错误.';
        exit;
    }
    $appid1 = Db::name('config')->value('appid');
    $secret1 = Db::name('config')->value('secret');
    //微信小程序appid
    $appid = $appid1;
    //微信小程序secret
    $secret = $secret1;

    $code = $_GET['code'];        //小程序传来的code值
    $nick = $_GET['nick'];        //小程序传来的用户昵称
    $imgUrl = $_GET['avaurl'];    //小程序传来的用户头像地址
    $sex = $_GET['sex'];        //小程序传来的用户性别
    // dump($imgUrl);die;
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
    $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据,推荐使用curl
    $json = json_decode($info, true);//对json数据解码


    return json_encode($json);
}
-

js
//获取用户头像昵称

点击查看代码
//获取用户头像昵称
  login: function () {
    wx.getUserProfile({
      desc: '完善用户信息',
      success:(res) =>{
        var openid = wx.getStorageSync('openid');
        var nickName = res.userInfo.nickName;
        var avatarUrl = res.userInfo.avatarUrl;
        let introduct = app.globalData.url + '/index/User/user_message_update';
        let data = {
          nickName :nickName,
          avatarUrl:avatarUrl,
          openid:openid
         };
         app.wxRequest('POST', introduct, data, (res) => {
           if(res.code == 500){
            wx.showToast({
              title: '授权成功',
            })
            wx.switchTab({
              url: '/pages/my/my',
            })
           }
        }, (err) => {
        //   console.log(err);
        // console.log(err.errMsg)
         })
      }
    })
  },

在后端接口中更新用户信息即可

posted @ 2022-07-01 17:48  蜻蝇吊客  阅读(800)  评论(0)    收藏  举报
Live2D