bind-mobile-by-mp-weixin.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. const {
  2. preBind,
  3. postBind
  4. } = require('../../lib/utils/relate')
  5. const {
  6. LOG_TYPE
  7. } = require('../../common/constants')
  8. const {
  9. decryptWeixinData,
  10. getWeixinCache, getWeixinAccessToken
  11. } = require('../../lib/utils/weixin')
  12. const { initWeixin } = require('../../lib/third-party')
  13. const { ERROR } = require('../../common/error')
  14. /**
  15. * 通过微信绑定手机号
  16. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#bind-mobile-by-mp-weixin
  17. * @param {Object} params
  18. * @param {String} params.encryptedData 微信获取手机号返回的加密信息
  19. * @param {String} params.iv 微信获取手机号返回的初始向量
  20. * @param {String} params.code 微信获取手机号返回的code
  21. * @returns
  22. */
  23. module.exports = async function (params = {}) {
  24. /**
  25. * 微信小程序的规则是客户端应先使用checkSession接口检测上次获取的sessionKey是否仍有效
  26. * 如果有效则直接使用上次存储的sessionKey即可
  27. * 如果无效应重新调用login接口再次刷新sessionKey
  28. * 因此此接口不应直接使用客户端login获取的code,只能使用缓存的sessionKey
  29. */
  30. const schema = {
  31. encryptedData: {
  32. required: false,
  33. type: 'string'
  34. },
  35. iv: {
  36. required: false,
  37. type: 'string'
  38. },
  39. code: {
  40. required: false,
  41. type: 'string'
  42. }
  43. }
  44. const {
  45. encryptedData,
  46. iv,
  47. code
  48. } = params
  49. this.middleware.validate(params, schema)
  50. if ((!encryptedData && !iv) && !code) {
  51. return {
  52. errCode: ERROR.INVALID_PARAM
  53. }
  54. }
  55. const uid = this.authInfo.uid
  56. let mobile
  57. if (code) {
  58. // 区分客户端类型 小程序还是App
  59. const accessToken = await getWeixinAccessToken.call(this)
  60. const weixinApi = initWeixin.call(this)
  61. const res = await weixinApi.getPhoneNumber(accessToken, code)
  62. mobile = res.purePhoneNumber
  63. } else {
  64. const sessionKey = await getWeixinCache.call(this, {
  65. uid,
  66. key: 'session_key'
  67. })
  68. if (!sessionKey) {
  69. throw new Error('Session key not found')
  70. }
  71. const res = decryptWeixinData.call(this, {
  72. encryptedData,
  73. sessionKey,
  74. iv
  75. })
  76. mobile = res.purePhoneNumber
  77. }
  78. const bindAccount = {
  79. mobile
  80. }
  81. await preBind.call(this, {
  82. uid,
  83. bindAccount,
  84. logType: LOG_TYPE.BIND_MOBILE
  85. })
  86. await postBind.call(this, {
  87. uid,
  88. bindAccount,
  89. extraData: {
  90. mobile_confirmed: 1
  91. },
  92. logType: LOG_TYPE.BIND_MOBILE
  93. })
  94. return {
  95. errCode: 0
  96. }
  97. }