Home Web Front-end JS Tutorial Node.js access_token implements WeChat access and refresh examples

Node.js access_token implements WeChat access and refresh examples

Jan 27, 2018 pm 02:46 PM
access javascript node.js

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
  }
})
Copy after login

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 文件的存放目录,这个参数可以不传
Copy after login

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 多传个参数
Copy after login

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 了
})
Copy after login

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)
}
Copy after login

Usage:


const access_token = require('./access_token') // 这里把这个模块与 access_token 模块当成在同一目录下来作为例子。
access_token((data) => {
 // 这个 data 就是 access_token
})
Copy after login

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)
}
Copy after login

Use:


const jsapi_ticket = require('./jsapi_ticket')
jsapi_ticket((data) => {
 // 这个 data 就是 jsapi_ticket
})
Copy after login

Related Recommendation:

Development process analysis of php tree structure data access instance

Solve the garbled problem of php access mysql 4.1

PHP implements the effect of encrypting text files and restricting access to specific pages_php example

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
How to use sql if statement How to use sql if statement Apr 09, 2025 pm 06:12 PM

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.

How to solve the 'Network Error' caused by Vue Axios across domains How to solve the 'Network Error' caused by Vue Axios across domains Apr 07, 2025 pm 10:27 PM

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 for apache How to configure zend for apache Apr 13, 2025 pm 12:57 PM

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.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

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.

How to monitor Nginx SSL performance on Debian How to monitor Nginx SSL performance on Debian Apr 12, 2025 pm 10:18 PM

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

Summary of phpmyadmin vulnerabilities Summary of phpmyadmin vulnerabilities Apr 10, 2025 pm 10:24 PM

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.

How to identify malicious access in Debian Apache logs How to identify malicious access in Debian Apache logs Apr 13, 2025 am 07:30 AM

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"

Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

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

See all articles