uniapp H5微信授权登录

文章描述:

uniapp H5微信公众号授权登录,我们可以去微信公众号申请测试账号在本地进行测试,然后在部署到服务器上面进行访问。

微信公众平台

测试帐号申请

地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

微信扫码登录

 

测试号信息

appID、appsecret

JS接口安全域名

127.0.0.1

测试号二维码

微信扫描关注测试公众号

网页服务

网页账号 → 授权回调页面域名:127.0.0.1:8080

 

Uniapp

本地测试

template

<template>
	<view class="">
		{{code}}
	</view>
</template>

script

	export default {
		data() {
			return {
				code:""
			};
		},
		created() {
			this.isWXBrowser = this.isWXBrowser();
			
			if (this.isWXBrowser) {
			    let code = this.getUrlCode("code");
					if (code) {
						console.log(code)
						
						this.code = code
						this.wxLogin(code); //后台登录
					} else {
						this.getWeChatCode(); //微信授权
				}
			}
			
			
		},
		onLoad(option) {
			
		},
		methods:{
			wxLogin(code){
				
			},
			//判断是否是微信内置的浏览器
			isWXBrowser() {
			  return (
				String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) ===
				"micromessenger"
			  );
			},
			//截取地址栏code
			getUrlCode(name) {
			  return (
				decodeURIComponent(
				  (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
					location.href
				  ) || [, ""])[1].replace(/\+/g, "%20")
				) || null
			  );
			},
			//访问微信地址,用来获取code
			getWeChatCode() {
				//处理域名
				let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				  
				let appid = 'wx01034e279fcb****'
				//let appid = '' //正式appid
				//通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
			
				window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+local+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"
			
				// window.location.href =
				// "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
				// appid +
				// "&redirect_uri=" +
				// local +
				// "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			},
	
		},
		
		
	}

微信开发者工具

公众号网页项目

地址栏输入:http://127.0.0.1:8080

正式上线

第一步:微信公众号 → 公众号设置

JS接口安全域名、网页授权域名里面添加域名即可,列如:api.miyil.com

第二步:把代码中的appid改为服务号appid即可

第三步:打包h5上传到服务器访问

 

template

<template>
	<view >
		<view class="userInfo">
			<view class="headImg"><image :src="headimgurl"></image></view>
			<view class="text">{{nickname}}</view>
		</view>
		<view class="hide">
			{{code}}
		</view>
	</view>
</template>

script

	export default {
		data() {
			return {
				code:"",
				nickname:"",
				headimgurl:""
			};
		},
		created() {
			this.isWXBrowser = this.isWXBrowser();
			
			if (this.isWXBrowser) {
			    let code = this.getUrlCode("code");
					if (code) {
						//console.log(code)
						
						this.code = code
						this.wxLogin(code); //后台登录
						
					} else {
						this.getWeChatCode(); //微信授权
				}
			}
			
			
		},
		onLoad(option) {
			
		},
		methods:{
			wxLogin(code){
				//console.log(code)
				
				uni.request({
				    url: 'https://api.miyil.com/h5/api.php', //仅为示例,并非真实接口地址。
				    data: {
				        code: code
				    },
				    header: {
				        // 'custom-header': 'hello' //自定义请求头信息
				    },
				    success: (res) => {
				        console.log(res.data);
				        this.headimgurl = res.data.headimgurl
						this.nickname = res.data.nickname
				    }
				});
			},
			//判断是否是微信内置的浏览器
			isWXBrowser() {
			  return (
				String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) ===
				"micromessenger"
			  );
			},
			//截取地址栏code
			getUrlCode(name) {
			  return (
				decodeURIComponent(
				  (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
					location.href
				  ) || [, ""])[1].replace(/\+/g, "%20")
				) || null
			  );
			},
			//访问微信地址,用来获取code
			getWeChatCode() {
				//处理域名
				let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				  
				
				let appid = '' //正式appid
				//通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
			
				window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+local+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"
			
			},
	
		},
		
		
	}

style.css

.userInfo{
	text-align: center;
	padding: 20upx 0;
}
.headImg image{
	width: 224upx;
	height: 224upx;
}
.text{
	text-align: center;
}
.hide{
	display: none;
}

 

PHP

    $appid = '';
    $secret = '';
    $code = $_GET["code"];
    
    $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$get_token_url);
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);

    //print_r($res);


    $json_obj = json_decode($res,true);
    $access_token = $json_obj['access_token'];
    //echo $access_token;


    $openid = $json_obj['openid'];
    //echo $openid;
    
    
    $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    // $user_obj = json_decode($res,true);
    // print_r($user_obj);
    echo $res;

 

 

发布时间:2022/07/07

发表评论