H5 access to WeChat official account (super detailed)

Wechat official documents

1. Use the official account number and authenticate the developer, or apply for the test number.

be careful:
Debugging in WeChat developer tools must first become official account developers, and can be configured in the background of WeChat official account.
Location:
The official account background > settings and Development > Developer Tools > Web Developer Tools > WeChat developers to micro signal (must first pay attention to this official account to become developers).

Two, configure relevant information in the background of official account, there are two places to fill in.

1. Interface configuration information

It is not necessary to fill in here. The content of this place is used when sending messages. If it is only to call the ordinary wechat api, it is not necessary to fill in.

2. js security domain name

It must be configured here. Only the requests sent by this domain name can obtain wechat permission

Note: the domain name does not need to add http: / / or https: / /, nor does it need to add a port number. It can be an ip address

Example: 192.168 123.123; abcd.abcd.cn

3, Obtain wechat api interface authorization

To ensure security, it is recommended to obtain access_token,jsapi_ticket and signature calculation are completed by the back end

Tip: data that needs to be known in advance

1. Get access_token

Using the get request, there are three parameters: grant_type,appid,secret

Where grant_ The type value is fixed to client_credential, the other two are appID and appsecret, respectively, the official account.

// Request example
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

Note: access_ The valid period of the token is 7200 seconds

2. Get jsapi_ticket

Using the get request, there are two parameters: access_token,type

access_ The token is returned by the previous interface, and the type is a fixed value jsapi

// Request example
https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi

Note: jsapi_ The ticket is valid for 7200 seconds

3. Signature algorithm

sha1 sign the specified field

The fields are: jsapi_ticket (obtained through the above interface), noncestr (random string), timestamp (timestamp), URL (URL of the current web page, excluding # and subsequent parts)

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

Attachment: sha1 signature algorithm

export default {
  methods: {
    // Current timestamp
    timeStamp(data) {
      return parseInt(new Date(data).getTime()) + "";
    },
    // Character escape 
    encodeUTF8(s) {
      let i,
        r = [],
        c,
        x;
      for (i = 0; i < s.length; i++)
        if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
        else if (c < 0x800) r.push(0xc0 + ((c >> 6) & 0x1f), 0x80 + (c & 0x3f));
        else {
          if ((x = c ^ 0xd800) >> 10 == 0)
            //Convert four byte UTF-16 to Unicode
            (c = (x << 10) + (s.charCodeAt(++i) ^ 0xdc00) + 0x10000), r.push(0xf0 + ((c >> 18) & 0x7), 0x80 + ((c >> 12) & 0x3f));
          else r.push(0xe0 + ((c >> 12) & 0xf));
          r.push(0x80 + ((c >> 6) & 0x3f), 0x80 + (c & 0x3f));
        }
      return r;
    },
    // sha1 signature algorithm
    sha1(s) {
      let data = new Uint8Array(this.encodeUTF8(s));
      let i, j, t;
      let l = (((data.length + 8) >>> 6) << 4) + 16,
        s = new Uint8Array(l << 2);
      s.set(new Uint8Array(data.buffer)), (s = new Uint32Array(s.buffer));
      for (t = new DataView(s.buffer), i = 0; i < l; i++) s[i] = t.getUint32(i << 2);
      s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
      s[l - 1] = data.length << 3;
      let w = [],
        f = [
          function () {
            return (m[1] & m[2]) | (~m[1] & m[3]);
          },
          function () {
            return m[1] ^ m[2] ^ m[3];
          },
          function () {
            return (m[1] & m[2]) | (m[1] & m[3]) | (m[2] & m[3]);
          },
          function () {
            return m[1] ^ m[2] ^ m[3];
          },
        ],
        rol = function (n, c) {
          return (n << c) | (n >>> (32 - c));
        },
        k = [1518500249, 1859775393, -1894007588, -899497514],
        m = [1732584193, -271733879, null, null, -1009589776];
      (m[2] = ~m[0]), (m[3] = ~m[1]);
      for (i = 0; i < s.length; i += 16) {
        let o = m.slice(0);
        for (j = 0; j < 80; j++)
          (w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)),
            (t = (rol(m[0], 5) + f[(j / 20) | 0]() + m[4] + w[j] + k[(j / 20) | 0]) | 0),
            (m[1] = rol(m[1], 30)),
            m.pop(),
            m.unshift(t);
        for (j = 0; j < 5; j++) m[j] = (m[j] + o[j]) | 0;
      }
      t = new DataView(new Uint32Array(m).buffer);
      for (let i = 0; i < 5; i++) m[i] = t.getUint32(i << 2);

      let sign = Array.prototype.map
        .call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
          return (e < 16 ? "0" : "") + e.toString(16);
        })
        .join("");
      return sign;
    },
  },
};

4. Obtain wechat api permission

wx.config({
  debug: true, // Turn on debugging mode
  appId: '', // Required, the only sign of official account.
  timestamp: , // Required, time stamp to generate signature
  nonceStr: '', // Required, generate random string of signature
  signature: '',// Required, signature
  jsApiList: [] // Required, list of JS interfaces to be used
});

5. The verification is processed successfully through the ready interface
be careful:
Config information validation will execute the ready method. All interface calls must be obtained after the config interface gets the result. Config is an asynchronous operation of the client. Therefore, if the relevant interface is required when the page is loaded, the relevant interface must be put in the ready function to ensure the correct execution. For the interface called only when triggered by the user, it can be called directly without putting it in the ready function.

wx.ready(function(){
});

Wechat JS-SDK description document

6. Call the authorized api
This step is very simple. Just call it according to the official wechat document

Example:

wx.ready(function(){
	wx.getLocation({
	  type: 'wgs84', // The default is the gps coordinates of wgs84. If you want to return the Mars coordinates directly used for openLocation, you can pass in 'gcj02'
	  success: function (res) {
	    var latitude = res.latitude; // Latitude, floating point number, range 90 ~ - 90
	    var longitude = res.longitude; // Longitude, floating point number, range 180 ~ - 180.
	    var speed = res.speed; // Speed in meters per second
	    var accuracy = res.accuracy; // Position accuracy
	  }
	});
});

Keywords: Javascript Front-end html5 Vue Vue.js

Added by jacko_162 on Tue, 04 Jan 2022 07:54:26 +0200