详解基于Node.js的微信JS-SDK后端接口实现代码

2020-06-17 06:52:34易采站长站整理

let jsapi_ticket = JSON.parse(body).ticket
})
})

生成签名

生成签名的步骤和最开始的

/wxJssdk
的算法是一致的,具体如下:


let jsapi_ticket = jsapi_ticket // 上一步从获取的jsapi_ticket
let nonce_str = '123456' // 密钥,字符串任意,可以随机生成
let timestamp = new Date().getTime() // 时间戳
let url = req.query.url // 使用接口的url链接,不包含#后的内容

// 将请求以上字符串,先按字典排序,再以'&'拼接,如下:其中j > n > t > u,此处直接手动排序
let str = 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + nonce_str + '&timestamp=' + timestamp + '&url=' + url

// 用sha1加密
let signature = sha1(str)

连接后的代码为:


const request = require('request')

const grant_type = 'client_credential'
const appid = 'your app id'
const secret = 'your app secret'

request('https://api.weixin.qq.com/cgi-bin/token?grant_type=' + grant_type + '&appid=' + appid + '&secret=' + secret, (err, response, body) => {
let access_toekn = JSON.parse(body).access_token

request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + access_token + '&type=jsapi', (err, response, body) => {
let jsapi_ticket = JSON.parse(body).ticket
let nonce_str = '123456' // 密钥,字符串任意,可以随机生成
let timestamp = new Date().getTime() // 时间戳
let url = req.query.url // 使用接口的url链接,不包含#后的内容

// 将请求以上字符串,先按字典排序,再以'&'拼接,如下:其中j > n > t > u,此处直接手动排序
let str = 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + nonce_str + '&timestamp=' + timestamp + '&url=' + url

// 用sha1加密
let signature = sha1(str)
})
})

曝露接口,返回给前端


app.post('/wxJssdk/getJssdk', (req, res) => {
const request = require('request')

const grant_type = 'client_credential'
const appid = 'your app id'
const secret = 'your app secret'

request('https://api.weixin.qq.com/cgi-bin/token?grant_type=' + grant_type + '&appid=' + appid + '&secret=' + secret, (err, response, body) => {
let access_toekn = JSON.parse(body).access_token

request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + access_token + '&type=jsapi', (err, response, body) => {
let jsapi_ticket = JSON.parse(body).ticket
let nonce_str = '123456' // 密钥,字符串任意,可以随机生成
let timestamp = new Date().getTime() // 时间戳