在拿到App發送過來的deviceToken和產品經理的推送payload以後,做爲服務端程序員的咱們,還須要作一個操做,那就是生成並加密JSON Web Token (JWT),而後才能把這三個一塊兒發送給APNs。php
關於JWT身份驗證令牌的概念以及如何在蘋果開發者網站獲取簽名密鑰(Key)在個人教程中都有講解,不熟悉的同窗能夠再去看一下。程序員
這裏主要說一下如何在服務端用PHP語言web
使用框架:jwt-framework算法
composer require web-token/jwt-framework
json
<?php
require_once 'vendor/autoload.php';
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\Converter\StandardConverter;
use Jose\Component\KeyManagement\JWKFactory;
use Jose\Component\Signature\JWSBuilder;
use Jose\Component\Signature\Algorithm\ES256;
use Jose\Component\Signature\Serializer\CompactSerializer;
複製代碼
<?php
function getToken($cerPath, $keyID, $teamId) {
// 1.建立ES256算法
$algorithmManager = AlgorithmManager::create([
new ES256()
]);
// 2.用蘋果開發者網站建立的p8文件(簽名密鑰)建立JSON web key($cerPath爲p8文件的路徑)
$jwk = JWKFactory::createFromKeyFile($cerPath);
// JSON轉化器
$jsonConverter = new StandardConverter();
// 實例化JWSBuilder
$jwsBuilder = new JWSBuilder(
$jsonConverter,
$algorithmManager
);
// 3.建立JWT的payload部分(iat爲當前時間戳,iss爲開發者帳號TeamID)
$payload = $jsonConverter->encode([
'iat' => time(),
'iss' => $teamId,
]);
// 4.生成並加密JWT
$jws = $jwsBuilder
->create() // 建立
->withPayload($payload) // 設定JWT的payload
->addSignature($jwk, ['alg' => 'ES256', 'kid' => $keyID]) // 用JSON web key和蘋果規定的JWTheader簽名加密
->build(); // 生成
$serializer = new CompactSerializer($jsonConverter); // 序列化工具
// 5.序列化JWT
$token = $serializer->serialize($jws); // 序列化上面的jws,只有一個簽名,故index爲0的便可
return $token;
}
複製代碼
<?php
function sendPush($deviceToken, $authToken, $payload) {
// 1.建立一個帶有deviceToken的path(其實就是字串)-蘋果規定必須這麼寫
$path = '/3/device/'.$deviceToken;
$curl = curl_init();
curl_setopt_array($curl, array(
// 2.帶上deviceToken向APNs服務器請求
CURLOPT_URL => "https://api.development.push.apple.com:443".$path,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "POST",
// 3.把推送的payload放入請求體+設置請求頭
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"apns-expiration: 0",
"apns-push-type: alert",
"apns-topic: com.example.app", // 4.咱們App的bundleID
"authorization: bearer ".$authToken // 5.上面生成並加密的JWT
),
));
//發送請求
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
複製代碼
<?php
$token = getToken('key/path/mykey.p8', 'Key ID', 'Team ID');
$payload = json_encode(['aps' => ['alert' => 'Hi there!']]);
sendPush('9fbb61136e03c.................', $token, $payload);
複製代碼