bind-weixin.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const {
  2. preBind,
  3. postBind
  4. } = require('../../lib/utils/relate')
  5. const {
  6. LOG_TYPE
  7. } = require('../../common/constants')
  8. const {
  9. generateWeixinCache,
  10. saveWeixinUserKey,
  11. getWeixinPlatform
  12. } = require('../../lib/utils/weixin')
  13. const {
  14. initWeixin
  15. } = require('../../lib/third-party/index')
  16. const {
  17. ERROR
  18. } = require('../../common/error')
  19. /**
  20. * 绑定微信
  21. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#bind-weixin
  22. * @param {Object} params
  23. * @param {String} params.code 微信登录返回的code
  24. * @returns
  25. */
  26. module.exports = async function (params = {}) {
  27. const schema = {
  28. code: 'string'
  29. }
  30. this.middleware.validate(params, schema)
  31. const uid = this.authInfo.uid
  32. const {
  33. code
  34. } = params
  35. const weixinPlatform = getWeixinPlatform.call(this)
  36. const appId = this.getClientInfo().appId
  37. const weixinApi = initWeixin.call(this)
  38. const clientPlatform = this.clientPlatform
  39. const apiName = clientPlatform === 'mp-weixin' ? 'code2Session' : 'getOauthAccessToken'
  40. let getWeixinAccountResult
  41. try {
  42. getWeixinAccountResult = await weixinApi[apiName](code)
  43. } catch (error) {
  44. await this.middleware.uniIdLog({
  45. success: false,
  46. type: LOG_TYPE.BIND_WEIXIN
  47. })
  48. throw {
  49. errCode: ERROR.GET_THIRD_PARTY_ACCOUNT_FAILED
  50. }
  51. }
  52. const {
  53. openid,
  54. unionid,
  55. // 保存下面四个字段
  56. sessionKey, // 微信小程序用户sessionKey
  57. accessToken, // App端微信用户accessToken
  58. refreshToken, // App端微信用户refreshToken
  59. expired: accessTokenExpired // App端微信用户accessToken过期时间
  60. } = getWeixinAccountResult
  61. const bindAccount = {
  62. wx_openid: {
  63. [clientPlatform]: openid
  64. },
  65. wx_unionid: unionid
  66. }
  67. await preBind.call(this, {
  68. uid,
  69. bindAccount,
  70. logType: LOG_TYPE.BIND_WEIXIN
  71. })
  72. await saveWeixinUserKey.call(this, {
  73. openid,
  74. sessionKey,
  75. accessToken,
  76. refreshToken,
  77. accessTokenExpired
  78. })
  79. return postBind.call(this, {
  80. uid,
  81. bindAccount,
  82. extraData: {
  83. wx_openid: {
  84. [`${weixinPlatform}_${appId}`]: openid
  85. },
  86. ...generateWeixinCache.call(this, {
  87. openid,
  88. sessionKey, // 微信小程序用户sessionKey
  89. accessToken, // App端微信用户accessToken
  90. refreshToken, // App端微信用户refreshToken
  91. accessTokenExpired // App端微信用户accessToken过期时间
  92. })
  93. },
  94. logType: LOG_TYPE.BIND_WEIXIN
  95. })
  96. }