Teach you the development of wechat public number
A lot of people will certainly wonder, why people have a document not to see, must see you this? Originally also do not intend to write this article, that day in the nuggets have a digging friends sent a boiling point, roughly means that the public number development can also count as a technology (because the public number web page development document readability is poor). Sometimes see technical group many people also ask questions; So write about wechat authorized login and wechat sharing and wechat payment.
Preparation before development
If you want to do a good job, you have to sharpen your tools first. Let’s prepare some necessary things first, and then we can start the development process. First need to register the enterprise wechat public account, and then bind developers, download development tools.
Registered account
- Register wechat public number, generally choose the service number (specific business scenarios), input relevant information to submit, this is relatively simple, will not expand the narrative.
Bind developer account
-
1. Log in to wechat Developer platform, find Development -> Developer Tools on the left menu bar, and click enter.
-
2. Click the Web Developer tool to bind our developer wechat account, which is convenient for debugging later.
Download the development debugging tool
- Click to enter the wechat development and debugging tool download page, select the version to download, by now, our preparation for development is completed.
Wechat authorized login
After the preparation work is finished, we can begin to develop, the general public number development must do wechat web page authorization, share to friends, share to circle of friends, part of the wechat payment function. Let’s share the process of wechat web page authorization development.
Secure Domain name Settings
- 1. Log in to the background of the official account and find the following information in the left menu bar:
Set up the
–>Public Account setting
Enter the page and selectFeature set
, configure itJS Interface security domain nameandWeb authorized domain name, the configuration rules are as follows:
The configuration of | The rules | use |
---|---|---|
JS Interface security domain name | The domain name must be verified by ICP registration and must be downloadedMP_verify_jhf9FhUVRNDnBE96.txt Put it in the root directory pointing to the configured domain name |
Pages under this domain name will not be reformatted when accessed in wechat. No security prompt is displayed when users enter the domain name |
Web authorized domain name | Need to be!MP_verify_jhf9FhUVRNDnBE96.txt To the root directory of the domain name |
This parameter must be configured for wechat web page authorization |
The login process
- Wechat login process:
- The front-end key code is as follows (for writing convenience, request to use here
jquery
the$ajax
) :
<script>
// Get address bar parameters
function GetURL(name) {
var reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)");
var r = window.location.search.substr(1).match(reg);
if(r ! =null) return unescape(r[2]);
return null;
};
// Get the code parameter in the URL
let code = GetURL('code');
// If there is no code, go to the authorization page for authorization
if(! code){let url = window.location.href;
let appid = 'abckdeh129292'; // Public account appID, which can be viewed in the background of wechat public account
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri=' + url + '&response_type=code&scope=snsapi_base&state=123#wechat_redirect';
}
// If there is code
$.ajax({
url: "https://test.abcd.com/api/WXUserInfo".data: { code,},
type: "get".dataType: "json".success: function (res) {
//code is available to get user information
if (res.status) {
userInfo = res.data;
}else{
// Code has expired and needs to be reauthorized
window.location.href = 'http://test.abcd.com/juejin/index.html'}}); });</script>
Copy the code
-
Parameter description: about to jump to the authorization page splicing parameters, here is not to say, interested can see 👉 official documents
-
Common return error codes:
- 10003 Check whether the background callback domain name is correctly configured
- The 10005 public account does not have this capability
- 10009 operates frequently. This has little to do with the front end. Check the logic on the back end
The user information
- The corresponding description of the user information returned by wechat is as follows. There are several points that need to be noted. Transcoding is required when the back-end saves the user nickname, because some users’ wechat nickname isexpression, followed by if the public page wants to communicate with the small program page user information, you need to take
unionid
When the unique ID, while the applets to obtain user information also need to saveunionid
.
The parameter name | describe |
---|---|
openid | Unique identification of a user |
nickname | User’s nickname |
sex | Gender of the user. If the value is 1, it is male, if the value is 2, it is female, and if the value is 0, it is unknown |
province | Province where the personal information is filled in |
city | The city where the personal information of ordinary users is filled in |
country | Countries, such as China, are CN |
headimgurl | The avatars |
privilege | User privilege information |
unionid | The user id |
Share it with your friends. Share it on moments
We must have seen wechat to friends in the web page with titles, introductions and thumbnails, so that users do not enter the page about some information about the page. Here is to write a share to wechat friends and share to the moments, other can see 👉 official documents. Js-sdk examples can be accessed within wechat 👉 example demo.
The development process
-
1. Configure the JS secure domain name (the specific configuration method is described above).
-
2. Introduction of js – SDK
// Add jS-SDK to the page
<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
// Vue and React can also be installed as pluginsNPM install weixin-js-sdk or yarn add weixin-js-sdkCopy the code
- 3. Verify the configuration by using the injection permission of the Config interface and check whether the processing succeeds or fails
// Get the config interface injection permission validation parameters, which are returned by the back end
$.ajax({
url: "https://test.abcd.com/api/wxconfig".data: { url:window.location.href},
type: "get".dataType: "json".success: function (data) {
//
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: data.appId, // Mandatory, the unique identifier of the public account
timestamp: data.timestamp, // Mandatory to generate the timestamp of the signature
nonceStr: data.nonceStr, // Mandatory to generate a random string of signatures
signature: data.signature,// Mandatory, signature
jsApiList: ['updateAppMessageShareData'.'updateTimelineShareData',] // Mandatory, need to use the JS interface list if you want to share to friends and to share to moments write these two
});
// configure the verification success handler
wx.ready(function(){
const link = "www.test.com/index.html",
title = 'Nuggets invite you to punch in.',
desc = 'Nuggets invite you to participate in the punch card activity, rich prizes, come and see! ',
imgUrl = 'http://www.test.com/images/share.jpg';
// Share with friends
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 () {
// Set the success handler}});// Share it on moments
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 () {
// Set the success handler}})});// Configure the failed 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.
});
});
});
Copy the code
⚠️ Precautions
-
During debugging, enable the DEBUG function. Otherwise, no message is displayed after a failure. Most common errors are caused by back-end signature calculation problems.
-
Wechat JS-SDK has nothing to do with wechat webpage authorization, so you can use jS-SDK without authorization.
-
The success processing function of wechat sharing only means that the user clicks the share button, but does not mean that the user really shares with friends. As long as the user clicks the share in the upper right corner, the success function will be executed. Generally, encouraged sharing carries parameters after sharing, and relevant business processing will be conducted after users share and friends enter.
At the end
I was going to write about wechat Payment, but it will be a long article, so I will write it next time. Let me know in the comments section if you have any questions. Welcome to 👉 Focus on front-end 365: Share front-end tips and problems during development. Remember to follow + favorites + like, soon to LV3, thank you for your support ~