The sharing function has been implemented before, but it has not been implemented in business. Blind box products participated in this year just use the sharing function, including:

  • App share mini program/H5 to wechat friends
  • App shares pictures to moments
  • Wechat H5 share links to friends/moments
  • Applet shares applet cards with friends
  • Browsers share links to friends

In fact, most of them rely on the ability of encapsulation within the company, and many of them involve internal business, which is not convenient to elaborate here, but the principles are the same.

This article will take the common wechat sharing on the market as an example to tell about the general process, hoping to have a little inspiration for you.

How to use JSSDK

First of all, let’s take a look at the specific process in the wechat JS-SDK documentation:

Respectively is:

  • Binding domain
  • The introduction ofJSfile
  • throughconfigInterface injection permission verification configuration
  • throughreadyVerify that the interface processing succeeds
  • througherrorInterface processing failed to verify

It is easy to see that the core lies in the third step: verify the configuration through the config interface injection permission:

wx.config({
  debug: true.// If debug mode is enabled, the return value of all API calls will be displayed in the client alert. If you want to view the parameters passed in, you can open it in the PC, and the parameter information will be printed in the log.
  appId: ' '.// Mandatory, the unique identifier of the public account
  timestamp:,// Mandatory to generate the timestamp of the signature
  nonceStr: ' '.// Mandatory to generate a random string of signatures
  signature: ' '.// Mandatory, signature
  jsApiList: [] // Mandatory, a list of JS interfaces to be used
});
Copy the code

With the emphasis on signature injection permissions shown above, let’s look at how to obtain signatures.

To get the signaturesignature

By default, you now have a testable wechat official account (i.e. you have obtained the appId and Secret).

We use a picture to tease out the signaturesignatureThe process of:

Public accounts and applets can call this interface using AppID and AppSecret to obtain access_token. AppID and AppSecret can be obtained in the “wechat Public Platform – Development – Basic Configuration” page (you need to be a developer and the account has no abnormal status). Before invoking the interface, log in to wechat Public Platform – Development – Basic Configuration and add the server IP address to the IP whitelist in advance

Let’s follow the above flowchart step by step to generate the final signature

According to theappIdandsecretTo obtainaccess-token

For details about the access-token generation rule, see obtaining an Access Token

Is to actually get to request https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET, Replace appId and Secret in the URL with your own.

Normally this returns:

{"access_token":"ACCESS_TOKEN"."expires_in":7200}
Copy the code

Expires_in indicates that the validity period is 2h. It must be reacquired when the expiration date is exceeded.

Take a look at the code implementation:

/** * Obtain access_token **@returns* /
async function genWxAccessToken() {
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${secret}`;
  const response = await axios.get(url);
  const result = response.data || {};
  if (result.access_token && result.expires_in) {
    console.log("Wechat access_token generation succeeded");
    return result;
  }

  console.log("Failed to generate wechat access_token".JSON.stringify(result));
  return null;
}
Copy the code

According to theaccess-tokenFurther acquisitionticket

Here, similar to the previous step, the structure returned on success is:

{
  "errcode":0."errmsg":"ok"."ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA"."expires_in":7200
}
Copy the code

Specific code implementation:

/** * Obtain ticket **@param {*} accessToken
 * @returns* /
async function genWxTicket(accessToken) {
  const url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`;
  const response = await axios.get(url);
  const result = response.data || {};
  // result Correct format {errCode: 0, errmsg: 'OK ', ticket:' XXX ', expiRES_in: 7200} Validity period 2h

  if (result.errcode === 0) {
    console.log("Wechat ticket generated successfully");
    return result;
  }
  console.log("Failed to generate wechat ticket".JSON.stringify(result));
  return null;
}
Copy the code

According to theticket,nonceStr,timeStampandurlTo get the signature

Let’s take a look at the signature algorithm:

  • The fields participating in the signature includenoncestr(random string), validjsapi_ticket.timestamp(Timestamp),url(The current pageURL, does not contain#And the rest)
  • For all parameters to be signed according to the field nameASCIICode sorted from smallest to largest (lexicographical order) after useURLThe format of key-value pairs (i.eKey1 = value1 & key2 = value2...) concatenated to a stringstring1
  • rightstring1As asha1Encryption, the field name and field value use the original value, do not performURLescape

The signature = sha1 (string1)

We use Crypto to implement SHA1:

const { createHash } = require("crypto");

/** * Unified encryption algorithm **@param {*} Algorithm Encryption algorithm *@param {*} Content Source content *@returns* /
function encrypt(algorithm, content) {
  const hash = createHash(algorithm);
  hash.update(content);
  return hash.digest("hex");
}

/** * sha1 encryption **@param {*} content
 * @returns* /
function sha1(content) {
  return encrypt("sha1", content);
}
Copy the code

Then follow the above signature algorithm to generate the signature:

const timestamp = parseInt(Date.now() / 1000.10);
const nonceStr = Math.random().toString(36).slice(-8);
/** * Generate signature **@param {*} ticket
 * @param {*} NonceStr Random string *@param {*} Timestamp Indicates the time *@param {*} Url The current full URL *@returns* /
function genSignature(ticket, nonceStr, timestamp, url) {
  // key1=val1&key2=val2, the key value and order must be as follows
  // Sort by the ASCII characters of the field name from smallest to largest
  const str = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
  const sign = sha1(str);
  return sign;
}
Copy the code

throughreadyVerify that the interface processing succeeds

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.

Here is the sharing behavior, which needs to override the default sharing logic when the page loads:

wx.ready(() = > {
 // Customize the share content of "Share to friends" and "Share to QQ" buttons
  wx.updateAppMessageShareData({
    title: ' '.// Share the title
    desc: ' '.// Share the description
    link: ' '.// Share link, the link domain name or path must be the same as the current page corresponding public number JS security domain name
    imgUrl: ' '.// Share ICONS
    success: function () {
      // The setting succeeded}});// Customize the share content of "Share to moments" and "Share to Qzone" buttons
  wx.updateTimelineShareData({
    wx.updateTimelineShareData({
    title: ' '.// Share the title
    link: ' '.// Share link, the link domain name or path must be the same as the current page corresponding public number JS security domain name
    imgUrl: ' '.// Share ICONS
    success: function () {
      // The setting succeeded}})}); });Copy the code

When generating access-token and ticket, wechat official documents mentioned a very important point: cache. Because the number of API calls is limited, frequent refreshing will restrict API calls and affect their own services. Therefore, developers must cache ticket and Access-Token globally in their own services. Because the generation logic is handled on the server side, redis can be used for caching.

Make a summary

In fact, here, wechat sharing about the process and realization of my summary. The whole process is quite complicated. I remember that when I went to see it for the first time two years ago, I was really confused. This year, I picked it up again and looked at it carefully.

Objectively speaking, wechat official documents are very detailed, many students feel very headache because his process is really a bit troublesome 😂

And many students from the beginning of the beat back, not only sharing, like the usual upload, many students do for the first time will feel good trouble, but as long as you carefully look at the document, seriously study, these are not difficult. A lot of times it’s a matter of experience.