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