wechatLogin.vue 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. let code = getUrlParams(local, "code")
  24. if (code) {
  25. this.code = code
  26. this.handleGetWXInfo(this.code)
  27. } else {
  28. window.location.href =
  29. `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.config.wxAppid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&#wechat_redirect`
  30. }
  31. },
  32. methods: {
  33. // 通过code获取 openId等用户信息
  34. handleGetWXInfo(code) {
  35. uni.showLoading({
  36. title: '加载中'
  37. })
  38. this.$u.api.getWXInfo(code).then((res) => {
  39. if (res.code === 200) {
  40. this.$u.vuex('vuex_wxinfo', res.data);
  41. this.getToken(res.data.openId)
  42. } else {
  43. this.$refs.uToast.show({
  44. title: '获取用户信息失败!',
  45. type: 'error'
  46. });
  47. uni.hideLoading()
  48. }
  49. }).catch((err) => {
  50. this.$refs.uToast.show({
  51. title: '获取用户信息失败!',
  52. type: 'error'
  53. });
  54. uni.hideLoading()
  55. })
  56. },
  57. /**
  58. * 通过openId获取token
  59. * @param {Object} openId
  60. */
  61. getToken(openId) {
  62. this.$u.api.codeV2Api.sendSmsCodeV2api({ openId }).then(res => {
  63. if (res.code === 200) {
  64. if (res.data.needVerify) {
  65. localStorage.setItem('backUrl', this.backUrl)
  66. uni.navigateTo({
  67. url: '/pages/center/phoneLogin/phoneLogin'
  68. })
  69. } else {
  70. this.$u.vuex('vuex_user', res.data);
  71. this.$u.vuex('vuex_token', res.data.accessToken);
  72. this.$u.vuex('vuex_hasLogin', true);
  73. location.href = this.backUrl
  74. }
  75. uni.hideLoading()
  76. } else {
  77. this.$refs.uToast.show({
  78. title: res.msg || '获取用户信息失败!',
  79. type: 'error'
  80. });
  81. uni.hideLoading()
  82. }
  83. })
  84. }
  85. }
  86. }
  87. </script>
  88. <style>
  89. </style>