首先下载jssha
npm i -save jssha
sign.ts
import jsSHA from "jssha";
var createNonceStr = function () {
return Math.random().toString(36).substr(2, 15)
}
var createTimestamp = function () {
return parseInt((new Date().getTime() / 1000) + '') + ''
}
var raw = function (args) {
var keys = Object.keys(args)
keys = keys.sort()
var newArgs = {}
keys.forEach(function (key) {
newArgs[key.toLowerCase()] = args[key]
})
var string = ''
for (var k in newArgs) {
string += '&' + k + '=' + newArgs[k]
}
string = string.substr(1)
return string
}
/**
* @synopsis 签名算法
*
* @param jsapi_ticket 用于签名的 jsapi_ticket
* @param url 用于签名的 url ,注意必须动态获取,不能 hardcode
*
* @returns
*/
export var sign = function (jsapi_ticket, url) {
var ret = {
jsapi_ticket: jsapi_ticket,
nonceStr: createNonceStr(),
timestamp: createTimestamp(),
url: url,
signature: null
}
var string = raw(ret)
let shaObj = new jsSHA('SHA-1', 'TEXT')
shaObj.update(string)
ret.signature = shaObj.getHash('HEX')
return ret
}
import { sign } from './sign';
async getconfig(params: { url: string }) {
let wxapi = 'https://api.weixin.qq.com/cgi-bin'
let APPID = 'wx2ac60114dbb204e3'
let SECRET = '69b09cb1e827562dde548951a55406cc'
let tokenObj = await this.http.get(`${wxapi}/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET}`)
let access_token = tokenObj.access_token
// {"access_token":"ACCESS_TOKEN","expires_in":7200}
let ticketObj = await this.http.get(`${wxapi}/ticket/getticket?access_token=${access_token}&type=jsapi`)
let ticket = ticketObj.ticket
// {
// "errcode":0,
// "errmsg":"ok",
// "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
// "expires_in":7200
// }
let config = {...sign(ticket, params.url),appId:APPID}
return config ?? {}
}
注意使用自己的http请求
我用的axios
同时 access_token和 ticket不应该实时获取,我这里只是方便演示