uniapp微信授权登录

文章描述:

uniapp开发微信授权登录

template

<button class="login-btn" type="primary" @click="getUserInfo">微信用户一键登录</button>

script

getUserInfo

		getUserInfo() {
			uni.getUserInfo({
			   provider: 'weixin',
			   success: (res) => {
				 console.log('getUserInfo', res);
		
			   },
			});	
		},

微信公众开发4月更新了这个方法getUserProfile,用getUserinfo无法弹出授权窗口

getUserProfile

		getUserInfo() {
			// #ifdef MP-WEIXIN
			uni.getUserProfile({
				desc: '登录后可同步数据',
				lang: 'zh_CN',
				success: (res) => {
					console.log('getUserProfile', res);
				},
			});
		   //#endif
		},

demo

script

		login(){
			// #ifdef MP-WEIXIN
			var self=this;
			uni.showLoading({
				mask:true,
				title: '正在登录···',
				complete:()=>{}
			});
			uni.login({
				provider: 'weixin',
				success: function (loginRes) {
					let js_code = loginRes.code;	//js_code可以给后台获取unionID或openID作为用户标识
					console.log(js_code)
					uni.showToast({
						title:js_code,
						icon:'none'
					})
					// 获取用户信息
					uni.request({
						url:'https://www.xxx.com/index.php/index/index/login',
						method:"GET",
						data:{code:js_code},
						success:function(res) {
							console.log(res)
						}
					})
					
				},
				fail:function(res){
					
				}
			})
			//#endif
		}

php

    public function login(){
        $appid = '';//微信小程序appid
        $secret = '';//微信小程序secret
		$code = input('code');//接收code参数,换取用户唯一标识
      	$username = input('username');//接收用户名
      	$sex = input('sex');//接收用户性别
      	//下面url是请求微信端地址获取用户唯一标识的,对应的appid和secret改成自己的
      	$url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
      	$res = $this->https_request($url);//https_request是封装的发送请求的方法
        print_r($res);
    }
    
    public function https_request($url, $data = null)
    {
        $curl = curl_init();//初始化
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);//允许 cURL 函数执行的最长秒数。
        /*if (!empty($port)) {
            curl_setopt($curl, CURLOPT_PORT, $port);//可选的用来指定连接端口,默认80端口可不写
        }*/
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json;charset=UTF-8'));//设置请求目标url头部信息
        if (!empty($data)) {
            //$data不为空,发送post请求
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); //$data:数组
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);//执行命令
        $error = curl_error($curl);//错误信息
        if ($error || $output == FALSE) {
            //报错信息
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        return $output;
    }

 

发布时间:2022/05/26

发表评论