其他分享
首页 > 其他分享> > uniapp h5微信授权登录

uniapp h5微信授权登录

作者:互联网

直接上代码:

<view class="IconBox">
	<view class="tips">——第三方登录——</view>
		<view class="IconItemBox">
			<view class="IconItem" @click="weixinLogin">
			     <u-icon name="weixin-fill" size="45" color="#07C160"></u-icon>
		    </view>
	    </view>
    </view>
</view>
<script>
const app = getApp();
	// 判断是否为公众号模拟器环境
	const isWechat = () => {
		return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
	}
	// 判断公众号截取code
	const getUrlParam = (name) => {
		let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		let r = window.location.search.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
		return null;
	}
  export default{
     data(){
      return{
            
        }  
    },
    onl oad() { 
			if (!isWechat()) {
				location.href = app.$vm.globalData.baseLoginUrl
			}
		},
    methods:{
        weixinLogin(){
				this.getWxCode()
			},
			getWxCode() {
				let code = getUrlParam("code"); //是否存在code
				let local = app.$vm.globalData.baseLoginUrl;
				if (code == null || code === "") {
					//不存在就打开上面的地址进行授权
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${app.$vm.globalData.appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
					// https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxae048f1b059e77c0&redirect_uri=http://devapi.xingyeqiao.com/&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect								
				}
				
				// if (isWechat()) {
				// 	if(sessionStorage.getItem("id")){
				// 		let ids = sessionStorage.getItem("id")
				// 		location.href = app.$vm.globalData.baseLoginUrl+"?id="+ids
				// 	}else{
				// 		location.href = app.$vm.globalData.baseLoginUrl
				// 	}
				// };
			},
    } 
  }
</script>

上面的公共属性在app.vue文件中

//App.vue
<script>
	export default {
		globalData:{
			uploadUrl:"http://*************.com/index/file/FileAdd",
			imgBaseUrl:"http://*************.aliyuncs.com/", 
			connectObj:null,
			connectUrl:"ws://*************.com:8282",
			baseLoginUrl:"http://*************.com/index/login/wxLogin",
			appid:"wxbf34f4f4*************"
		}
</script>

上面有两种跳转方式,一种被我注释掉了,主要看后端怎么对接登录授权。

标签:uniapp,code,微信,app,h5,let,location,globalData,com
来源: https://blog.csdn.net/weixin_44694389/article/details/121019636