15年软件开发经验 只做源码定制 互联网+定制化解决方案

15年软件开发经验,只做源码定制!

原创设计 定制开发

满足您的个性化需求

当前位置:首页 后端开发 Thinkphp5

百度小程序手机号授权登录

王少铮| 发布于 2021-09-29 11:59:50| 272阅读| 1点赞| 0评论
举报

解决思路是一定要多看官方文档

前端部分

<template>
		<view class="warp" style="width: 100%;height: 100vh;">
			<button open-type="getPhoneNumber" type="primary" style="position:absolute;top:35%;left:5%;width:90%;" @getphonenumber="getphonenumber">
				一键授权登录
			</button>
		</view>
	</template>

	<script>
		export default {
			data() {
				return {
					code:'',
					session_key:'',
					phone:'',
				}
			},
			onLoad() {
				this.getInfo();
			},
			methods: {
				getInfo(){
					//用uni.login静默获取的code请求完是错误的,换成swan.getLoginCode就可以正常使用了
					swan.getLoginCode({
						success:(res)=>{
							this.code = res.code;

							//此处是请求后台的接口,后端用此接口去百度方请求session_key
							uni.request({
								url:'https://www.bzhuo.com/api/Login/getSessionKey',
								method:'POST',
								data:{code:this.code},
								success:(res)=>{
									this.session_key = res.data.session_key;
								}
							})
						}
					})
				},
				
				getphonenumber(e) {
					
					if (e.detail.encryptedData) {
						var arr = JSON.stringify(e);
						var encryptedData = e.detail.encryptedData;
						var iv = e.detail.iv;
						//此处将值传给后端,后端用encryptedData和iv和session_key进行解密
						uni.request({
							url:'https://www.bzhuo.com/api/Login/getPhone',
							method:'POST',
							data:{
								encryptedData:encryptedData,
								iv:iv,
								session_key:this.session_key,
							},
							success:(res)=>{
								if(res.data.mobile){
									this.phone = res.data.mobile;
									uni.setStorageSync('phone',this.phone);
									if(uni.getStorageSync('phone','') != ''){
										uni.showToast({
											title:'授权登录成功',
											icon:'none',
											duration:1500
										});
										uni.request({
											url:'https://www.bzhuo.com/api/Login/phoneAdd',
											method:'POST',
											data:{phone:uni.getStorageSync('phone','')},
											success:(res)=>{
											}
										})
										setTimeout(function(){
											<a href="https://www.qinfenniao.com/article.html?name=uni" target="_blank">uni</a>.navigateTo({
												url:'../index/index',
											})
										},1500)
									}else{
										<a href="https://www.qinfenniao.com/article.html?name=uni" target="_blank">uni</a>.showToast({
											title:'授权登录失败',
											icon:'none',
											duration:1500
										});
									}
								}
							}
						})
					} else {
						<a href="https://www.qinfenniao.com/article.html?name=uni" target="_blank">uni</a>.showModal({
							title: '获取失败',
							content: <a href="https://www.qinfenniao.com/article.html?name=js" target="_blank">js</a>ON.stringify(e)
						});
					}
				}
			}
		}
	</script>

	<style>
		.warp {
			position: relative;
			height: 100vh;
		}

		.btn {
			width: 400rpx;
			height: 100rpx;
			text-align: center;
			line-height: 100rpx;
			border-radius: 12rpx;
			background-color: #4CD964;
			color: #fff;
			font-size: 39rpx;
			font-weight: bold;
			margin: auto;
			position: absolute;
			top: 0%;
			bottom: 0px;
			left: 0px;
			right: 0px;
		}

		.wenzi {
			text-align: center;
			position: relative;
			top: 450rpx;
			color: grey;
		}
	</style>


后端部分:

public function getSessionKey()
    {
        $code = input('code');
        $url = 'https://spapi.baidu.com/oauth/jscode2sessionkey';
        $params = [
            'code' =>$code,
            'client_id' =>'PSGL75oGUczjixdMzlzQtTvXi2xVQqik',
            'sk' =>'7yrYM3PP2P7gwOK25dbzCsGDqrHtVa47',
        ];
        //发起get请求
        $res = httpCurl($url,$params,'GET');
        return <a href="https://www.qinfenniao.com/article.html?name=js" target="_blank">js</a>on(<a href="https://www.qinfenniao.com/article.html?name=js" target="_blank">js</a>on_decode($res));
    }

    public function getPhone()
    {
        $encryptedData = input('encryptedData');
        $iv = input('iv');
        $<a href="https://www.qinfenniao.com/nav/%E7%BD%91%E7%AB%99%E5%BC%80%E5%8F%91.html" target="_blank">app</a>_key = 'PSGL75oGUczjixdMzlzQtTvXi2xVQqik';
        $session_key = input('session_key');
        //进行解密
        $data = decrypt($encryptedData,$iv,$<a href="https://www.qinfenniao.com/nav/%E7%BD%91%E7%AB%99%E5%BC%80%E5%8F%91.html" target="_blank">app</a>_key,$session_key);
        return <a href="https://www.qinfenniao.com/article.html?name=js" target="_blank">js</a>on(<a href="https://www.qinfenniao.com/article.html?name=js" target="_blank">js</a>on_decode($data));
    }


