bind-qq.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. const {
  2. preBind,
  3. postBind
  4. } = require('../../lib/utils/relate')
  5. const {
  6. LOG_TYPE
  7. } = require('../../common/constants')
  8. const {
  9. ERROR
  10. } = require('../../common/error')
  11. const {
  12. initQQ
  13. } = require('../../lib/third-party/index')
  14. const {
  15. generateQQCache,
  16. getQQPlatform,
  17. saveQQUserKey
  18. } = require('../../lib/utils/qq')
  19. /**
  20. * 绑定QQ
  21. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#bind-qq
  22. * @param {Object} params
  23. * @param {String} params.code 小程序端QQ登录返回的code
  24. * @param {String} params.accessToken APP端QQ登录返回的accessToken
  25. * @param {String} params.accessTokenExpired accessToken过期时间,由App端QQ登录返回的expires_in参数计算而来,单位:毫秒
  26. * @returns
  27. */
  28. module.exports = async function (params = {}) {
  29. const schema = {
  30. code: {
  31. type: 'string',
  32. required: false
  33. },
  34. accessToken: {
  35. type: 'string',
  36. required: false
  37. },
  38. accessTokenExpired: {
  39. type: 'number',
  40. required: false
  41. }
  42. }
  43. this.middleware.validate(params, schema)
  44. const uid = this.authInfo.uid
  45. const {
  46. code,
  47. accessToken,
  48. accessTokenExpired
  49. } = params
  50. const qqPlatform = getQQPlatform.call(this)
  51. const appId = this.getClientInfo().appId
  52. const qqApi = initQQ.call(this)
  53. const clientPlatform = this.clientPlatform
  54. const apiName = clientPlatform === 'mp-qq' ? 'code2Session' : 'getOpenidByToken'
  55. let getQQAccountResult
  56. try {
  57. getQQAccountResult = await qqApi[apiName]({
  58. code,
  59. accessToken
  60. })
  61. } catch (error) {
  62. await this.middleware.uniIdLog({
  63. success: false,
  64. type: LOG_TYPE.BIND_QQ
  65. })
  66. throw {
  67. errCode: ERROR.GET_THIRD_PARTY_ACCOUNT_FAILED
  68. }
  69. }
  70. const {
  71. openid,
  72. unionid,
  73. // 保存下面四个字段
  74. sessionKey // 微信小程序用户sessionKey
  75. } = getQQAccountResult
  76. const bindAccount = {
  77. qq_openid: {
  78. [clientPlatform]: openid
  79. },
  80. qq_unionid: unionid
  81. }
  82. await preBind.call(this, {
  83. uid,
  84. bindAccount,
  85. logType: LOG_TYPE.BIND_QQ
  86. })
  87. await saveQQUserKey.call(this, {
  88. openid,
  89. sessionKey,
  90. accessToken,
  91. accessTokenExpired
  92. })
  93. return postBind.call(this, {
  94. uid,
  95. bindAccount,
  96. extraData: {
  97. qq_openid: {
  98. [`${qqPlatform}_${appId}`]: openid
  99. },
  100. ...generateQQCache.call(this, {
  101. openid,
  102. sessionKey
  103. })
  104. },
  105. logType: LOG_TYPE.BIND_QQ
  106. })
  107. }