微信小程序登录
<?php
/*start 登录 start*/
$code = "";
$iv = "";
$encryptedData = "";
$LoginWxXcx = new LoginWxXcx();
$LoginWxXcx->setCode($code);
$LoginWxXcx->setIv($iv);
$LoginWxXcx->encryptedData($encryptedData);
return $LoginWxXcx->initialization();
/*end 登录 end*/
/**
* 微信小程序登录
* Created by Sublime.
* User: dongfh
* Date: 2020/07/14
*/
class LoginWxXcx
{
/**
* error code 微信解密错误说明.
* <ul>
* <li>-41001: encodingAesKey 非法</li>
* <li>-41003: aes 解密失败</li>
* <li>-41004: 解密后得到的buffer非法</li>
* <li>-41005: base64加密失败</li>
* <li>-41016: base64解密失败</li>
* </ul>
*/
private static $OK = 0;
private static $IllegalAesKey = -41001;
private static $IllegalIv = -41002;
private static $IllegalBuffer = -41003;
private static $DecodeBase64Error = -41004;
/**
* error code 业务错误说明.
* <ul>
* <li>1000: 成功</li>
* <li>1004: 失败</li>
* <li>1005: 业务失败</li>
* </ul>
*/
private static $success = 1000;
private static $fail = 1004;
private static $business = 1005;
private static $appid = "xxxx";
private static $appsecret = "xxxx";
private static $sessionKeyUri = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
private $openid;
private $sessionKey;
private $member_id;
private $UserToken;
private $encryptedData;
public function setEncryptedData($encryptedData){
$this->encryptedData = $encryptedData;
}
private $iv;
public function setIv($iv){
$this->iv = $iv;
}
private $code;
public function setCode($code){
$this->code = $code;
}
/**
* [initialization 初始化登录]
* @return [type] [description]
*/
public function initialization(){
//获取openID
$this->getOpenId();
//获取用户ID
$this->getMemberId();
//获取User-Token
$this->getUserToken();
$info = [
"user_token" => $this->UserToken
];
return $this->JsonSuccess($info,"登录成功",self::$success);
}
/**
* [getOpenId 获取openID]
* @return [type] [description]
*/
private function getOpenId(){
//替换数据传输过程中的空格为+
$this->encryptedData = str_replace(' ','+',$this->encryptedData);
$this->iv = str_replace(' ','+',$this->iv);
//格式化请求地址 请求接口
$sessionKeyUri = sprintf(self::$sessionKeyUri,self::$appid,self::$appsecret,$this->code);
$result = $this->https_request($sessionKeyUri);
$result = json_decode($result, true);
if(empty($result['openid']) || empty($result['session_key'])){
return $this->JsonError("获取sessionKey失败",self::$business,["errmsg" => $result["errmsg"]]);
}
$this->openid = $result['openid'];
$this->sessionKey = $result['session_key'];
}
/**
* [getMemberId 获取用户ID]
* @return [type] [description]
*/
private function getMemberId(){
//查询数据
$userInfo_db = Db::name("member")->where("openid",$this->openid)->find();
//用户不存在去注册
if(empty($userInfo_db["id"])){
//解密用户信息
$errCode = $this->decryptData($data);
if($errCode != 0){
return $this->JsonError("信息解密失败",self::$business,["errCode" => $errCode]);
}
$userInfo = json_decode($data,true);
//解密成功
if(!empty($userInfo['openId'])){
$Member_params = [
"nickname" => $userInfo["nickName"],
"avatar" => $userInfo["avatarUrl"],
"openid" => $userInfo["openId"],
"create_time" => time()
];
$user_id = Db::name("member")->insert($Member_params);
if(!$user_id){
return $this->JsonError("注册用户信息失败!",self::$fail,$Member_params);
}
$userInfo_db = Db::name("member")->where("member_id",$user_id)->find();
}else{
return $this->JsonError("解密用户信息失败!",self::$business,$userInfo);
}
}
if(empty($userInfo_db["id"])){
return $this->JsonError("获取用户信息失败!",self::$business,["openid" => $this->openid]);
}
$this->member_id = $userInfo_db["id"];
}
/**
* [getUserToken 获取User-Token]
* @return [type] [description]
*/
private function getUserToken(){
//生成用户User-Token
$UserToken = $this->generateUserToken();
$timestamp = time() + 2592000;
//查询token
$MemberToken = Db::name("MemberToken")->where("member_id",$this->member_id)->find();
//不存在
if(!$MemberToken){
$Params = [
"member_id" => $this->member_id ,
"token" => $UserToken ,
"create_time" => $timestamp
];
$result = Db::name("MemberToken")->insert($Params);
if(!$result){
return $this->JsonError("添加token失败",self::$fail,$Params);
}
}else{
$timeParams = [
"token" => $UserToken ,
"update_time" => $timestamp
];
$result = Db::name("MemberToken")->where("member_id",$this->member_id)->update($timeParams);
if(!$result){
return $this->JsonError("更改过期时间失败",self::$fail,$timeParams);
}
}
$this->UserToken = $UserToken."#".base64_encode($this->member_id);
}
/**
* [generateUserToken 生成token]
* @return [type] [description]
*/
private function generateUserToken(){
$token = strtoupper(md5($this->member_id.'dongfh_'.mt_rand(100,999)));
return $token;
}
/**
* 检验数据的真实性,并且获取解密后的明文.
* @param $data string 解密后的原文
* @return int 成功0,失败返回对应的错误码
*/
private function decryptData(&$data){
if (strlen($this->sessionKey) != 24) {
return self::$IllegalAesKey;
}
$aesKey = base64_decode($this->sessionKey);
if (strlen($iv) != 24) {
return self::$IllegalIv;
}
$aesIV = base64_decode($this->iv);
$aesCipher = base64_decode($this->encryptedData);
$result = openssl_decrypt($aesCipher,"AES-128-CBC",$aesKey,1,$aesIV);
$dataObj = json_decode($result);
if($dataObj == NULL){
return self::$IllegalBuffer;
}
if($dataObj->watermark->appid != self::$appid){
return self::$IllegalBuffer;
}
$data = $result;
return self::$OK;
}
/**
* [https_request 请求]
* @param [type] $url [路径]
* @param [type] $data [参数]
* @return [type] [description]
*/
private function https_request($url, $data = null) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
if(curl_errno($curl)){
$output = curl_error($curl);
}
curl_close($curl);
return $output;
}
/**
* [JsonSuccess 返回数据]
* @param [type] $data [数据]
* @param string $msg [信息]
* @param integer $code [状态码]
*/
private function JsonSuccess($data=[],$msg='成功',$code=1000){
$data = [
"code" => $code,
"msg" => $msg,
"data" => $data
];
return json_encode($data);
}
/**
* [JsonError 返回数据]
* @param integer $code [状态码]
* @param string $msg [信息]
* @param [type] $data [数据]
*/
private function JsonError($msg='失败',$code=1004,$data=[]){
return $this->JsonSuccess($data,$msg,$code);
}
}
?>