微信小程序授权登录

<?php

class WeChat{
    private $appid;
    private $appsecret;

    /**
     * WeChat constructor.
     * @param $appid string 小程序的APPID
     * @param $appsecret string 小程序的密钥
     */
    public function __construct($appid,$appsecret)
    {
        $this->appid = $appid;
        $this->appsecret = $appsecret;
    }

    /**
     * 获取openid信息
     * @param $code string code码
     * @return mixed
     */
    public function getOpenid($code){
        //api接口
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->appsecret}&js_code={$code}&grant_type=authorization_code";

        //获取GET请求
        $json = $this->httpRequest($url);
        return json_decode($json, true);
    }

    /**
     * 获取用户的手机号
     * @param $iv string 加密的用户数据
     * @param $encryptedData string 与用户数据一同返回的初始向量
     * @param $sessionKey string 用户在小程序登录后获取的会话密钥
     * @return mixed
     */
    public function getUserMobile($iv,$encryptedData,$sessionKey)
    {
        $WX = new WXBizDataCrypt($this->appid,$sessionKey);
        $errCode = $WX->decryptData($encryptedData,$iv, $data);

        if ($errCode == 0) {
            $msg = 'ok';
            $status = 1;
        } else {
            $msg = $errCode;
            $status = 0;
            $data = [];
        }

        return ['status'=>$status,'msg'=>$msg,'data'=>$data];
    }
    
    /**
     * CURL请求
     * @param $url string 请求url地址
     * @param $method string 请求方法 get post
     * @param mixed $postfields post数据数组
     * @param array $headers 请求header信息
     * @param bool|false $debug  调试开启 默认false
     * @return mixed
     */
    public function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false){
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }
}

class WXBizDataCrypt {
    private $appid;
	private $sessionKey;

	/**
	 * 构造函数
	 * @param $sessionKey string 用户在小程序登录后获取的会话密钥
	 * @param $appid string 小程序的appid
	 */
	public function __construct($appid,$sessionKey)
	{
		$this->appid = $appid;
		$this->sessionKey = $sessionKey;
	}

	/**
	 * 检验数据的真实性,并且获取解密后的明文.
	 * @param $encryptedData string 加密的用户数据
	 * @param $iv string 与用户数据一同返回的初始向量
	 * @param $data string 解密后的原文
     *
	 * @return int 成功0,失败返回对应的错误码
	 */
	public function decryptData($encryptedData,$iv, &$data )
	{
		if (strlen($this->sessionKey) != 24) {
			return $this->ErrorCode("IllegalAesKey");
		}

		$aesKey=base64_decode($this->sessionKey);

		if (strlen($iv) != 24) {
			return $this->ErrorCode("IllegalIv");
		}

		$aesIV=base64_decode($iv);

		$aesCipher=base64_decode($encryptedData);

		$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

		$dataObj=json_decode( $result );
		if( $dataObj  == NULL )
		{
			return $this->ErrorCode("IllegalBuffer");
		}
		if( $dataObj->watermark->appid != $this->appid )
		{
			return $this->ErrorCode("IllegalBuffer");
		}
		$data = $result;
		return $this->ErrorCode("OK");
	}

	public function ErrorCode($parameter){

		$errorcode = array(
			'ValidateSignatureError'	=> "-41001: encodingAesKey 非法",
			'ParseXmlError'				=> "-40002: xml解析失败",
			'ComputeSignatureError'		=> "-40003: sha加密生成签名失败",
			'IllegalAesKey' 			=> "-40004: encodingAesKey 非法",
			'ValidateAppidError'		=> "-40005: appid 校验错误",
			'EncryptAESError'			=> "-40006: aes 加密失败",
			'DecryptAESError'			=> "-40007: aes 解密失败",
			'IllegalBuffer'				=> "-40008: 解密后得到的buffer非法",
			'EncodeBase64Error'			=> "-40009: base64加密失败",
			'DecodeBase64Error'			=> "-40010: base64解密失败",
			'GenReturnXmlError'			=> "-40011: 生成xml失败",
			'IllegalIv'					=> "-40012: Iv 非法",
			'OK'						=> 0
		);

		return $errorcode[$parameter];
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值