This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging
Long Long Ago used wechat authorization to obtain user information and share, fell pit countless times, hence made this article.
In this article, from the information obtained by wechat authorization to how to carry out wechat authorization and wechat sharing, some code practices only realize the basic functions, if you need to customize the development, please carry out secondary development on this basis.
More articles on my Github and personal public number [Whole cliff Road], welcome to watch [front knowledge points], if there is benefit, don’t pay, little hands point a Star
Read this article
- Wechat authorized access to information
- How to realize wechat authorization in front
- Front-end how to achieve wechat sharing
What can WECHAT authorization get
- Basic information obtained through wechat authorization
- The basic information includes the user’s display information, including but not limited to the nickname, gender, address, profile picture and other information.
{" openid ":" XXX, XXX, "" unionid" : "XXXX", "nickname" : "nickname", "sex" : 1, / / 1:2: Women "language" : "zh_CN", "city" : "jinan", "province", "shandong province", "country" : "Chinese", "headimgurl" : "HTTP: XXXXXXXX", "privilege" : []}Copy the code
openid
andunionid
The difference between- Under different public accounts
openid
Is not the same as theirsunionid
But it’s the same - The official account will be acquired only after it is tied to an account on wechat’s open platform
UnionID
. As long as it is an official account under the same wechat open platform account, the user’sUnionID
It’s unique. In other words, the same user, different applications under the same wechat open platform account,UnionID
Is the same
- Under different public accounts
Project situation
Technology selection
- Project language: HTML, CSS, JavaScript
- Project framework: vue.js
- Project scaffolding: vue-CLI
- Engineering tools: Webpack, Npm
- Source code management: Gitlab
- Operating environment: WeChatBrowser
- Third-party service: wechat JS-SDK
The project requirements
- Wechat authorizes access to user information
- Wechat sharing statistics
- The submission form carries part of the wechat information
The following technical implementation methods and solutions are based on the public account has been assigned the relevant authorization and permission, the specific authorization and permission application please see the wechat official document, not to be detailed here
Wechat Authorization (Authorization scheme based on public account)
- At present, the Internet is mostly divided into two ways to obtain wechat authorization, one is the front-end leading wechat authorization, the other is the server leading wechat authorization, the two ways to achieve the result is the same, the specific way to choose according to their own project
Authorization method
- Authorization mode for client transfer (picture from network)
- A completely server-side authorization mode
- The server-side authorization front-end is developed with minimal effort, and the basic authentication is done on the server, which is not covered in this article.
Authorization process
- Authorization mode for client transfer
- Wechat users enter the page (dynamic URL needs to obtain the authorized address from the server in advance)
- Client portability
redirect_uri
Send an authorization request to the wechat server - Wechat server authorization will carry one
code
inurl
On the back - The client carries it
code
Send the request to the server - The server returns user information
- A completely server-side authorization mode
Client transfer authorization mode technology implementation
- Obtain wechat authorization
code
- Use the current URL; otherwise, authentication fails.
let redirectUri = encodeURI(window.location.href) window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=${redirectUri}&response_type=code&scope=snsa pi_userinfo&state=123#wechat_redirect`Copy the code
- carry
code
Obtain user authorization from the server- Wechat will be authorized after authorization
code
On theurl
Of the parameters, the front end only needs to be inurl
To get the authorizationcode
It can be used to verify related information and obtain user data with the server.
- Wechat will be authorized after authorization
Let code = getQuery(window.location.href).code // Return the code to the backend to get the authorized information axios.get("/ XXX /getWxInfo? code=" + code).then(res => { if (res && res.data && res.data.code == 10000) { this.userInfo = res.data.data // LocalStorge is stored in the wechat side, but there is a problem. SetCookie ('userInfo', this.userinfo); setCookie('userInfo', this.userinfo); }else {alert(' wechat authorization failed, please re-open the article ', res.code)}}).catch(error => {this.userinfo = "alert(' wechat authorization failed, please re-open the article ', res.code)}}).catch(error => {this.userinfo =" alert(' wechat authorization failed, Please open ', res.code) console.log(' error obtaining wechat authorization ', error)})Copy the code
- The authorization is successful. At this time, the user’s wechat authorization information and personal information have been obtained
WeChat share
Sharing process
- Get wechat sharing authorization
- Customize share title, share summary, share picture, and write wechat configuration (
wx.config
) - Call the share interface (
wx.ready
) - Share success
Wechat sharing technology implementation
- Wechat sharing is a frequently called method, the implementation process can be abstracted, encapsulated
Function $setShare(options) {axios.get('/ XXX /getWxSignature? url=' + encodeURIComponent(location.href.split('#')[0])).then(function(resp) { if (! resp || ! resp.data || resp.data.code ! = 10000) { return } wx.config({ appId: resp.data.data.appid, timestamp: resp.data.data.timestamp, nonceStr: resp.data.data.noncestr, signature: resp.data.data.signature, jsApiList: [" onMenuShareTimeline onMenuShareAppMessage ", ""]}) var shareTimeLineData = options | | {title: 'share title, desc: 'share the link: "', imgUrl: "',} var shareAppData = options | | {title: 'share title, desc:' sharing the 'link: '', imgUrl:'', } wx.ready(function() { wx.onMenuShareAppMessage(shareAppData); wx.onMenuShareTimeline(shareTimeLineData); }); Wx.error (function(res){console.log(' share license failed ', res)})},function(err){if (err){alert(err); }else{alert(' Network error, please try again later! ')}}); }Copy the code
- Call the shared code implementation
- The wechat share callback is not a successful share callback, but a user clicks on the share callback, the existing version of wechat does not tell the developer whether the user shared successfully
Let shareWxData = {title: 'test wechat share title ', desc:' test wechat share abstract ', link: window.location.href, imgUrl: 'XXXXXXX ', success: function(res) {} } $setWxShare(shareWxData)Copy the code
Write in the last
If you find this article helpful, please like it and share it with more people who need it!
Welcome to pay attention to [Quanzhendaolu] and wechat public account [Quanzhendaolu], to get more good articles and free books!
There is a need [Baidu] & [bytedance] & [JD] & [ape counselling] within the push, please leave a message oh, you will enjoy the VIP level extreme speed within the push service ~
Past oliver
Create a personalized Github profile
The interviewer asks you<img>
What elements do you say
Special JS floating point number storage and calculation
Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future
Front end practical regular expression & tips, all throw you 🏆 nuggets all technical essay | double festival special articles
HTML Tabindex
A few lines of code to teach you to solve wechat poster and TWO-DIMENSIONAL code generation
Vue3.0 Responsive data principle: ES6 Proxy
Read on to make your interviewer fall in love with you
How to draw a fine line gracefully
Front-end performance optimization -HTML, CSS, JS parts
Front-end performance optimization – Page loading speed optimization
Front-end performance optimization – Network transport layer optimization