小程序开发(授权登陆)

吐槽君 分类:微信小程序

授权登陆功能实现:

1.通过wx.login获取code

2.然后wx.request发送给后台,获取openid和session_key

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

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

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

login.js

Page({

data:{login:flase},

onLoad: function () {

  var that = this;

  // 查看是否授权

  let a = wx.getStorageSync('token')

  //获取token

  if (a ==""){

  	//通过改变login的ture或flase来判断是否展示登陆按钮

that.setData({login:flase})

}else{

that.setData({login:ture})}

 },

//登陆

 bindGetUserInfo:function(e){

consloe.log(e)

let a = e.detail

wx.login({

	//获取code发送到php后台

success:function(res){

	console.log(res.code)

	wx.request({

          url: 'login.php', //接口地址

          data: {code:res.code},

          header: {

            'content-type': 'application/json' //默认值

          },

          success: function (res) {

            console.log(res.data.token)

            wx.setStorageSync('token',res.data.token)

            //缓存token

            this.setData({

           login:ture

})

          },fail:function(){

           console.log("登陆失败")

}

        })

	}

})

}

})
 

login.wxml

  <view wx:if="{{login}}" class='userinfo'>

        <open-data type="userAvatarUrl"></open-data>

      </view>

      <view wx:else>

      <button type='primary' open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo" >授权登录</button>

      </view>
 

login.wxss

.userinfo {

  overflow: hidden;

  display: block;

  width: 120rpx;

  height: 120rpx;

  border-radius: 50%;

}
 

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发送到客户端,用作登陆态,最好是设置有时效性的。

本人菜鸟一枚,有什么错的地方希望大佬们多多包涵。

作者:掘金-小程序开发(授权登陆)

回复

我来回复
  • 暂无回复内容