import { WeChatUtil } from '../../utile/wechat.util' ; import { CACHE_MANAGER , HttpException , HttpService , Inject , Injectable } from '@nestjs/common' ; import * as crypto from 'crypto' ; @ Injectable ( ) export class WechatSdk { constructor ( @ Inject ( WeChatUtil ) private readonly wechatUtil , @ Inject ( HttpService ) private readonly httpService , @ Inject ( CACHE_MANAGER ) protected readonly cacheManager ) { } param { string } appid param { string } url returns { Promise < string > } async signatureAlgorithm ( nonceStr , timestamp , appid , url ) { const ticket = await this . getTicket ( appid ) ; const ret = { jsapi_ticket : ticket , nonceStr , timestamp , url } ; const str = await this . wechatUtil . sortQuery ( ret ) ; const shasum = crypto . createHash ( 'sha1' ) ; shasum . update ( str ) ; return shasum . digest ( 'hex' ) ; } param { string } appid returns { Promise < any > } async getTicket ( appid ) { if ( ! appid ) { throw new HttpException ( 'appid不存在！！' , 500 ) ; } const ticket = await this . cacheManager . get ( appid ) ; if ( ticket ) { return ticket ; } const accessToken = await this . wechatUtil . ensureAccessToken ( appid ) ; const url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${ accessToken }&type=jsapi` ; const { data } = await this . httpService . get ( url ) . toPromise ( ) ; if ( data . errcode ) { throw new HttpException ( data . errmsg , data . errcode ) ; } await this . cacheManager . set ( appid , data . data . ticket ) ; return ticket ; } param { string } appid param { string } url returns { Promise < { nonceStr : any ; timestamp : string ; signature : string } > } async getJsSdkConfig ( appid , url ) { if ( ! appid ) { throw new HttpException ( 'appid不存在！！' , 500 ) ; } if ( ! url ) { throw new HttpException ( 'url不存在！！' , 500 ) ; } const nonceStr = await this . wechatUtil . generatingRandomNumbers ( ) ; const timestamp = await this . wechatUtil . generationTimestamp ( ) ; const signature = await this . signatureAlgorithm ( nonceStr , timestamp , appid , url ) ; return { nonceStr , timestamp , signature } ; } }