Before, I shared the details page of a news project on wechat twice, which was a little painful in the development stage. The blogs that Google visited were half and half, and I was not familiar with the configuration of wechat public account, so I took many detours. Now I am slowly sorting it out.
Wechat secondary sharing needs to rely on the configuration of the public account, so that after the H5 page is shared, others will see not just a simple page title and a URL, but can customize the title, content and icon with a certain degree of beauty of the share block.
1. Obtain information about the test number
Enter WeChat public account test application system (mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index)
Just to test this document forward, just get the “test number information” and configure the “JS interface security domain name”.
2. Signature algorithm
With the above two pieces of information, you can complete a “signature algorithm” service
/ / express
app.use('/sdWxService'.async function (req, res, next) {
const {url} = req.query;
const access_token = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${AppID}&secret=5397a76acffd10116413dbd741849c1c`).then(
(res) = > {
const {access_token} = res.data;
return access_token;
});
const ticket = await axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`).then((res) = > {
console.log(res.data)
return res.data.ticket;
});
let noncestr = uuidv4();
let jsapiTicket = ticket
let timestamp = moment().unix().toString()
// Noncestr is all lowercase
let string = `jsapi_ticket=${jsapiTicket}&noncestr=${noncestr}×tamp=${timestamp}&url=${url}`
let signature = crypto.createHash('sha1').update(string).digest('hex')
res.json({
status: 200.data: {
jsapiTicket,
appId: AppID,
timestamp,
nonceStr: noncestr, // Note the case here
signature,
}
})
});
Copy the code
There are several common problems that need to be noted
- Timestamp and nonceStr must both be strings
- Ensure that the APPID in config is the same as the appID used to obtain jSAPi_ticket
- If it’s an official public, be sure to cache access_token and JSAPi_ticket (test numbers don’t care about that for now)
- Timestamp is a 10-bit timestamp
- Timestamp The value is the same as the timestamp in the signature
- Note url: The URL that is not escaped and signed must be the complete URL that calls the JS interface page
- Verify that the URL is the full URL of the page (check the current page alert(location.hre.split (‘#’)[0])), including ‘HTTP (s)://’ part, and’? The ‘GET argument part after’, but not the ‘#’hash part.
- The front-end needs to get the current page with js, excluding the ‘#’hash part of the link (available with location.hre.split (‘#’)[0], and encodeURIComponent is required
- Note: noncestr, when stitching the signature string, this key is all lowercase; However, when the front end is configured in config, nonceStr of the hump is required
- To eventually produce information can use WeChat JS interface signature verification tools (mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign)
- About the interface signature calibration tool But still gave people the wrong, be sure to carefully check the above several matters needing attention, and developers.weixin.qq.com/doc/offiacc…
3. Configure H5
First of all, the page should introduce wechat SDK, there are two ways, here also incidentally posted:
Methods a
< script SRC = "/ > http://res.wx.qq.com/open/js/jweixin-1.2.0.jsCopy the code
Way 2
npm install weixin-js-sdk
/* Use the CommonJs specification to introduce */
const wx = require('weixin-js-sdk');
/* Use the ES6 module to introduce */
import wx from 'weixin-js-sdk';
Copy the code
- H5 shares module code
import wx from 'weixin-js-sdk';
import axios from 'axios';
import moment from 'moment';
import _ from 'lodash';
const url = encodeURIComponent(window.location.href);
const getSignature = () = >
axios
.get(
` http://192.168.0.106:4003/sdWxService? url=${url}`,
)
.then(res= > res.data);
export default async function initWeChat() {
const {
signature,
nonceStr,
timestamp,
appId,
jsapiTicket,
} = await getSignature();
wx.config({
// debug: true, // Enable the debug mode, the return value of all API calls will be displayed in the client alert, to view the passed parameters, you can open the PC, parameter information will be printed in the log, only on the PC.
appId, // Mandatory, the unique identifier of the public account
jsApiList: [
'checkJsApi'.'onMenuShareTimeline'.'onMenuShareAppMessage'.'onMenuShareQQ'.'onMenuShareWeibo',
],
nonceStr, // Mandatory to generate a random string of signatures
signature, // Mandatory, signature
timestamp, // Mandatory to generate the timestamp of the signature
});
}
export const updateWeChatShareData = () = > {
initWeChat();
// TODO:Confirm the picture link provided by Hua 'an
const wxShareData = {
title: 'Active page'.// Share the title
desc: 'Active Page --111'.// 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:
'https://res.wx.qq.com/a/wx_fed/assets/res/OTE0YTAw.png'.// Share ICONS
};
wx.ready(() = > {
// It needs to be called before the user clicks the share button
wx.updateAppMessageShareData(wxShareData);
wx.updateTimelineShareData(wxShareData);
wx.onMenuShareAppMessage(wxShareData);
wx.onMenuShareTimeline(wxShareData);
});
};
updateWeChatShareData();
Copy the code
In the final screenshot of the shared result (debugging screenshot in wechat developer tool), it can be seen that the shared title has been set to the title value defined in the H5 module.
Another case is to prohibit sharing of pages in wechat, refer to the following code snippet
This method seems to have a problem, weixinjsbridge-call will report an error, use the following method
function onBridgeReady() {
window.WeixinJSBridge.call('hideOptionMenu');
}
if (typeof WeixinJSBridge === 'undefined') {
if (document.addEventListener) {
document.addEventListener(
'WeixinJSBridgeReady',
onBridgeReady,
false,); }else if (document.attachEvent) {
document.attachEvent(
'WeixinJSBridgeReady',
onBridgeReady,
);
document.attachEvent(
'onWeixinJSBridgeReady', onBridgeReady, ); }}else {
onBridgeReady();
}
Copy the code
Wx.ready (() => {}); wx.ready(() => {}); wx.ready(() => {}
wx.hideMenuItems({ menuList: [ 'menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:share: Facebook ', 'menuItem: Share :QZone', 'menuItem:favorite',], // To hide menu items, only hide "Spread class" and "Protect class" buttons, all menu items see Appendix 3});Copy the code
It can also be displayed dynamically
wx.showMenuItems({ menuList: [ 'menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:share: Facebook ', 'menuItem: Share :QZone', 'menuItem:favorite',], // To hide menu items, only hide "Spread class" and "Protect class" buttons, all menu items see Appendix 3});Copy the code
JsApiList in wx.config requires hideMenuItems and showMenuItems to be configured