小程序开发(授权登陆)

3,033

授权登陆功能实现:

1.通过wx.getUserProfile接口获取用户信息,wx.login获取code

2.然后wx.request发送给后台,获取openid和session_key,保存用户信息

3.服务根据openid端随机生成一串唯一字符串为3rdSessionId

4.客户端使用wx.setstoragesync缓存3rdSessionId

5.用wx.getstoragesync获取3rdSessionId如果存在,就已经登陆,不存在就未登陆(检验登陆态)

wxml:

  <button bindtap="getUserInfos"></button>

js:

getUserInfos: function(e) {
    wx.getUserProfile({
      desc: '业务需要',
      success: res => {
//获取信息成功,调用
this.setCode( res.userInfo);
      }
    })
  },
setCode:function(a){
var that = this;
//code获取
wx.login({
success: function(res) {
        wx.request({
          method: 'GET',
          url: 'xxx.com',
 data: {
            code: res.code,
            userName: a.nickName,
            userImg: a.avatarUrl,
            gender: a.gender,
            city: a.city
          },
          header: {
            'content-type': 'application/json'
          },
success: function(res) {
//成功后
//缓存用户token
wx.setStorageSync('user', res.data)
          },
fail: function() {
         //失败   
          }
        })
      }
    })
  }

php解析code代码(login.php接口):

function login(){

    $code = $_GET['code'];

    $appid = 'APPID';

    $AppSecret = 'APPSECRET';

    $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$AppSecret."&js_code=".$code."&grant_type=authorization_code";

    $str = file_get_contents($url);

    $json = json_decode($str);

    $arr = get_object_vars($json);

    echo $openid = $arr['openid']; //这是openid

    echo $session_key = $arr['session_key']; //这是session_key

}

总结:

后台根据openid生成3rdSessionId发送到客户端,用作登陆态,最好是设置有时效性的。

本人菜鸟一枚,有什么错的地方希望大佬们多多包涵,小程序推荐: