Recently, I encountered the need for wechat built-in H5 page to customize the sharing function
Description:
It was the first time to develop the card-type sharing link. During the process, I encountered many difficulties and finally completed this function. The development process of recording may not meet your needs, but if you are also using UNIApp development, I hope this article can help you.
Effect:
Preparations:
Set JS secure domain name: Settings > Public number Settings > Function Settings; Enter the server domain name into the JS interface security domain name. (Important: the download verification file will be obtained)
Setting an IP address whitelist: Settings > Security Center >IP address whitelist. Add the server IP address to the IP address whitelist.
Note: after configuration, download the validation file and upload it to your own server root directory.
Import js files:
Plan a
/ / CMD installation
npm install jweixin-module --save
// Import the position to be imported
let jweixin = require('jweixin-module')
Copy the code
Scheme 2
// In the HTML head
<script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
// Use dom in onLoad()
var hm = document.createElement("script");
hm.src = "https://res2.wx.qq.com/open/js/jweixin-1.6.0.js";
var s = document.getElementsByTagName("script") [0];
s.parentNode.insertBefore(hm, s);
Copy the code
Verify the configuration through the config interface injection permission
The backend needs to write a signature authentication interface to return the following necessary parameters (this is compatible with your own backend, see how he gives you the processing, how to generate the signature algorithm is available in the developer documentation)
Click here: developers.weixin.qq.com/doc/offiacc…
List of all JS interfaces
Address: developers.weixin.qq.com/doc/offiacc…
All the code
// Call the page
import weixinModule from "./weixinModule.js"
onLoad() {
weixinModule.WXConfig(this);
}
Copy the code
// weixinModule.js
var jweixin = require('jweixin-module')
function WXConfig(_this){
// The URL path must not contain hash values after # (including #)
// encodeURIComponent() is used here. Why
let URL = window.encodeURIComponent(location.href.split(The '#') [0])
console.log(URL);
_this.api({
url: URL // HERE I pass the current page URL to the back end for signature
}).then(response= > {
console.log('response', response);
let res = response.data
if (res.codes === '200') {
jweixin.config({
debug: false.// 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: res.appId, ------ mandatory, the unique identifier of the public number
timestamp: res.timestamp, // Mandatory to generate the timestamp of the signature
nonceStr: res.nonceStr, // Mandatory to generate a random string of signatures
signature: res.signature, // Mandatory, signature, see Appendix 1
// List items to share: send to friends, share to moments, share to QQ, share to QQ zone
jsApiList: ["updateAppMessageShareData"."updateTimelineShareData"]}); jweixin.ready(function(){
// Share with friends
jweixin.updateAppMessageShareData({
title: 'look! Here's a handsome man. '.// Share the title
desc: 'Do you think I'm handsome?'.// Share the description
// Share link, the link domain name or path must be the same as the current page corresponding public number JS security domain name
link: 'http://your domain name /index? inviteCode=2222'.// The parameter must be the same as the configured JS secure domain name
imgUrl:'http://your domain name /images/shuai.png'.// It must be the same as the configured JS secure domain name
success: function () {}
})
})
wx.error(function(res){
If the config information fails to be verified, the error function will be executed. For example, the verification 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.
console.log("There was an error.", res); }); }})}export default {
WXConfig
}
Copy the code
Common errors and causes
Invalid signature Indicates a signature error. You are advised to check in the following order:
1. Verify that the signature algorithm is correct. (mp.weixin.qq.com/debug/cgi-b…
2. Ensure that nonceStr (js hump standard capital S) and timestamp in config are consistent with the corresponding nonceStr and timestamp in the signature.
Alert (location.href. Split (‘#’)[0])), including ‘HTTP (s)://’ part, and’? The ‘GET argument part after’, but not the ‘#’hash part.
4. Ensure that the APPID in config is the same as that used to obtain jSAPi_ticket.
5. Ensure that access_token and JSAPi_ticket are cached. (Token has been cached in request, ticket I am please depending on the situation)
6. Make sure that the URL you get for signing is dynamically retrieved. If it is a static HTML page, the URL is sent to the background through Ajax. The front-end needs to get the current page with js, except for the ‘#’hash part of the link (available with location.hre.split (‘#’)[0], and encodeURIComponent is required), because once the page is shared, the wechat client will add other parameters at the end of your link, If the current link is not obtained dynamically, the shared page will fail to be signed.
7. Most Important: Have you done your homework
Common backend errors
1. The problem of the url
The front-end URL is converted using the encodeURIComponent method and sent to the back end. The back end returns to the FORMAT of the URL www.baidu.com => Front-end format: HTTPS %3A%2F%2www.baidu.com%2F => The url received by the back end: HTTPS %3A%2F%2www.baidu.com%2F => Backend transfer format: www.baidu.com To the URL of the signature
Set JS secure domain name: Settings > Public number Settings > Function Settings; Enter the server domain name into the JS interface security domain name. After configuration, download the validation file and upload your own server root directory.
Jsapi_ticket Specifies whether the jSAPi_ticket expires
Noncestr S is lowercase and the front end is uppercase
Timestamp Time stamps are all correct
Wechat JS interface signature verification tool
Use a signature verification tool to check for expiration, timestamp issues, and signature correctness
Click view JS interface signature verification tools (mp.weixin.qq.com/debug/cgi-b…