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!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











SQL IF statements are used to conditionally execute SQL statements, with the syntax as: IF (condition) THEN {statement} ELSE {statement} END IF;. The condition can be any valid SQL expression, and if the condition is true, execute the THEN clause; if the condition is false, execute the ELSE clause. IF statements can be nested, allowing for more complex conditional checks.

Methods to solve the cross-domain problem of Vue Axios include: Configuring the CORS header on the server side using the Axios proxy using JSONP using WebSocket using the CORS plug-in

How to configure Zend in Apache? The steps to configure Zend Framework in an Apache Web Server are as follows: Install Zend Framework and extract it into the Web Server directory. Create a .htaccess file. Create the Zend application directory and add the index.php file. Configure the Zend application (application.ini). Restart the Apache Web server.

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

This article describes how to effectively monitor the SSL performance of Nginx servers on Debian systems. We will use NginxExporter to export Nginx status data to Prometheus and then visually display it through Grafana. Step 1: Configuring Nginx First, we need to enable the stub_status module in the Nginx configuration file to obtain the status information of Nginx. Add the following snippet in your Nginx configuration file (usually located in /etc/nginx/nginx.conf or its include file): location/nginx_status{stub_status

The key to PHPMyAdmin security defense strategy is: 1. Use the latest version of PHPMyAdmin and regularly update PHP and MySQL; 2. Strictly control access rights, use .htaccess or web server access control; 3. Enable strong password and two-factor authentication; 4. Back up the database regularly; 5. Carefully check the configuration files to avoid exposing sensitive information; 6. Use Web Application Firewall (WAF); 7. Carry out security audits. These measures can effectively reduce the security risks caused by PHPMyAdmin due to improper configuration, over-old version or environmental security risks, and ensure the security of the database.

Effective monitoring and defense against malicious website access is crucial to the Apache server on the Debian system. Apache access logs are the key source of information to identify such threats. This article will guide you on how to analyze logs and take defensive measures. The Apache access log that identifies malicious access behaviors Debian systems is usually located in /var/log/apache2/access.log. You can analyze the logs in a variety of ways: Log file location confirmation: First, please confirm the exact location of your Apache access log, which may vary slightly depending on the system configuration. Command line tool analysis: Use grep command to search for specific patterns, such as grep "404"

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko
