secure-network-handshake-by-weixin.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const {
  2. ERROR
  3. } = require('../../common/error')
  4. const {
  5. initWeixin
  6. } = require('../../lib/third-party/index')
  7. const {
  8. saveWeixinUserKey,
  9. saveSecureNetworkCache
  10. } = require('../../lib/utils/weixin')
  11. const loginByWeixin = require('../login/login-by-weixin')
  12. /**
  13. * 微信安全网络握手
  14. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#set-push-cid
  15. * @param {object} params
  16. * @param {string} params.code 微信登录返回的code
  17. * @param {boolean} params.callLoginByWeixin 是否同时调用一次微信登录
  18. * @returns
  19. */
  20. module.exports = async function (params = {}) {
  21. const schema = {
  22. code: 'string',
  23. callLoginByWeixin: {
  24. type: 'boolean',
  25. required: false
  26. }
  27. }
  28. this.middleware.validate(params, schema)
  29. let platform = this.clientPlatform
  30. if (platform !== 'mp-weixin') {
  31. throw new Error(`[secureNetworkHandshake] platform ${platform} is not supported`)
  32. }
  33. const {
  34. code,
  35. callLoginByWeixin = false
  36. } = params
  37. if (callLoginByWeixin) {
  38. return loginByWeixin.call(this, {
  39. code,
  40. secureNetworkCache: true
  41. })
  42. }
  43. const weixinApi = initWeixin.call(this)
  44. let getWeixinAccountResult
  45. try {
  46. getWeixinAccountResult = await weixinApi.code2Session(code)
  47. } catch (error) {
  48. console.error(error)
  49. throw {
  50. errCode: ERROR.GET_THIRD_PARTY_ACCOUNT_FAILED
  51. }
  52. }
  53. const {
  54. openid,
  55. unionid,
  56. sessionKey // 微信小程序用户sessionKey
  57. } = getWeixinAccountResult
  58. await saveSecureNetworkCache.call(this, {
  59. code,
  60. openid,
  61. unionid,
  62. sessionKey
  63. })
  64. await saveWeixinUserKey.call(this, {
  65. openid,
  66. sessionKey
  67. })
  68. return {
  69. errCode: 0
  70. }
  71. }