實現原理:
1、安裝外部庫php-jwt,在項目的composer.json 同級目錄下運行
composer require firebase/php-jwt
執行失敗的話可借鑑本文:https://blog.csdn.net/qq_24909089/article/details/106055699
2、
<?php
/**
* 蘋果驗證類
* Date: 2019/9/11
*/
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
const AUTH_KEYS_URL = 'https://appleid.apple.com/auth/keys'; //獲取Apple公鑰訪問地址
class Vendor_Interface_Apple
{
/**
* 驗證token是否正常
* 驗證準確性:通過Apple公鑰在線(https://8gwifi.org/jwkconvertfunctions.jsp)得到用於解密的pem公鑰字符串
* @param string $identityToken 前端獲取的token
* @return bool|object
* @throws \Firebase\JWT\InvalidArgumentException
*/
public function apple_jwt_verify($identityToken = '')
{
if(!$identityToken){
return false;
}
//取得下標值
$subscript = 0;
//獲取apple認證祕鑰 :https://appleid.apple.com/auth/keys
$public_key = $this->curl_request(AUTH_KEYS_URL);
if ($public_key['code'] != 200) {
return false;
}
$alg = $public_key['data']['keys'][$subscript]['alg'];
$kid = $public_key['data']['keys'][$subscript]['kid'];
//獲取公鑰
$pem = JWK::parseKeySet($public_key['data']);
//返回包含密鑰詳情的數組
$publicKey = openssl_pkey_get_details($pem[$kid]);
// print_r($publicKey);
// exit;
$decoded = JWT::decode($identityToken, $publicKey['key'], [$alg]);
return $decoded;
}
/**
* curl請求
* @param $url
* @param string $type
* @param string $post_data
* @return array
*/
public function curl_request($url, $type = 'GET', $post_data = '')
{
$curl = curl_init();
$aHeader = Array();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
if ($type == 'POST') {
$aHeader[] = 'Content-type: application/json';
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
}
if (!empty($aHeader)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $aHeader);
}
curl_setopt($curl, CURLOPT_TIMEOUT, 120);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$info = curl_getinfo($curl);
$error_no = curl_errno($curl);
$error_str = curl_error($curl);
curl_close($curl);
$result_array = json_decode($result, true);
if ($info["http_code"] == 200) {
$data = array(
"code" => $info["http_code"],
"data" => $result_array
);
} else {
$data = array(
"code" => $info["http_code"],
"data" => Array(
'time' => date('Y-m-d H:i:s', time()),
'type' => $type,
'url' => $url,
'post_data' => $post_data,
'code' => $info["http_code"],
'body' => $result_array,
'error_no' => $error_no,
'error_str' => $error_str
)
);
}
return $data;
}
}