Node.js access_token implements WeChat access and refresh examples
This article mainly introduces examples of Node.js WeChat access_token (jsapi_ticket) access and refresh, which has certain reference value. Those who are interested can learn more about it. I hope it can help everyone.
access_token
There are two access_tokens in WeChat documents: ordinary access_token and web page authorization access_token. For specific differences, please refer to: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
The access_token mentioned below are all ordinary access_token
1. First of all Let’s first take a look at how to request access_token? WeChat public platform technical documentation
GET request: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
Normal return: {"access_token":"ACCESS_TOKEN","expires_in":7200}
Error return: {"errcode":40013,"errmsg": "invalid appid"}
2. So the code to obtain access_token is as follows:
const request = require('request') // 请安装第三方包 request request.get({ uri: 'https://api.weixin.qq.com/cgi-bin/token', json: true, qs: { grant_type: 'client_credential', appid: APPID, // APPID请换成你的 appid secret: APPSECRET // APPSECRET请换成你的 appsecret } }, (err, res, body) => { if (err) { console.log(err) return } console.log(body) if (body.errcode) { // 返回错误时的处理 return } })
3. guard_dog implements data persistence and regular refresh
guard_dog will generate .dog files, each file corresponds to a KEY
const guard_dog = require('guard_dog') // 请安装第三方包 guard_dog guard_dog.init(KEY, (handler) => { // KEY是guard_dog存取数据的键名 // 拿到数据后调用 handler handler(DATA, EXPIREDS_IN) // DATA是要持久化的数据,EXPIREDS_IN是数据的有效时间,单位是秒 }, DIR) // DIR是 .dog 文件的存放目录,这个参数可以不传
4. Now combine the above two pieces of code to get what we want The effect
const request = require('request') const guard_dog = require('guard_dog') guard_dog.init('ACCESS_TOKEN', (handler) => { request.get({ uri: 'https://api.weixin.qq.com/cgi-bin/token', json: true, qs: { grant_type: 'client_credential', appid: APPID, // APPID请换成你的 appid secret: APPSECRET // APPSECRET请换成你的 appsecret } }, (err, res, body) => { if (err) { console.log(err) return } console.log(body) if (body.errcode) { return } handler(body.access_token, body.expires_in) }) }) // 如有需要指定目录,可以再给 guard_dog.init 多传个参数
5. After guard_dog initializes this key, all valid values obtained. The code for guard_dog to obtain the value is as follows:
guard_dog.get('ACCESS_TOKEN', (data) => { // 上面初始化时用的键名为'ACCESS_TOKEN',所以这里取值也要用这个键名 // 在这里拿到的 data 就是 access_token 了 })
6. If you want to make it more convenient, you can directly encapsulate it into a module
access_token.js
const request = require('request') const guard_dog = require('guard_dog') // 加载这个模块的时候给 ACCESS_TOKEN 这个键名初始化 guard_dog.init('ACCESS_TOKEN', (handler) => { request.get({ uri: 'https://api.weixin.qq.com/cgi-bin/token', json: true, qs: { grant_type: 'client_credential', appid: APPID, // APPID请换成你的 appid secret: APPSECRET // APPSECRET请换成你的 appsecret } }, (err, res, body) => { if (err) { console.log(err) return } console.log(body) if (body.errcode) { return } handler(body.access_token, body.expires_in) }) }) // 只要向外暴露一个获取值的方法就可以了 module.exports = function (callback) { guard_dog.get('ACCESS_TOKEN', callback) }
Usage:
const access_token = require('./access_token') // 这里把这个模块与 access_token 模块当成在同一目录下来作为例子。 access_token((data) => { // 这个 data 就是 access_token })
jsapi_ticket
jsapi_ticket Official document description
The above example about access_token has been explained in detail. The processing of jsapi_ticket is also very similar, so the code is directly posted below:
(One thing to note: getting jsapi_ticket needs to rely on access_token. The following code directly relies on the above. Written in access_token.js)
jsapi_ticket.js
const request = require('request') const guard_dog = require('guard_dog') const access_token = require('./access_token') guard_dog.init('JSAPI_TICKET', (handler) => { access_token((access_token) => { request.get({ uri: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket', json: true, qs: { access_token: access_token, type: 'jsapi' } }, (err, res, body) => { if (err) { console.log(err) return } console.log(body) if (body.errcode) { return } handler(body.ticket, body.expires_in) }) }) }) module.exports = function (callback) { guard_dog.get('JSAPI_TICKET', callback) }
Use:
const jsapi_ticket = require('./jsapi_ticket') jsapi_ticket((data) => { // 这个 data 就是 jsapi_ticket })
Related Recommendation:
Development process analysis of php tree structure data access instance
Solve the garbled problem of php access mysql 4.1
The above is the detailed content of Node.js access_token implements WeChat access and refresh examples. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
