login-by-weixin-mobile.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. const {
  2. initWeixin
  3. } = require('../../lib/third-party/index')
  4. const {
  5. getWeixinAccessToken
  6. } = require('../../lib/utils/weixin')
  7. const {
  8. ERROR
  9. } = require('../../common/error')
  10. const {
  11. preUnifiedLogin,
  12. postUnifiedLogin
  13. } = require('../../lib/utils/unified-login')
  14. const {
  15. LOG_TYPE
  16. } = require('../../common/constants')
  17. const {
  18. preBind,
  19. postBind
  20. } = require('../../lib/utils/relate')
  21. /**
  22. * 微信授权手机号登录
  23. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#login-by-weixin-mobile
  24. * @param {Object} params
  25. * @param {String} params.phoneCode 微信手机号返回的code
  26. * @param {String} params.inviteCode 邀请码
  27. * @returns
  28. */
  29. module.exports = async function (params = {}) {
  30. const schema = {
  31. phoneCode: 'string',
  32. inviteCode: {
  33. type: 'string',
  34. required: false
  35. }
  36. }
  37. this.middleware.validate(params, schema)
  38. const { phoneCode, inviteCode } = params
  39. const weixinApi = initWeixin.call(this)
  40. let mobile
  41. try {
  42. const accessToken = await getWeixinAccessToken.call(this)
  43. const mobileRes = await weixinApi.getPhoneNumber(accessToken, phoneCode)
  44. mobile = mobileRes.purePhoneNumber
  45. } catch (error) {
  46. console.error(error)
  47. await this.middleware.uniIdLog({
  48. success: false,
  49. type: LOG_TYPE.LOGIN
  50. })
  51. throw {
  52. errCode: ERROR.GET_THIRD_PARTY_ACCOUNT_FAILED
  53. }
  54. }
  55. const { type, user } = await preUnifiedLogin.call(this, {
  56. user: {
  57. mobile
  58. }
  59. })
  60. let extraData = {
  61. mobile_confirmed: 1
  62. }
  63. if (type === 'login') {
  64. // 绑定手机号
  65. if (!user.mobile_confirmed) {
  66. const bindAccount = {
  67. mobile
  68. }
  69. await preBind.call(this, {
  70. uid: user._id,
  71. bindAccount,
  72. logType: LOG_TYPE.BIND_MOBILE
  73. })
  74. await postBind.call(this, {
  75. uid: user._id,
  76. bindAccount,
  77. extraData: {
  78. mobile_confirmed: 1
  79. },
  80. logType: LOG_TYPE.BIND_MOBILE
  81. })
  82. extraData = {
  83. ...extraData,
  84. ...bindAccount
  85. }
  86. }
  87. }
  88. return postUnifiedLogin.call(this, {
  89. user,
  90. extraData: {
  91. ...extraData
  92. },
  93. isThirdParty: false,
  94. type,
  95. inviteCode
  96. })
  97. }