1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- import config from '@/config'
- import {loginWx} from "../apis/user";
- // 配置信息,需要替换为自己的信息
- const APPID = config.appid;
- const REDIRECT_URI = encodeURIComponent(window.location.href);
- // 判断是否在微信浏览器中
- function isWechatBrowser() {
- return /MicroMessenger/i.test(navigator.userAgent)
- }
- // 获取授权链接
- function getAuthorizeUrl() {
- 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`;
- }
- // 获取 code
- function getCodeFromUrl() {
- const url = window.location.href;
- const reg = /code=([^&]*)/;
- const arr = url.match(reg);
- return arr ? arr[1] : null;
- }
- // 获取微信用户信息
- export async function getWxUserInfo() {
- if (!isWechatBrowser()) {
- console.error('请在微信浏览器中打开');
- return null;
- }
- const code = getCodeFromUrl();
- if (!code) {
- console.log('授权跳转')
- window.location.href = getAuthorizeUrl();
- return null;
- }
- loginWx({
- code
- }).then(res => {
- console.log('code',res);
- uni.setStorageSync('token', res.token)
- uni.setStorageSync('realName',res.realName)
- return res
- })
- }
|