Previous article: UNI-APP Series I, build the basic structure of wechat applets project development

Wechat small program is more commonly used through wechat account system authorized login, which eliminates manual registration and login process, and the authenticity of information is also more reliable.

In uni-App, how to implement the authorized login operation of wechat applets, combined with the back-end PHP interface to achieve the whole process

It’s the same old routine. Start jerking off

A small wechat program to get the code to the server to get the OpenID and session_key

Attach document address

Steps:

  1. The wechat applet calls wx.login() to get the temporary login credential code and sends it back to the developer server.
  2. The server invokes the Auth. code2Session interface to obtain the user’s unique identification of OpenID and session key session_key.

The server obtains open data

Attach document address

Here use a developer background to verify and decrypt open data

Steps:

  1. The server obtains encryptedData and IV data based on the appID, User OpenID, openID obtained in the previous step, and wx.getUserInfo() method of wechat small program, and parses the user information data with the official case

  2. If the resolution is successful, perform subsequent operations. Resolve the failure and find the cause.

The above two steps are authorized to obtain user information provided by wechat officials. For details, please refer to the documentation. Here is only a brief explanation

Three small program end implementation code

1. The first step is for the applet to get the code through the wx.login() method, which simply calls the method to get the parameters.

Wx.getuserinfo () is used to retrieve the encryptedData and iv data from the wx.getUserInfo() method. If it is the first time to log in to the system, the call will directly enter the fail callback. Open-type is set to getUserInfo to obtain basic user information. Since the button must be triggered manually, the implementation idea is

2.1 Click on the button whose open-type is getUserInfo to retrieve the encryptedData and IV information.

2.2 Then call wx.login() in the SUCCESS callback to get the code.

2.3 Send the code to the server for the OpenID and session_key

2.4 Obtaining OpenID After a successful callback, the OpenID and encryptedData and IV obtained in 2.1 are sent to the server to parse the user information and perform a successful login

3. Take a screenshot of the page

4. The key is to authorize the login button

<button open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getUserinfo ="getUserInfo">Copy the code

Specify button open-type getUserInfo and set callback method getUserInfo()

The following is the entire method execution process, in order of execution

export default { data() { return { userdetail: {} } }, methods: { getUserInfo(res) { this.userdetail = res.detail; // Save the user information, next time use this.login(); Call wx.login() to get code}, login() {uni.login({provider: 'weixin', success: res => {this.wxlogin (res.code); }, fail: err => { console.log('err', err); }}); WxLogin (code) {let params = {code}; wxLogin(code) {let params = {code}; this.$ajax.wxlogin(params).then(res => { this.wxAuth(res.data.openid); }); }, // Parse data wxAuth(openID) {let params = {openID, iv: this.userdetail.iv, encryptedData: this.userdetail.encryptedData }; This.$ajax.wxauth (params).then(res => {uni.showtoast ({title: 'authorization succeeded ', duration: 2000})}); }}}Copy the code

The server implementation code takes PHP as an example

PHP uses CodeIgniter as an example

Openid public function index_post() {$id = "" $secret = "" $post =" $this->input->post(); $code = trim($post['code']); // Get the code value $ajax_URL = passed by the applet "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code"; $res = functionHelper::ajax_get($ajax_url); $data = array(); if (! Empty ($res)) {$res_arr = json_decode($res, true); If ($res_arr) {/ / will return to give small program openid $data [' data '] [' openid] = $res_arr [' openid]? $res_arr['openid'] : ''; //session_key is stored in redis and is not returned to the applet. Manual head $this - > cache - > redis - > save ($res_arr [' openid], $res_arr [' session_key], 3000); Response_ok ($this, $data); } else {responseHelper::response_bad_request($this, "request failed "); }} public function auth_post() {$appId = ""; $post = $this->input->post(); $openID = $post['openid']; $encryptedData = $post['encryptedData']; $iv = $post['iv']; $sessionKey = $this->cache->redis->get($openID); $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data); $data_arr = json_decode($data, true); if ($errCode == 0) {$data_arr = json_decode($data, true); responseHelper::response_ok($this, $data_arr); } else {responseHelper::response_bad_request($this, "failed "); }} public static function ajax_get($durl) {$headers = array(); $curl = curl_init(); Curl_setopt ($curl, CURLOPT_URL, $durl); // Return the information obtained by curl_exec() as a file stream rather than output it directly. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); Curl_setopt ($curl, CURLOPT_BINARYTRANSFER, true); Curl_setopt ($curl, CURLOPT_HTTPHEADER, $headers); Curl_setopt ($curl, CURLINFO_HEADER_OUT, true); $curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); $data = curl_exec($curl); Curl_close ($curl); Return $data; }Copy the code

The WXBizDataCrypt method used to decrypt data can be downloaded by using the PHP example provided by wechat

Obtain a mobile phone number

The process and resolution method for obtaining mobile phone numbers and users are the same. The only difference is that the button type needs to be set to getPhoneNumber. The process of obtaining a mobile phone number is left to you to test yourself.