Recently I received an urgent demand for wechat web page development, because most of the calls to wechat API are processed in the back end, so the front end has no sense. But whole flow, it is necessary to know also as front end, otherwise work overtime besides the overdraw on the body, what harvest do not have

authorization

Those who are not interested in the text can just drag it down to see the image

First get the access_token

The process of applying for an official account is not described here. Access_token is a certificate to use the wechat interface. Different types of official accounts have different permissions to use the interface. Access_token is valid for 7200 seconds

HTTPS request method: GET api.weixin.qq.com/cgi-bin/tok…

The ginseng

AppId and secret can be seen in the background of wechat official accounts, and grant_type is filled in client_credential

Return to participate

  • Normal state
{"access_token":"ACCESS_TOKEN","expires_in":7200}
Copy the code
  • The state of failure.
{"errcode":40013,"errmsg":"invalid appid"}
Copy the code

More error code instructions click

And then web authorization

The first step is to get the code

Obtaining the code requires authorization. There are two ways, silent authorization (users do not perceive) and the need to obtain users’ consent. Wechat official documents specifically mention that there are two scenarios, users do not perceive

1. As mentioned above, for web page authorization with SNSAPi_base as scope, it is silent authorization, and users have no perception; 2. For the user who has followed the public account, if the user enters the webpage authorization page of the public account from the session or custom menu of the public account, even if the scope is SNSAPi_userinfo, it is silent authorization and the user has no perception.

Scope for snsapi_base(silent authorization)

Open.weixin.qq.com/connect/oau…

Scope is snsapi_userinfo(user’s consent required)

Open.weixin.qq.com/connect/oau…

The second step is to exchange the access_token with code

The obtained access_token is used to call other interfaces, unlike the underlying access_token.

Request access code, the following links for access_token: api.weixin.qq.com/sns/oauth2/…

  • Return to participate
{
  "access_token":"ACCESS_TOKEN"."expires_in":7200."refresh_token":"REFRESH_TOKEN"."openid":"OPENID"."scope":"SCOPE" 
}
Copy the code

Step 3 Refresh the token

The validity period of the Access_token is short. When the Access_token becomes invalid, refresh_Token can be refreshed (30 days). When the refresh_token becomes invalid, the user needs to re-authorize the access_token

For the second step after refresh_token, request the following links for access_token: api.weixin.qq.com/sns/oauth2/…

  • Return to participate
{ 
  "access_token":"ACCESS_TOKEN",
  "expires_in":7200,
  "refresh_token":"REFRESH_TOKEN",
  "openid":"OPENID",
  "scope":"SCOPE" 
}
Copy the code

Step 4 Pull user information (scope is snsapi_userinfo)

HTTP: GET (please use the HTTPS protocol) api.weixin.qq.com/sns/userinf…

  • Return to participate
{ "openid":" OPENID", "nickname": NICKNAME, "sex":"1", "province":"PROVINCE", "city":"CITY", "country":"COUNTRY", "headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbE RQQ4eMsv84eavHiaiceqxibJxCfHe / 46 ", "privilege" : [" PRIVILEGE1 "" PRIVILEGE2"], / / the user privilege information, json arrays, For example, the wechat Werka user is "UnionID ": "o6_bmasdasdsad6_2sgVt7hMZOPfL"}Copy the code

The above are noteworthy:

  • twoaccess_tokenThe difference between. throughAppIdandsecretTo obtain theaccess_tokenIs the credential of using wechat interface, passcodeIn return for theaccess_tokenIs used to obtain user information (scopeforsnsapi_userInfo)
  • Silent authorization can only be obtainedopenid, non-silent authorization is required to passaccess_tokenGet more information about the user, such as nicknames, avatars,unionidEtc.
  • access_tokenHas a shorter validity period (7200 seconds) whenaccess_tokenAfter timeout, it can be usedrefresh_tokenRefresh,refresh_tokenIt is valid for 30 days

share

Click on the upper right corner of wechat, wechat will share by itself, but sometimes we want to customize the content we share, we can change it through the following steps

Configure the JS secure domain name

The introduction of JSSDK

npm install weixin-js-sdk
import wx  from "weixin-js-sdk"
Copy the code

Verify the configuration through the config interface injection permission

Wx. config({debug: true, // Enable debug mode, the return value of all API calls will be alert in the client, if you want to view the passed parameters, you can open it in the PC, parameter information will be printed in the log, only on the PC. Timestamp:,// Required, generate signature's timestamp nonceStr: ",// Required, generate signature's random string signature: ",// Required, signature jsApiList:" [] // Required, list of JS interfaces to use});Copy the code

Api.weixin.qq.com/cgi-bin/tic…

  • Return to participate
{
"errcode":0,
"errmsg":"ok",
"ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
"expires_in":7200
}
Copy the code

Obtain the JSAPi_ticket (validity period: 7200 seconds) based on the access_token. The signature generation rule is composed of nonCESTr (random string), valid jSAPi_ticket, TIMESTAMP (timestamp), URL, sorted according to the ASCII code of the field from smallest to largest, and spliced into a string in the form of key-value pairs, such as

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

I remember the ASCII value of little A was 97, and so on, and sha-1 encrypted the string. Ok, so the question is, how do I randomly generate strings? What is SHA1 encryption

How to generate random characters

import java.util.Random;
Copy the code

In fact, there are various Java classes on the back end, which I found on the Internet

SHA – 1 encryption

Sha-1 is a data encryption algorithm that takes a piece of plain text and converts it irreversibly into a (usually smaller) piece of ciphertext, or simply takes a string of input codes (called premaps or messages), The process of converting them into a short, fixed-bit output sequence known as a hash value (also known as a message digest or message authentication code).

Wx. ready Processing interface succeeded. Procedure

const shareParams = {
       desc: "Description".title: "Title".link:"Shared URL"(Ensure that the CONFIGURED JS secure domain names are the same; otherwise, user-defined sharing fails.)imgUrl: "Image url"(network url)} wx.ready(function(){
// Send it to your wechat friendwx.updateAppMessageShareData({ ... shareParams,success: function() {}});// Share it on momentswx.updateTimelineShareData({ ... shareParams,success: function() {}}); }); })Copy the code

Wx. error Indicates that processing through the error interface fails to verify

Wx. error(function(res){// If the config information fails to be verified, the error function will be executed. For example, the authentication fails due to the expiration of the signature. You can view the specific error information in the debug mode of config or in the returned res parameter.  });Copy the code

Judge whether users pay attention to the public number

Api.weixin.qq.com/cgi-bin/use…

Subscribe 0 indicates no concern and 1 indicates concern about the public account

There is a problem here, assume that the user didn’t pay attention to the public, (demand is forced to pay attention to the public), how to guide the user to focus on the public interface, our approach is to give the public the qr code link, it seems to be some experience is not very good, should be directly forced attention, but there is no clear WeChat guidance. Click here to get the value of __biz

conclusion

The above is the wechat API and JS interface that I used to do this wechat public account web page project. It is only the tip of the iceberg, and there are more can be viewed on the official website