NestJS(NodeJS)使用JS-SDK签名算法

@Controller

 @Get('config')
  async getWXConfig(@Query('url') url : string,@Session() session){
    return await this.wxChatService.getWXConfig(url,session)
  }

@Service层

const { createHash } = require('crypto');
async getWXConfig(url: string, session) {
    const configObj: any = {}
    const configKeyArr = ['noncestr', 'jsapi_ticket', 'timestamp', 'url']
    let configStr = ""
    let access_token
    let jsapi_ticket
    const currentDate = new Date().getTime()
    const diffDate = currentDate - (session?.currentData ?? 0)
    const sec = diffDate / 1000
    if (sec > (session?.expires_in ?? 0)) {
      const tokenRes: any = await this.asyncAxiosProxy(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxConfig.appID}&secret=${wxConfig.appsecret}`)
      access_token = JSON.parse(tokenRes)?.access_token
      const ticketRes: any = await this.asyncAxiosProxy(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`)
      jsapi_ticket = JSON.parse(ticketRes)?.ticket
      session.access_token = access_token
      session.jsapi_ticket = jsapi_ticket
      session.expires_in = JSON.parse(tokenRes)?.expires_in
      session.currentData = currentDate
    } else {
      access_token = session.access_token
      jsapi_ticket = session.jsapi_ticket
    }
    console.log(access_token)
    console.log(jsapi_ticket)
    configObj.jsapi_ticket = jsapi_ticket
    configObj.noncestr = this.randomString(5)
    configObj.timestamp = currentDate
    configObj.url = url
    let sortKeyArr = configKeyArr.sort()
    for (const key of sortKeyArr) {
      configStr += `${key}=${configObj[key]}&`
    }
    configStr = configStr?.substr(0, configStr?.length - 1)
    const signature = this.encrypt(configStr)
    const config = {
      appId: wxConfig?.appID,
      appsecret: wxConfig?.appsecret,
      timestamp: configObj.timestamp,
      nonceStr: configObj.noncestr,
      signature: signature,
      jsApiList: ['updateAppMessageShareData']
    }
    return config
  }

  protected randomString(e: number) {
    e = e || 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
      a = t.length,
      n = "";
    for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n
  }

你可能感兴趣的:(NestJS(NodeJS)使用JS-SDK签名算法)