weixin.js 5.1 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5 6 7
const crypto = require('crypto')
const {
  userCollection
} = require('../../common/constants')
const {
  ERROR
} = require('../../common/error')
雪洛's avatar
雪洛 已提交
8

DCloud_JSON's avatar
DCloud_JSON 已提交
9 10 11 12 13
function decryptWeixinData ({
  encryptedData,
  sessionKey,
  iv
} = {}) {
雪洛's avatar
雪洛 已提交
14 15
  const oauthConfig = this.configUtils.getOauthConfig({
    provider: 'weixin'
DCloud_JSON's avatar
DCloud_JSON 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
  })
  const decipher = crypto.createDecipheriv(
    'aes-128-cbc',
    Buffer.from(sessionKey, 'base64'),
    Buffer.from(iv, 'base64')
  )
  // 设置自动 padding 为 true,删除填充补位
  decipher.setAutoPadding(true)
  let decoded
  decoded = decipher.update(encryptedData, 'base64', 'utf8')
  decoded += decipher.final('utf8')
  decoded = JSON.parse(decoded)
  if (decoded.watermark.appid !== oauthConfig.appid) {
    throw new Error('Invalid wechat appid in decode content')
  }
  return decoded
}

function getWeixinPlatform () {
  const platform = this.clientPlatform
  const userAgent = this.getClientInfo().userAgent
  switch (platform) {
    case 'app':
    case 'app-plus':
      return 'app'
    case 'mp-weixin':
      return 'mp'
    case 'h5':
    case 'web':
      return userAgent.indexOf('MicroMessenger') > -1 ? 'h5' : 'web'
    default:
      throw new Error('Unsupported weixin platform')
  }
}

雪洛's avatar
雪洛 已提交
51
async function saveWeixinUserKey ({
雪洛's avatar
雪洛 已提交
52
  openid,
DCloud_JSON's avatar
DCloud_JSON 已提交
53 54 55 56 57
  sessionKey, // 微信小程序用户sessionKey
  accessToken, // App端微信用户accessToken
  refreshToken, // App端微信用户refreshToken
  accessTokenExpired // App端微信用户accessToken过期时间
} = {}) {
雪洛's avatar
雪洛 已提交
58 59 60
  // 微信公众平台、开放平台refreshToken有效期均为30天(微信没有在网络请求里面返回30天这个值,务必注意未来可能出现调整,需及时更新此处逻辑)。
  // 此前QQ开放平台有调整过accessToken的过期时间:[access_token有效期由90天缩短至30天](https://wiki.connect.qq.com/%E3%80%90qq%E4%BA%92%E8%81%94%E3%80%91access_token%E6%9C%89%E6%95%88%E6%9C%9F%E8%B0%83%E6%95%B4)

雪洛's avatar
雪洛 已提交
61
  const appId = this.getClientInfo().appId
雪洛's avatar
雪洛 已提交
62 63 64 65
  const weixinPlatform = getWeixinPlatform.call(this)
  const keyObj = {
    dcloudAppid: appId,
    openid,
雪洛's avatar
雪洛 已提交
66
    platform: 'weixin-' + weixinPlatform
雪洛's avatar
雪洛 已提交
67 68 69
  }
  switch (weixinPlatform) {
    case 'mp':
70
      await this.uniOpenBridge.setSessionKey(keyObj, {
雪洛's avatar
雪洛 已提交
71
        session_key: sessionKey
雪洛's avatar
雪洛 已提交
72
      }, 30 * 24 * 60 * 60)
雪洛's avatar
雪洛 已提交
73 74 75 76
      break
    case 'app':
    case 'h5':
    case 'web':
77
      await this.uniOpenBridge.setUserAccessToken(keyObj, {
雪洛's avatar
雪洛 已提交
78 79 80
        access_token: accessToken,
        refresh_token: refreshToken,
        access_token_expired: accessTokenExpired
81
      }, 30 * 24 * 60 * 60)
雪洛's avatar
雪洛 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94
      break
    default:
      break
  }
}

