微信小程序登录实现,前端+后端PHP代码(前端获得CODE,后端获取微信用户的OPEN ID 和 UNION ID)

说说获取openid 和 union id 的条件
1.AppID(小程序ID);
2.AppSecret(小程序密钥);
3.登录时获取code;

获取流程:

1.公众平台上找到AppID(小程序ID)和AppSecret(小程序密钥);
公众平台

2.微信小程序中调用API获取code

官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

示例代码:

 wx.login({
      success: function(res) {
        console.log(res.code)//这就是code  
    });

 

3.code 换取 session_key和openid
用户允许登录后,回调内容会带上 code(有效期五分钟),开发者需要将 code 发送到开发者服务器后台,使用code 换取 session_key api,将 code 换成 openid 和 session_key

接口地址:GET 请求  https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

官方文档https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

接口


后台访问微信服务器接口就能拿到openid 和 session_key, 至于会不会返回 union id ,需要有条件,见微信官方的文档说明: https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html

说明
文档说不应该把openid或者session_key作为用户标识;
我就不折腾了.直接用openid做唯一标识.没啥毛病.

当然也可以按照官方文档,后台生成session,以3rd_session为key,session_key+ opneid为value.

登录时序图

有人要问了,session_key 有啥用呢?见下面的回答

相关官方文档列表:

小程序登录:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html

前端获得CODE:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

后端根据CODE获得 OPEN ID 和 SESSION KEY : https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

流程图:

前端代码:获得CODE https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

wx.login({
      success: function (res) {
        var code = res.code
        if (code) {
          that.globalData.code = code;
          globalData: {
            code: code
          }
          wx.request({
            url: 'https://www.nidedyuming.com/index.php/index/index/login',
            method: 'POST',
            data: {code: code},
            success: function (res) {
              that.globalData.openid = res.data.openid;
              console.log(res.data.openid);
            }
          })
        }
      }
    })

后端PHP:拿着CODE去获取 OPEN ID 等信息 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

        function oauth2($code)
        {
            //$code = $_GET['code'];//小程序传来的code值
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid="你的APPID"&secret="你的app密钥"&js_code=' . $code . '&grant_type=authorization_code';
            //yourAppid为开发者appid.appSecret为开发者的appsecret,都可以从微信公众平台获取;
            $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据,推荐使用curl
            $json = json_decode($info);//对json数据解码
            $arr = get_object_vars($json);
            // dump($arr);die;
            $openid = $arr['openid'];
            return $openid;
        }
原文地址:https://www.cnblogs.com/zoutong/p/13545715.html