Wechat web page authorization

Development scene: public mall

There are two ways of webpage authorization: one is webpage authorization with SNSAPi_base as scope, namely silent authorization.

Advantages: Users have no perception disadvantages: users need to pay attention to the public

The other is the authorization method with SNSAPi_userinfo as scope

Advantage: the user does not need the audience public number disadvantage: the user needs the manual unified authorization

This scenario uses the second method

The front part

Step 1: Get the code

Direct the user to open the following link:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsap i_userinfo&state=STATE#wechat_redirect

APPID: unique identifier of the public id redirect_URI: address of the callback link redirected after authorization

Redirect_uri: Change the authorization callback domain name in development – Interface permission – Web service – Web Account – Obtaining Basic User Information through Web authorization on the official website of the public platform. Please note that this is the domain name (a string), not the URL, so do not include protocol headers such as http://;

Authorization Page:

After the user agrees to authorize

If the user agrees to authorize, the page is redirect_uri/? code=CODE&state=STATE

The code is obtained by intercepting the URL. Since the secret of the public number and the access_token obtained are of very high security level, the code is transmitted to the back end, which processes the following process, including refreshing the access_token and obtaining user information through the access_token.

Code Description: The code is used as an access_token token. The code on the authorization strip is different each time. The code can be used only once and expires automatically if it is not used within 5 minutes.

The backend part

Step 2: Exchange web authorization access_token with code

After receiving the code from the front end, request the following link to obtain the access_token:

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
The GET: https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

Use wechat JSSDK (Share, pay)

Binding domain

Fill in “JS interface security domain name” in “Function Setting” of “public Account Setting”. Note: To download the MP_verify_EZhQkscUv44pvLNO. TXT file to the root directory of the project, the project uses the Nginx proxy. The project is stored in the dist directory in a folder on the server. Therefore, MP_verify_EZhQkscUv44pvLNO. TXT can be stored in the dist directory

Importing JS files

This project can be installed using NPM:

npm install weixin-js-sdk
Copy the code

use

import wx from 'weixin-js-sdk';
Copy the code

Verify the configuration through the config interface injection permission

1. Back-end signature

(1) Obtain access_token
HTTPS request mode: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET

Note: The validity period of access_token is currently 2 hours and needs to be updated periodically

(2) Obtain jSAPi_ticket

Use the access_token obtained in the first step to request the JSAPi_ticket in HTTP GET mode

HTTPS request mode: GET https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi

Note: The validity period of jsapi_ticket is 2 hours and needs to be updated periodically

(3) Generate signatures

Signature algorithm

Fields participating in the signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), url (the url of the current web page, excluding # and the following part, usually passed from the front end to the back end). After sorting all parameters to be signed in alphabetical order according to the ASCII code of the field name, use the FORMAT of URL key-value pairs (key1= Value1 &key2=value2…). Concatenated to the string string1. Note that all parameter names are lowercase characters. Sha1 encrypts string1, using the original field name and value, without URL escape.

The official instance

noncestr=Wm3WZYTPz0wzccnW jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg timestamp=1414587457  url=http://mp.weixin.qq.com?params=valueCopy the code

Step 1 Sort all parameters to be signed in alphabetical order based on the ASCII characters of field names, and use the URL key-value pair format (key1= ValuE1&key2 =value2…). Concatenated to the string string1:

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0w zccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=valueCopy the code

Step 2. Create sha1 signature for string1.

Var jssha = require(var jssha = require('jssha');

var shaObj = new jsSHA(string1, "TEXT");
signature = shaObj.getHash('SHA-1'.'HEX');
Copy the code
0f9de62fce790f9a083d5c99e95740ceb90c27ed
Copy the code

2. The front end obtains the signature and infuses the permission verification configuration

wx.config({
  debug: true// If debug mode is enabled, the return value of all API calls will be displayed in the client side alert. To view the passed parameters, you can open it in the PC side and the parameter information will pass throughlogPrint, print only on PC. appId:' 'Timestamp:, // Mandatory, generated signature's timestamp nonceStr:' ', // mandatory, generate a random string signature:' ',// Required, signed jsApiList: ['onMenuShareAppMessage'.'onMenuShareTimeline'.'chooseWXPay'] // Required, list of JS interfaces to be used (sharing and payment used in this project)}); wx.ready(function(){// The ready method is executed after the config information is validated. All interface calls must be made after the result of the config interface. Config is an asynchronous operation on the client side, so if the relevant interface needs to be called when the page loads, it must be called in the ready function to ensure correct execution. Interfaces that are invoked only when triggered by the user can be invoked directly without being placed in the ready function. });Copy the code

Calling the payment interface

The payment signature mode is similar to the authentication Config signature mode above

Wx.choosewxpay ({timestamp: 0, // Payment signature timestamp, note that all using timestamp fields in wechat JSSDK are lowercase. But the latest version of the payment background generated signature timeStamp field name needs to be capitalized where the S character nonceStr:' ', // Payment signature random string, no longer than 32 bits package:' '// The prepay_id parameter returned by the unified payment interface is submitted in the following format: prepay_id=\*\* *) signType:' '// Signature mode. The default value is'SHA1'To use the new version of the payment needs to be passed in'MD5'
  paySign: ' ', // Pay signature success:function(res) {// Callback function after successful payment}, cancel:function(res) {// Cancel payout callback function}});Copy the code