Authorized login function:

1. Obtain the code from wx.login

2. Then wx.request is sent to the background to obtain the OpenID and session_key

3. The service randomly generates a unique string of 3rdSessionId according to the OpenID end

4. The client uses wx. setStoragesync to cache the 3rdSessionId

Wx. getStoragesync = 3rdSessionId = 3rdSessionId;

login.js

Page({ data:{login:flase}, onLoad: function () { var that = this; Let a = wx.getStoragesync ('token') // Obtain token if (a ==""){// Display the login button by changing the ture or flase of login that.setData({login:flase}) }else{ that.setData({login:ture})} }, BindGetUserInfo :function(e){consloe.log(e) let a = e.dail wx.login({function(res){ Console. log(res.code) wx.request({url: 'login.php', // Interface address Data: {code:res.code}, header: {'content-type': 'application/json' // default}, success: Function (res) {console.log(res.data.token) wx.setStoragesync ('token',res.data.token) // Cache token this.setData({function (res) {console.log(res.data.token) wx.setStoragesync ('token',res.data.token) // Cache token this.setdata ({ Login: true})}, fail: the function () {the console. The log (" login failed ")}}}}}})))Copy the code

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 ">Copy the code

login.wxss

.userinfo {

  overflow: hidden;

  display: block;

  width: 120rpx;

  height: 120rpx;

  border-radius: 50%;

}
Copy the code

PHP parsing code (login.php interface):

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=author ization_code"; $str = file_get_contents($url); $json = json_decode($str); $arr = get_object_vars($json); echo $openid = $arr['openid']; Echo $session_key = $arr['session_key']; // this is session_key}Copy the code

Conclusion:

The background generates 3rdSessionId according to openID and sends it to the client, which is used as login state. It is better to set it with timeliness.

Oneself rookie one, have what wrong place hope big men many bear with.