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页面
nbsp;html> <meta> <!-- 页面描述 --> <meta> <!-- 页面关键词 --> <meta> <!-- 搜索引擎抓取 --> <meta> <!-- 启用360浏览器的极速模式(webkit) --> <meta> <!-- 避免IE使用兼容模式 --> <meta> <!-- 不让百度转码 --> <meta> <!-- 针对手持设备优化,主要是针对一些老的不识别viewport的浏览器,比如黑莓 --> <meta> <meta> <!-- 优先使用 IE 最新版本和 Chrome --> <meta> <meta> <meta> <link> <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></script> <script></script> <div> <div> <div>获取微信授权(静默)</div> <div>获取微信授权(弹框)</div> <br> <div>扫一扫</div> <br> <div>获取用户信息</div> </div> <div></div> </div> <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>
下面是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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),