wxAuth.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import config from '@/config'
  2. import {loginWx} from "../apis/user";
  3. // 配置信息,需要替换为自己的信息
  4. const APPID = config.appid;
  5. const REDIRECT_URI = encodeURIComponent(window.location.href);
  6. // 判断是否在微信浏览器中
  7. function isWechatBrowser() {
  8. return /MicroMessenger/i.test(navigator.userAgent)
  9. }
  10. // 获取授权链接
  11. function getAuthorizeUrl() {
  12. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
  13. }
  14. // 获取 code
  15. function getCodeFromUrl() {
  16. const url = window.location.href;
  17. const reg = /code=([^&]*)/;
  18. const arr = url.match(reg);
  19. return arr ? arr[1] : null;
  20. }
  21. // 获取微信用户信息
  22. export async function getWxUserInfo() {
  23. if (!isWechatBrowser()) {
  24. console.error('请在微信浏览器中打开');
  25. return null;
  26. }
  27. const code = getCodeFromUrl();
  28. if (!code) {
  29. console.log('授权跳转')
  30. window.location.href = getAuthorizeUrl();
  31. return null;
  32. }
  33. loginWx({
  34. code
  35. }).then(res => {
  36. console.log('code',res);
  37. uni.setStorageSync('token', res.token)
  38. uni.setStorageSync('realName',res.realName)
  39. return res
  40. })
  41. }