public function actionGetToken(){
$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);
$code = $data['code'] ;
$encryptedData = $data['encryptedData'] ;
$iv = $data['iv'] ;
//首先要知道微信方使用的是AES-128-CBC加密的:
BaseToolService::info($data,"get-token-data") ;
$appid = "XXXXXXXXXXX" ;
$appsecert = "XXXXXXXXXXXXXXXXXXXXXX" ;
$url = "https://api.weixin.qq.com/sns/jscode2session?" . "appid=%s&secret=%s&js_code=%s&grant_type=authorization_code" ;
$url = sprintf($url, $appid, $appsecert, $code);
$rs = HttpService::curlGet($url) ;
$wxResult = json_decode($rs, true);
BaseToolService::info($wxResult,"wxapp") ;
if (empty($wxResult)) {
return ["errcode"=>1,"msg"=>"获取session_key及openID时异常,微信内部错误"];
// 为什么以empty判断是否错误,这是根据微信返回
// 规则摸索出来的
// 这种情况通常是由于传入不合法的code
}
else {
// 建议用明确的变量来表示是否成功
// 微信服务器并不会将错误标记为400,无论成功还是失败都标记成200
// 这样非常不好判断,只能使用errcode是否存在来判断
$loginFail = array_key_exists('errcode', $wxResult);
if ($loginFail) {
return ["errcode"=>$wxResult['errcode'],"msg"=>$wxResult['errmsg']];
} else {
$sessionKey = $wxResult['session_key'];
$openid = $wxResult['openid'];
$aesKey = base64_decode($sessionKey);// 对称解密的秘钥 aeskey
$aesIV = base64_decode($iv); // 对称解密算法初始向
$aesCipher = base64_decode($encryptedData); // 对称解密的密文
$decrypted = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, OPENSSL_RAW_DATA, $aesIV);
BaseToolService::info($decrypted,"wxapp-decrypted") ;
return ["errcode"=>0,"msg"=>"成功","data"=>$openid];
}
}
}