qq.js 1.8 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
const {
  userCollection
} = require('../../common/constants')
const {
  ERROR
} = require('../../common/error')

function getQQPlatform () {
  const platform = this.clientPlatform
  switch (platform) {
    case 'app':
    case 'app-plus':
      return 'app'
    case 'mp-qq':
      return 'mp'
    default:
      throw new Error('Unsupported qq platform')
  }
}

function generateQQCache ({
雪洛's avatar
雪洛 已提交
22
  openid,
DCloud_JSON's avatar
DCloud_JSON 已提交
23 24 25 26 27
  sessionKey, // QQ小程序用户sessionKey
  accessToken, // App端QQ用户accessToken
  accessTokenExpired // App端QQ用户accessToken过期时间
} = {}) {
  const platform = getQQPlatform.call(this)
雪洛's avatar
雪洛 已提交
28
  const appId = this.getClientInfo().appId
DCloud_JSON's avatar
DCloud_JSON 已提交
29 30 31 32
  let cache
  switch (platform) {
    case 'app':
      cache = {
雪洛's avatar
雪洛 已提交
33
        openid,
DCloud_JSON's avatar
DCloud_JSON 已提交
34 35 36 37 38 39
        access_token: accessToken,
        access_token_expired: accessTokenExpired
      }
      break
    case 'mp':
      cache = {
雪洛's avatar
雪洛 已提交
40
        openid,
DCloud_JSON's avatar
DCloud_JSON 已提交
41 42 43 44 45 46 47 48
        session_key: sessionKey
      }
      break
    default:
      throw new Error('Unsupported qq platform')
  }
  return {
    third_party: {
49 50
      [`${appId}_${platform}_qq`]: cache,
      [`${platform}_qq`]: cache
DCloud_JSON's avatar
DCloud_JSON 已提交
51 52 53 54 55 56 57 58 59 60
    }
  }
}

async function getQQCache ({
  uid,
  userRecord,
  key
} = {}) {
  const platform = getQQPlatform.call(this)
雪洛's avatar
雪洛 已提交
61
  const appId = this.getClientInfo().appId
DCloud_JSON's avatar
DCloud_JSON 已提交
62 63 64 65 66 67 68 69 70
  if (!userRecord) {
    const getUserRes = await userCollection.doc(uid).get()
    userRecord = getUserRes.data[0]
  }
  if (!userRecord) {
    throw {
      errCode: ERROR.ACCOUNT_NOT_EXISTS
    }
  }
雪洛's avatar
雪洛 已提交
71 72 73 74 75 76 77
  const thirdParty = userRecord && userRecord.third_party
  if (!thirdParty) {
    return
  }
  const qqCacheOld = thirdParty[`${platform}_qq`]
  const qqCache = thirdParty[`${appId}_${platform}_qq`]
  return (qqCache && qqCache[key]) || (qqCacheOld && qqCacheOld[key])
DCloud_JSON's avatar
DCloud_JSON 已提交
78 79 80 81 82 83 84
}

module.exports = {
  getQQPlatform,
  generateQQCache,
  getQQCache
}