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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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
  11. } = require('../../lib/utils/weixin')
  12. /**
  13. * 通过微信绑定手机号
  14. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#bind-mobile-by-mp-weixin
  15. * @param {Object} params
  16. * @param {String} params.encryptedData 微信获取手机号返回的加密信息
  17. * @param {String} params.iv 微信获取手机号返回的初始向量
  18. * @returns
  19. */
  20. module.exports = async function (params = {}) {
  21. /**
  22. * 微信小程序的规则是客户端应先使用checkSession接口检测上次获取的sessionKey是否仍有效
  23. * 如果有效则直接使用上次存储的sessionKey即可
  24. * 如果无效应重新调用login接口再次刷新sessionKey
  25. * 因此此接口不应直接使用客户端login获取的code,只能使用缓存的sessionKey
  26. */
  27. const schema = {
  28. encryptedData: 'string',
  29. iv: 'string'
  30. }
  31. const {
  32. encryptedData,
  33. iv
  34. } = params
  35. this.middleware.validate(params, schema)
  36. const uid = this.authInfo.uid
  37. const sessionKey = await getWeixinCache.call(this, {
  38. uid,
  39. key: 'session_key'
  40. })
  41. if (!sessionKey) {
  42. throw new Error('Session key not found')
  43. }
  44. const {
  45. purePhoneNumber: mobile
  46. } = decryptWeixinData.call(this, {
  47. encryptedData,
  48. sessionKey,
  49. iv
  50. })
  51. const bindAccount = {
  52. mobile
  53. }
  54. await preBind.call(this, {
  55. uid,
  56. bindAccount,
  57. logType: LOG_TYPE.BIND_MOBILE
  58. })
  59. await postBind.call(this, {
  60. uid,
  61. bindAccount,
  62. extraData: {
  63. mobile_confirmed: 1
  64. },
  65. logType: LOG_TYPE.BIND_MOBILE
  66. })
  67. return {
  68. errCode: 0
  69. }
  70. }