小程序授权、获取手机号

后端基本上是组装一些前端请求来的一些参数,再请求腾讯返回信息给前端

 

1、auth

前端传 code


 

2、前端传 code 、iv 、encryptedData到后端,后端解密,获取用户信息

3个文件 1、smallWx.php(主类)   2. wxBizDataCrypt.php(加载的解密类)3.errorCode.php ()

1、

'');  //定义参数
            $data = @http_build_query($data);  //把参数转换成URL数据
            $aContext = array('http' => array('method' => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $data ));

            $cxContext  = stream_context_create($aContext);
            $sUrl = $post_wx_url; //此处必须为完整路径
            $d = @file_get_contents($sUrl,false,$cxContext);
            $re_arr_d = json_decode($d,true);
            // 将session_id和session_value存表
            $sid = session_id();
            $pc = new WXBizDataCrypt('wx79a47af4c6205509', $re_arr_d['session_key']);
            $errCode = $pc->decryptData($encryptedData, $iv, $return_data );
			
            if ($errCode == 0) {
                //$return_data = json_decode($return_data,true);
				echo $return_data;
			}else{
				echo json_encode(array('code'=>-200,"msg"=>'后端报错'));
			}

2、

sessionKey = $sessionKey;
		$this->appid = $appid;
	}


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

        
		if (strlen($iv) != 24) {
			return 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 ErrorCode::$IllegalBuffer;
		}
		if( $dataObj->watermark->appid != $this->appid )
		{
			return ErrorCode::$IllegalBuffer;
		}
		$data = $result;
		return ErrorCode::$OK;
	}

}

3、



 *    
  • -41001: encodingAesKey 非法
  • *
  • -41003: aes 解密失败
  • *
  • -41004: 解密后得到的buffer非法
  • *
  • -41005: base64加密失败
  • *
  • -41016: base64解密失败
  • * */ class ErrorCode { public static $OK = 0; public static $IllegalAesKey = -41001; public static $IllegalIv = -41002; public static $IllegalBuffer = -41003; public static $DecodeBase64Error = -41004; } ?>

     

    你可能感兴趣的:(小程序)