Node WeChat public number develops packaging request and getting access_token

According to the instructions in the previous article, we have done a good job of docking with wechat public platform. Next, I plan to implement the function of requesting access_token first.

In the process of development, I did not copy the contents of the tutorial, but made some modifications myself. The main modifications were in the file structure and data transmission.

Original tutorial directory structure:

  • Material (material folder)
  • wechat (core folder)
    • access_token.json (used to request access_token)
    • menu.json (custom menu directory file)
    • msg.js (all passive reply types involved)
    • wechat.js (core file, including functions such as calling custom menu and custom reply)
  • app.js (entry file)
  • config.json (basic configuration data, including appid, appscratch, and various request addresses)

My directory structure:

  • Material (material folder)
  • app.js (entry file)
  • config.json (basic configuration data and dynamically stored access? Token data)
  • request.js (encapsulated post and get methods)
  • Access token.js (used to request access_token)
  • createMenu.js (used to generate custom menus)
  • replyType.js (involving all passive reply types)
  • reply.js (custom reply)

In my opinion, at least my directory structure is more detailed. As for the quality, I dare not say.

Encapsulating the request method

In fact, the development of WeChat public number by Node.js is nothing more than to request the official interface address according to the document. So before the real development, we need to encapsulate a set of request methods (we tried to use aoxis, but we didn't deal with the processing of formData, only failed). Here we use the request module to implement the request.

var request = require('request') // Introduce request component

// Encapsulate a get request method
exports.get = (url) => {
	return new Promise((resolve, reject) => {
		request(url, (error, response, body) => {
			if (!error && response.statusCode == 200) {
				console.log('get request success')
				resolve(body)
			} else {
				console.log('get request fail')
				reject(error)
			}
		})
	})
}

// Encapsulate a post request method
exports.post = (url, data) => {
    // You need to judge the data type here, because the data format of the customized menu and the image upload is different, which will result in an error
	return new Promise((resolve, reject) => {
		var form = {
			url: url
		}
		if (typeof data == 'string') {
			form.body = data // If the data format is character, the menu data is submitted to the interface through the body
		} else {
			form.formData = data // Otherwise, the data is submitted to the interface through formData (in this case, the interface for uploading pictures)
		}
		request.post(form, (error, response, body) => {
			if (!error && response.statusCode == 200) {
				console.log('post request success')
				resolve(body)
			} else {
				console.log('post request fail', error)
			}
		})
	})
}

Through Promise, we can handle the request results more easily when we call later.

We need to pay special attention here, that is, we need to judge the post data type, because according to the current code, there are two places where post requests are involved, which are to reply to the picture material and create a custom menu. The data of the custom menu is in json format, which can directly pass through the body, while in the reply material, the data format is object, which needs to submit the formData.

This distinction has been troubling for some time.

Get access_token

What is access Ou token?

  • It is the global only interface calling credential of the public number.
  • The validity period is currently 2 hours, which needs to be refreshed regularly;
  • Repeated access will lead to the invalidation of the access_token obtained last time;
  • Its request method is get
  • Its request address is https://api.weixin.qq.com/cgi-bin/token? Grant'type = client'credential & appid = apppid & Secret = appsecret

We can use[ Wechat public platform test account ]The test appid and appsecret provided spliced the address into the correct request address, and then the get method request encapsulated previously.

Here, I use the fs module to write the requested access_token to config.json. In this way, I think it can ensure that all relevant configuration information is together, which is convenient to call.

var fs = require('fs') // Introducing core modules
var request = require('./request') // Introduce encapsulated request module

module.exports = (config) => {
  return new Promise((resolve, reject) => {    
    var currentTime = new Date().getTime() // Get current timestamp

    // Splicing request address
    var url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + config.appId + '&secret=' + config.appScrect

    // If the accesstoken in config is empty or expired, a new request is required
    if (config.setAccessToken.accessToken === '' || config.setAccessToken.time < currentTime) {
      request.get(url).then((response) => {
        var result = JSON.parse(response)
        
        // Modify config data
        config.setAccessToken.accessToken = result.access_token
        config.setAccessToken.time = new Date().getTime() + (parseInt(result.expires_in) - 200) * 1000 // accesstoken expiration time

        // Write the updated config to the file
        fs.writeFileSync
        fs.writeFile('./config.json', JSON.stringify(config), (error) => {
          if (error) {
            console.log('update accessToken fail')
            reject(error)
          }
          console.log('update accessToken success')
          
          resolve(response.access_token) // Export accesstoken
        })
      }).catch((error) => {
        // request was aborted
      	console.log('request accessToken fail', error)
        reject(error)
      })
    } else {
      // Export directly if the local access_token is not invalid
      console.log('get accessToken success')
      resolve(config.setAccessToken.accessToken)
    }
  })
}

So far, our previous work has been completed. I will update the custom menu and custom reply in the next two logs. I hope you will come here objectively.

Article synced to my personal blog:< Node WeChat public number develops packaging request and getting access_token>

Related articles:

Reference:

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Tags: Front-end JSON

Posted on Sun, 09 Feb 2020 23:02:29 -0800 by wesmont