openWx.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <template>
  2. <div>
  3. <!-- 微信页面授权回调:用户首次进入时判断当前用户所在环境:微信公众号和微信小程序 -->
  4. 微信页面授权回调:用户首次进入时判断当前用户所在环境:微信公众号和微信小程序
  5. </div>
  6. </template>
  7. <script>
  8. import { getUrlParams } from '@/utils/index';
  9. import { WxJsOpenId } from '@/utils/login';
  10. export default {
  11. created() {
  12. console.log(12121212);
  13. this.getCode();
  14. },
  15. mounted() {
  16. console.log(17171717171717);
  17. },
  18. methods: {
  19. getCode() {
  20. const code = getUrlParams()?.code; // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
  21. console.log(17);
  22. const local = window.location.href;
  23. if (code == null || code === '') {
  24. console.log(120);
  25. window.location.href =
  26. 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
  27. // window.APPID +
  28. `wx907c27f16841a919` +
  29. '&redirect_uri=' +
  30. encodeURIComponent(local) +
  31. '&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
  32. } else {
  33. this.getOpenId(code); //把code传给后台获取用户信息
  34. }
  35. },
  36. async getOpenId(code) {
  37. // 通过code获取 openId等用户信息,/api/user/wechat/login 为后台接口
  38. let _this = this;
  39. // ?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
  40. const res = await WxJsOpenId({
  41. appid: 'wx907c27f16841a919',
  42. secret: 'd9c81d6c47f7de322a2ff85847de6728',
  43. code,
  44. grant_type: 'authorization_code',
  45. });
  46. console.log(4848484848, res);
  47. // this.$http
  48. // .post('/api/user/wechat/login', { code: code })
  49. // .then((res) => {
  50. // let datas = res.data;
  51. // if (datas.code === 0) {
  52. // console.log('成功');
  53. // }
  54. // })
  55. // .catch((error) => {
  56. // console.log(error);
  57. // });
  58. },
  59. },
  60. };
  61. </script>