import { CACHE_MANAGER , HttpException , HttpService , Inject , Injectable } from '@nestjs/common' ; @ Injectable ( ) export class WeChatUtil { constructor ( @ Inject ( HttpService ) private readonly httpService , @ Inject ( CACHE_MANAGER ) protected readonly cacheManager ) { } param { string } appid param { string } appsecret returns { Promise < { code : number ; message : string } > } async weChatGetAccountToken ( appid , appsecret ) { const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${ appid }&secret=${ appsecret }` ; const data = await this . httpService . get ( url ) . toPromise ( ) ; if ( data . data . errcode ) { throw new HttpException ( data . data . errmsg , data . data . errcode ) ; } const a = await this . cacheManager . set ( appid , data . data . access_token ) ; return { code : 200 , message : 'AccountToken生成成功!' } ; } param { string } appid param { string } appsecret param { string } authCode returns { Promise < void > } async weChatGetUserAccountToken ( appid , appsecret , authCode ) { let baseApi = 'https://api.weixin.qq.com/sns/oauth2/' ; baseApi += `access_token?appid=${ appid }&secret=${ appsecret }&code=${ authCode }&grant_type=authorization_code` ; const { data } = await this . httpService . get ( baseApi ) . toPromise ( ) ; if ( data . errcode ) { throw new HttpException ( data . errmsg , data . errcode ) ; } return { code : 200 , openId : data . openid } ; } param { string } appId returns { Promise < any > } async ensureAccessToken ( appId ) { const accessToken = await this . cacheManager . get ( appId ) ; if ( ! accessToken ) { throw new HttpException ( 'accessToken已过期，请重新调用获取' , 500 ) ; } else { return accessToken ; } } returns { Promise < any > } async generatingRandomNumbers ( ) { return Math . random ( ) . toString ( 36 ) . substr ( 2 , 15 ) ; } returns { Promise < string > } async generationTimestamp ( ) { return '' + Math . floor ( Date . now ( ) / 1000 ) ; } param args returns { Promise < any > } async sortQuery ( args ) { let keys = Object . keys ( args ) ; keys = keys . sort ( ) ; const newArgs = { } ; for ( let i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; newArgs [ key . toLowerCase ( ) ] = args [ key ] ; } let str = '' ; const newKeys = Object . keys ( newArgs ) ; for ( let j = 0 ; j < newKeys . length ; j ++ ) { const k = newKeys [ j ] ; str += '&' + k + '=' + newArgs [ k ] ; } return str . substr ( 1 ) ; } }