wechatLogin.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <template>
  2. <view>
  3. <u-toast ref="uToast" />
  4. </view>
  5. </template>
  6. <script>
  7. import getUrlParams from "./../../utils/getUrlParams.js";
  8. export default {
  9. data() {
  10. return {
  11. backUrl: '',
  12. code: ''
  13. }
  14. },
  15. onLoad(page) {
  16. let local = window.location.href;
  17. let locationLocaturl = window.location.search;
  18. // 微信返回的回调地址
  19. let backUrl = local.split('backUrl=')[1]
  20. if (backUrl) {
  21. this.backUrl = decodeURIComponent(backUrl)
  22. }
  23. console.log('backUrl', decodeURIComponent(backUrl))
  24. let code = getUrlParams(locationLocaturl, "code")
  25. console.log('code', code)
  26. if (code) {
  27. this.code = code
  28. this.handleGetWXInfo(this.code)
  29. } else {
  30. window.location.href =
  31. `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.config.wxAppid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&#wechat_redirect`
  32. }
  33. },
  34. methods: {
  35. // 通过code获取 openId等用户信息
  36. handleGetWXInfo(code) {
  37. uni.showLoading({
  38. title: '加载中'
  39. })
  40. this.$u.api.getWXInfo(code).then((res) => {
  41. if (res.code === 200) {
  42. this.$u.vuex('vuex_wxinfo', res.data);
  43. this.getToken(res.data.openId)
  44. } else {
  45. this.$refs.uToast.show({
  46. title: res.msg || '获取用户信息失败!',
  47. type: 'error'
  48. });
  49. uni.hideLoading()
  50. }
  51. }).catch((err) => {
  52. uni.hideLoading()
  53. })
  54. },
  55. /**
  56. * 通过openId获取token
  57. * @param {Object} openId
  58. */
  59. getToken(openId) {
  60. this.$u.api.codeV2Api.sendSmsCodeV2api({ openId }).then(res => {
  61. if (res.code === 200) {
  62. this.$u.vuex('vuex_user', res.data);
  63. this.$u.vuex('vuex_token', res.data.accessToken);
  64. this.$u.vuex('vuex_hasLogin', true);
  65. if (res.data.needVerify) {
  66. localStorage.setItem('backUrl', this.backUrl)
  67. this.$u.route({
  68. url: 'pages/center/phoneLogin/phoneLogin'
  69. })
  70. } else {
  71. location.href = this.backUrl
  72. }
  73. uni.hideLoading()
  74. } else {
  75. this.$refs.uToast.show({
  76. title: res.msg || '获取用户信息失败!',
  77. type: 'error'
  78. });
  79. uni.hideLoading()
  80. }
  81. })
  82. }
  83. }
  84. }
  85. </script>
  86. <style>
  87. </style>