Wechat applet + php authorized login, complete code

Keywords: PHP curl JSON SDK

First map

      

 

Implementation process:

1. The authorized login button and the body information are placed on the same page. The login button is displayed when the user is not authorized, the login button is hidden when the user is authorized, and the body information is displayed. Of course, the authorization and the body can be separated into two pages. In the onload of the authorization page, judge whether the user is authorized or not. If the user is authorized, directly jump to the page of the body. This only refers to the case where the authorization button and the body are on the same page.

2. In onload, judge whether it is authorized first. If it is authorized, hide the authorized login button to display the text information. If it is not authorized, display the authorized login button.

3. The front-end uses the button's open type = "getUserInfo" to operate. After clicking the authorization button, the "e" will carry the userInfo and the user's basic information (the same as the data obtained by using the wx.getUserInfo interface, so I took it directly in the "e" instead of calling the wx.getUserInfo interface)

4. Use the wx.login interface to obtain the code of the login certificate, and use the code to decrypt in exchange for openid. When transmitting the code, take the user information obtained in step 3 and send it to the background for decryption (it can also not be carried, the purpose of carrying is to verify the signature, so it is safer, and it can not be verified)

5. The background decryption uses the "auth.code2Session" interface, and the SDK download address used for decryption.“ https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html".

5. After the background decryption (the background language is php), sensitive information such as openid will be returned, which can also be saved.

6. After obtaining the authorization, hide the authorization login button to display the text information.

7. If the user clicks "deny authorization", the user will be prompted to authorize again.

Note that authorization failure should be considered

 

Here is the detailed code

wxml

<view wx:if="{{isHide}}">
    <view wx:if="{{canIUse}}" >
        <view class='header'>
            <image src='/images/icon/wx_login.png'></image>
        </view>
 
        <view class='content'>
            <view>Request permission to</view>
            <text>Get your public information(Nicknames, avatars, etc)</text>
        </view>
 
        <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo">
            Authorized login
        </button>
    </view>
    <view wx:else>Please upgrade wechat version</view>
</view>
 
<view wx:else>
    <view>My homepage content</view>
</view>

wxss

.header {
    margin: 90rpx 0 90rpx 50rpx;
    border-bottom: 1px solid #ccc;
    text-align: center;
    width: 650rpx;
    height: 300rpx;
    line-height: 450rpx;
}
 
.header image {
    width: 200rpx;
    height: 200rpx;
}
 
.content {
    margin-left: 50rpx;
    margin-bottom: 90rpx;
}
 
.content text {
    display: block;
    color: #9d9d9d;
    margin-top: 40rpx;
}
 
.bottom {
    border-radius: 80rpx;
    margin: 70rpx 50rpx;
    font-size: 35rpx;
}

js

// pages/test1/test1.js
var app = getApp();
Page({

  /**
   * Initial data of the page
   */
  data: {
    //Judging applet's API,Whether callbacks, parameters, components, etc. are available in the current version.
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false
  },

  /**
   * Life cycle function -- listening to page loading
   */
  onLoad: function (options) {
    var that = this;
    // See if authorized
    wx.getSetting({
      success: function (res) {
        if (!res.authSetting['scope.userInfo']) {
          // Not authorized yet, display authorization button
          that.setData({
            isHide: true
          });
        } else {
          // Authorized, hide authorization button, show body
          that.setData({
            isHide: false
          });
        }
      }
    })
  },

  //Authorized login button
  bindGetUserInfo: function (e) {
    var that = this;
    console.log(e)
    if (e.detail.userInfo) {
      //User authorized to log in and jump to the home page
      // that.getOpenid()
      wx.login({
        success: function (res) {
          // Request to get users in the background openid
          wx.request({
            url: app.domain + 'teacherapi/Wx_Decode/WxDecode',
            method: 'POST',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            data: {
              encryptedData: e.detail.encryptedData,
              signature: e.detail.signature,
              rawData: e.detail.rawData,
              iv: e.detail.iv,
              code: res.code
            },
            success: function (res_user) {
              if (res_user.data.status == 0) {
                var data = JSON.parse(res_user.data.msg)    //json Transfer object
                //The data returned from authorization is operated according to your own needs
                console.log(data)

                //After the authorization is successful, hide the authorization button and display the text
                that.setData({
                  isHide: false
                });
              }
            }, fail: function () {
              that.showModal('Failed to get authorization information')
            }
          })
        }
      })
    } else {
      //The user presses the deny authorization button and prompts for boot authorization
      that.showModal('Please authorize to use the applet')
    }
  },

  //Unauthorized pop up
  showModal: function (e) {
    wx.showModal({
      title: 'Tips',
      content: e,
      showCancel: false,
      confirmText: 'Return authorization',
      success: function (res) {
        if (res.confirm) {
          console.log('User clicks "return to authorization"')
        }
      }
    })
  },

})

php

<?php
namespace app\teacherapi\controller;
use think\Controller;
/**
* @date: 2018-12
* Wechat operation class
*/

class WxDecode extends Controller
{
    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     * @author: zxf
     * @date: 2018-12-08
     * @description: Decrypt wechat user sensitive data
     * @return array
     */
    public function WxDecode()
    {
        // Receiving parameters
        $data = request() -> param();
        

        // Introducing decryption file to download in wechat applet development document
        vendor('wx.WXBizDataCrypt');
        vendor('wx.ErrorCode');

        $appid = config('TESTPPID');
        $appsecret = config('TESTSECREET');
        $grant_type = "authorization_code"; //Authorization (required)

        $code = $data['code'];        //Valid for 5 minutes login session

        $encryptedData=$data['encryptedData'];
        $iv = $data['iv'];
        $signature = $data['signature'];
        $rawData = $data['rawData'];

        // Splicing url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $res = json_decode($this->httpGet($url),true);


        $sessionKey = $res['session_key']; //take out json Corresponding value in
        $signature2 =  sha1(htmlspecialchars_decode($rawData).$sessionKey);
        // Verifying signature
        if ($signature2 !== $signature){
            return json("Failure of verification");
        } 

        // Get decrypted data
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {
            return return_succ($data);
        } else {
            return return_error($errCode);
        }
    }
        
}

Posted by Dixen on Tue, 12 Nov 2019 23:52:35 -0800