后端公共函数部分

/**
	 * 数据解密:低版本使用mcrypt库(PHP < 5.3.0),高版本使用openssl库(PHP >= 5.3.0)。
	 *
	 * @param string $ciphertext    待解密数据,返回的内容中的data字段
	 * @param string $iv            加密向量,返回的内容中的iv字段
	 * @param string $<a href="https://www.qinfenniao.com/nav/%E7%BD%91%E7%AB%99%E5%BC%80%E5%8F%91.html" target="_blank">app</a>_key       创建<a href="https://www.qinfenniao.com/nav/%E5%B0%8F%E7%A8%8B%E5%BA%8FAPP.html" target="_blank">小程序</a>时生成的<a href="https://www.qinfenniao.com/nav/%E7%BD%91%E7%AB%99%E5%BC%80%E5%8F%91.html" target="_blank">app</a>_key
	 * @param string $session_key   登录的code换得的
	 * @return string | false
	 */
	function decrypt($ciphertext, $iv, $<a href="https://www.qinfenniao.com/nav/%E7%BD%91%E7%AB%99%E5%BC%80%E5%8F%91.html" target="_blank">app</a>_key, $session_key) {
	    $session_key = base64_decode($session_key);
	    $iv = base64_decode($iv);
	    $ciphertext = base64_decode($ciphertext);

	    $plaintext = false;
	    if (function_exists("openssl_decrypt")) {
	        $plaintext = openssl_decrypt($ciphertext, "AES-192-CBC", $session_key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
	    } else {
	        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, null, MCRYPT_MODE_CBC, null);
	        mcrypt_generic_init($td, $session_key, $iv);
	        $plaintext = mdecrypt_generic($td, $ciphertext);
	        mcrypt_generic_deinit($td);
	        mcrypt_module_close($td);
	    }
	    if ($plaintext == false) {
	        return false;
	    }

	    // trim pkcs#7 padding
	    $pad = ord(substr($plaintext, -1));
	    $pad = ($pad < 1 || $pad > 32) ? 0 : $pad;
	    $plaintext = substr($plaintext, 0, strlen($plaintext) - $pad);

	    // trim header
	    $plaintext = substr($plaintext, 16);
	    // get content length
	    $unpack = unpack("Nlen/", substr($plaintext, 0, 4));
	    // get content
	    $content = substr($plaintext, 4, $unpack['len']);
	    // get app_key
	    $app_key_decode = substr($plaintext, $unpack['len'] + 4);

	    return $app_key == $app_key_decode ? $content : false;
	}

	/**
	 * 发送HTTP请求方法
	 * @param  string $url    请求URL
	 * @param  array  $params 请求参数
	 * @param  string $method 请求方法GET/POST
	 * @return array  $data   响应数据
	 */
	function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false){
	    date_default_timezone_set('PRC');
	    $opts = array(
	        CURLOPT_TIMEOUT        => 30,
	        CURLOPT_RETURNTRANSFER => 1,
	        CURLOPT_SSL_VERIFYPEER => false,
	        CURLOPT_SSL_VERIFYHOST => false,
	        CURLOPT_HTTPHEADER     => $header,
	        CURLOPT_COOKIESESSION  => true,
	        CURLOPT_FOLLOWLOCATION => 1,
	        CURLOPT_COOKIE         =>session_name().'='.session_id(),
	    );
	    /* 根据请求类型设置特定参数 */
	    switch(strtoupper($method)){
	        case 'GET':
	            // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
	            // 链接后拼接参数  &  非?
	            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
	            break;
	        case 'POST':
	            //判断是否传输文件
	            $params = $multi ? $params : http_build_query($params);
	            $opts[CURLOPT_URL] = $url;
	            $opts[CURLOPT_POST] = 1;
	            $opts[CURLOPT_POSTFIELDS] = $params;
	            break;
	        default:
	            throw new Exception('不支持的请求方式!');
	    }
	    /* 初始化并执行curl请求 */
	    $ch = curl_init();
	    curl_setopt_array($ch, $opts);
	    $data  = curl_exec($ch);
	    $error = curl_error($ch);
	    curl_close($ch);
	    if($error) throw new Exception('请求发生错误:' . $error);
	    return  $data;
	}


1

0条评论

别默默看啦~登录/注册一起参与讨论吧~

热门标签

王少铮
微信扫一扫立即咨询
账号登录|扫码登录

立即注册 |忘记密码?

欢迎注册

已有账号马上登录

重置密码

扫码绑定微信
微信扫一扫

绑定手机号

分享到-微信

举报

  • 举报类型:

  • 举报描述:

您好,当前积分不足。

在线客服
拨打电话
17330196230 13230981129
顶部