function generateWeixinCache ({
  sessionKey, // 微信小程序用户sessionKey
  accessToken, // App端微信用户accessToken
  refreshToken, // App端微信用户refreshToken
  accessTokenExpired // App端微信用户accessToken过期时间
} = {}) {
  const platform = getWeixinPlatform.call(this)
DCloud_JSON's avatar
DCloud_JSON 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  let cache
  switch (platform) {
    case 'app':
    case 'h5':
    case 'web':
      cache = {
        access_token: accessToken,
        refresh_token: refreshToken,
        access_token_expired: accessTokenExpired
      }
      break
    case 'mp':
      cache = {
        session_key: sessionKey
      }
      break
    default:
      throw new Error('Unsupported weixin platform')
  }
  return {
    third_party: {
116
      [`${platform}_weixin`]: cache
DCloud_JSON's avatar
DCloud_JSON 已提交
117 118 119 120
    }
  }
}

雪洛's avatar
雪洛 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
function getWeixinOpenid ({
  userRecord
} = {}) {
  const weixinPlatform = getWeixinPlatform.call(this)
  const appId = this.getClientInfo().appId
  const wxOpenidObj = userRecord.wx_openid
  if (!wxOpenidObj) {
    return
  }
  return wxOpenidObj[`${weixinPlatform}_${appId}`] || wxOpenidObj[weixinPlatform]
}

async function getWeixinCacheFallback ({
  userRecord,
  key
} = {}) {
  const platform = getWeixinPlatform.call(this)
  const thirdParty = userRecord && userRecord.third_party
  if (!thirdParty) {
    return
  }
  const weixinCache = thirdParty[`${platform}_weixin`]
  return weixinCache && weixinCache[key]
}

DCloud_JSON's avatar
DCloud_JSON 已提交
146 147 148 149 150
async function getWeixinCache ({
  uid,
  userRecord,
  key
} = {}) {
雪洛's avatar
雪洛 已提交
151
  const weixinPlatform = getWeixinPlatform.call(this)
雪洛's avatar
雪洛 已提交
152
  const appId = this.getClientInfo().appId
DCloud_JSON's avatar
DCloud_JSON 已提交
153 154 155 156 157 158 159 160 161
  if (!userRecord) {
    const getUserRes = await userCollection.doc(uid).get()
    userRecord = getUserRes.data[0]
  }
  if (!userRecord) {
    throw {
      errCode: ERROR.ACCOUNT_NOT_EXISTS
    }
  }
雪洛's avatar
雪洛 已提交
162 163 164
  const openid = getWeixinOpenid.call(this, {
    userRecord
  })
165 166
  const getCacheMethod = weixinPlatform === 'mp' ? 'getSessionKey' : 'getUserAccessToken'
  const userKey = await this.uniOpenBridge[getCacheMethod]({
雪洛's avatar
雪洛 已提交
167
    dcloudAppid: appId,
雪洛's avatar
雪洛 已提交
168
    platform: 'weixin-' + weixinPlatform,
雪洛's avatar
雪洛 已提交
169 170 171 172
    openid
  })
  if (userKey) {
    return userKey[key]
雪洛's avatar
雪洛 已提交
173
  }
雪洛's avatar
雪洛 已提交
174 175 176 177
  return getWeixinCacheFallback({
    userRecord,
    key
  })
DCloud_JSON's avatar
DCloud_JSON 已提交
178 179
}

180 181 182 183 184 185 186 187 188 189 190
async function getWeixinAccessToken () {
  const weixinPlatform = getWeixinPlatform.call(this)
  const appId = this.getClientInfo().appId

  const cache = await this.uniOpenBridge.getAccessToken({
    dcloudAppid: appId,
    platform: 'weixin-' + weixinPlatform
  })

  return cache.access_token
}
DCloud_JSON's avatar
DCloud_JSON 已提交
191 192 193 194
module.exports = {
  decryptWeixinData,
  getWeixinPlatform,
  generateWeixinCache,
雪洛's avatar
雪洛 已提交
195
  getWeixinCache,
196 197
  saveWeixinUserKey,
  getWeixinAccessToken
DCloud_JSON's avatar
DCloud_JSON 已提交
198
}