Home > Article > Web Front-end > How to use node.js to obtain WeChat user authorization (code attached)
The content of this article is about how to use node.js to obtain WeChat user authorization (with code). It has certain reference value. Friends in need can refer to it. I hope It will help you.
This article mainly describes how to open your own page in WeChat and pop up a window to request user authorization in order to get the user's WeChat information.
First of all, let’s talk about the process from scratch to complete custom sharing information:
Basic hardware service:
Requires a valid domain name that can be accessed by the public network:
Purchase the domain name and register it. I purchased it from Alibaba Cloud. The registration process takes more than ten working days.
Purchase an IP, then set the domain name above and resolve to the IP. This time can be ignored.
Have your own server to store your own page projects:
I still buy the server from Alibaba Cloud. This is the most expensive, with a few hundred yuan for the right to use it for a year.
And this server is essentially a computer, and it has configurations. I am currently just learning to use it myself, and the configuration is almost the lowest. Moreover, the package I purchased comes with a public network IP, so I can connect The money for purchasing IP above is also saved.
To sum up, in the end I only purchased a domain name and a server with a public IP address. The server is used to place front-end projects and back-end projects.
Alibaba Cloud ECS: https://cn.aliyun.com/product/ecs
WeChat public platform, developer certification
Open the WeChat public platform https:// mp.weixin.qq.com/, use email to register. Note that one email can only register one WeChat public platform account, and one account can only choose one account category and cannot be changed. You must be careful here and choose a subscription account here.
Optional personal type, enterprise type, etc. Among them, the personal type does not have shared customization functions, but I do not meet the enterprise type. . . In the end, I chose the personal type, because even if my account does not have permissions, there is a fully functional test account in the WeChat public account. You can use the test account to study and test, which is still no problem.
Fill in the information, bind WeChat, complete the registration, and log in.
In order to carry out development, you need to configure the corresponding configurations here with your back-end projects and front-end projects, and let WeChat confirm that the back-end projects and front-end projects are yours before providing services.
Configuration of server-side and backend projects:
First of all, it needs to be explained that since the subscription account has relatively few functions, if you are just learning, it is recommended to choose to use it in the development=> developer tools The public platform test account is developed for learning, so that the full-featured WeChat service can be used and the configuration is relatively small.
The following configuration steps are all required to use your own account
Development=> Basic configuration=> Official account development information, write down the developer ID (AppID) here , then activate the service and write down the developer password (AppSecret), which will be required during development.
Set the IP whitelist. What is written here is your own server IP address, because after the function is online, you need to use this server to obtain the access_token of your own service from the WeChat service area through the developer ID and password
Carry out the following background project in order to let WeChat determine that this background project is yours. The verification method is that WeChat initiates a get request and you return the correct return value. When this configuration is enabled, call:
url: interface address, such as http://wx.my.com/forWx
Token: a completely customized string, equivalent to a password. Your return value requires this string to participate in assembly.
EncodingAESKey: Randomly generated
Message encryption and decryption method: optional, here I use the plain text mode
Configuration of the front-end project:
Settings=> Official Account Settings=> Function Settings=> JS Interface Security Domain Name Add here the domain name of the website you want to use the WeChat SDK function, such as wx.qq.com or wx.qq.com/user, You can write up to three entries, and verification is required.
> The verification method is to place a txt file provided by WeChat in the access root directory of the web project placed on the server corresponding to this domain name. It needs to be combined with the main file (most defaults to " index.html") at the same level. When submitted, WeChat will access it to obtain the file and confirm that this domain name is yours.
After the configuration is completed, development can begin.
Now enter the code stage.
My own proof of backend projects and front-end projects
First of all, the above proves that the service is its own part. We need to implement an interface. I use http://wx.my.com/ Using forWx as an example, in order to enable configuration, I need to implement /forWx to call WeChat. The following is the code:
The basic environment construction of node is omitted. Only the internal methods of the interface are written here. The key is parameter encryption assembly
const crypto = require('crypto') // 引入加密模块 const config = require('./config') // 引入配置文件 // 提供给微信调用 server.get('/forWx', function (req, res) { res.header('Access-Control-Allow-Origin', '*') // 1.获取微信服务器Get请求的参数 signature、timestamp、nonce、echostr let signature = req.query.signature // 微信加密签名 let timestamp = req.query.timestamp // 时间戳 let nonce = req.query.nonce // 随机数 let echostr = req.query.echost // 随机字符串 // 2.将token、timestamp、nonce三个参数进行字典序排序,其中token就是设置在微信页面中的那个自定义字符串 let array = [config.token, timestamp, nonce] array.sort() // 3.将三个参数字符串拼接成一个字符串进行sha1加密 let tempStr = array.join('') const hashCode = crypto.createHash('sha1') //创建加密类型 let resultCode = hashCode.update(tempStr, 'utf8').digest('hex') //4.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 if (resultCode === signature) { res.send(echostr) } else { res.send('mismatch') } })
Completed, the above is to prove that the server is mine, and later I need to prove that the front-end project is mine. I skip this because it is too simple. Just download the file and put it in your own server. The front-end project is index.html can be of the same level
The above operations are the necessary steps and the basis for everything if you want to develop WeChat public pages.
首先顺着功能使用流程,顺一下实现此功能的方法:
用户在微信打开页面后,立即或者通过方法触发ajax,把当前url和一些state(自定义的数据,因为弹窗请求用户授权,是需要跳转页面的,这个state就是会帮你带到下个页面链接中的数据)作为请求参数,请求自己的后台接口。
后台请求微信服务器,把以下作为参数,拼装到某个固定的微信指定的url后,返回给前端,参数为:
appId:自己的AppId
redirect_uri:前端给的url
scope:授权方式,是静默授权(只能获取用户openId)还是弹窗授权(能获取用户微信个人信息)
state:要带到新页面的参数
前端拿到后端拼好的这个url,直接window.location.href暴力跳转
如果静默授权,则直接用户无感,如果是弹窗授权,则新页面(微信方提供的页面)会弹窗询问用户,是否授权
用户同意授权后,微信再次跳转页面,即跳转到之前传的你的url地址中,还会把state参数给你带上,此外,还多了个code参数,即openId
新页面中,可以使用用户的openId,再加上自己的AppId和AppSecret,调用微信的接口,获取用户的access_token
最后再使用用户的openId和access_token,成功获取用户信息
下面是前端获取微信授权的...html页面
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- 页面描述 --> <meta name="description" content=""/> <!-- 页面关键词 --> <meta name="keywords" content="" /> <!-- 搜索引擎抓取 --> <meta name="robots" content="index,follow"/> <!-- 启用360浏览器的极速模式(webkit) --> <meta name="renderer" content="webkit"> <!-- 避免IE使用兼容模式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- 不让百度转码 --> <meta http-equiv="Cache-Control" content="no-siteapp"/> <!-- 针对手持设备优化,主要是针对一些老的不识别viewport的浏览器,比如黑莓 --> <meta name="HandheldFriendly" content="true"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"> <!-- 优先使用 IE 最新版本和 Chrome --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> <link rel="shortcut icon" type="image/x-icon" href="../static/favicon.ico"> <title>微信</title> <style> html, body { background-color: skyblue; font-size: 16px; height: 50%; width: 100%; } #index { padding: 10px; } #index .box > div { cursor: pointer; background-color: #fff; display: inline-block; padding: 5px; margin: 10px; } #index .box .getUserInfo { display: none; } </style> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script> </head> <body> <div id="index"> <div class="box"> <div class="initOauth2" type="snsapi_base">获取微信授权(静默)</div> <div class="initOauth2" type="snsapi_userinfo">获取微信授权(弹框)</div> <br> <div class="wxSweep">扫一扫</div> <br> <div class="getUserInfo">获取用户信息</div> </div> <div class="userInfo"></div> </div> </body> <script> let BASE_URL = 'http://wxtestapi.junlli.com' // 获取 url 参数 const getValue = () => { let flag = decodeURI(window.location.search.substr(1)); if (!flag) return undefined let arr = flag.split('&') if (arr.length <= 0) return undefined let obj = {} for (let i = 0; i < arr.length; i++) { let tempArr = arr[i].split('=') obj[tempArr[0]] = tempArr[1] } return obj } let urlParams = getValue() let code // 判断是否有code if (urlParams && urlParams.code) { code = urlParams.code $('.getUserInfo').css('display', 'inline-block') } $('.getUserInfo').on('click', function() { if (!code) return alert('请重新获取授权') $.ajax({ url: BASE_URL + '/getUserInfo', type: 'post', data: { code, }, success: function(data) { console.log(data) $('.userInfo').html(JSON.stringify(data)) }, error: function(error) { console.log(error) alert('请重新获取授权') } }) }) // 获取微信授权 $('.box .initOauth2').on('click', function() { wxInitOauth2($(this).attr('type')) }) // 初始化 微信授权 wxInitOauth2 = type => { let url = window.location.origin + window.location.pathname console.log('url', url) $.ajax({ url: BASE_URL + '/getOauth2', type: 'post', data: { url, type, state: 'abcde' }, success: function(data) { // 去跳转 window.location.href = data.url // console.log(data) }, error: function(error) { console.log(error) }, }) } </script> </html>
下面是node后台代码
const config = require('./config') // 引入配置文件 // 通过 code 获取用户的 openId 和 access_token const getOpenIdAndAccessToken = code => { let params = { appid: config.appId, secret: config.appSecret, code, grant_type: 'authorization_code' } let url = `https://api.weixin.qq.com/sns/oauth2/access_token?${qs.stringify(params)}` return new Promise((resolve, reject) => { request(url, function (error, res, body) { if (res) { let bodyObj = JSON.parse(body) resolve(bodyObj); } else { reject(error); } }) }) } // 获取用户信息 const getUserInfo = ({ access_token, openid }) => { let params = { access_token, openid, lang: 'zh_CN' }; let url = `https://api.weixin.qq.com/sns/userinfo?${qs.stringify(params)}` return new Promise((resolve, reject) => { request(url, function (err, res, body) { if (res) { resolve(JSON.parse(body)) } else { reject(err); } }); }) } // 获取微信授权 --- code server.post('/getOauth2', (req, res) => { try { let params = req.body let redirect_uri = params.url let state = params.state let type = params.type // 第一步:用户同意授权,获取code // type:snsapi_base // 不弹出授权页面,直接跳转,只能获取用户openid // type:snsapi_userinfo // 弹出授权页面,可通过openid拿到昵称、性别、所在地 var scope = type // 弹出授权页面,拿到code let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.appId}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}${state ? '&state=' + state : ''}#wechat_redirect` res.send({ url }); } catch (error) { res.send(error) } }) // 获取用户个人信息 server.post('/getUserInfo', (req, res) => { try { let params = req.body let code = params.code // 先用 code 换取 openId 和 access_token getOpenIdAndAccessToken(code).then(obj => { // 用 openId 和 access_token 获取个人信息 getUserInfo(obj).then(data => { res.send(data) }).catch(error => res.send(error)) }).catch(error => res(error)) } catch (error) { res.send(error) } })
整体功能实现的步骤和具体代码如上,请酌情参考。
The above is the detailed content of How to use node.js to obtain WeChat user authorization (code attached). For more information, please follow other related articles on the PHP Chinese website!