Comment envoyer des messages push APNs à l'aide de la clé Auth APNs et des outils CLI standard?

Apple a récemment ajouté une nouvelle méthode d'authentification à APNS ( clé D'authentification Apple Push Notification (Sandbox & Production) ).

enter image description here

la clé téléchargée est un fichier .p8 avec une clé privée:

$ cat APNSAuthKey_3HHEB343FX.p8
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBH...Already.Revoked...lHEjCX1v51W
-----END PRIVATE KEY-----

j'utilise les messages APNs en utilisant l'ancienne méthode - en les ajoutant au porte-clés, en demandant un certificat et en utilisant OpenSSL pour envoyer des messages à gateway.production.push.apple.com:2195 .

Comment envoyer des notifications push en utilisant les outils standard de CLI Linux (OpenSSL, Python, etc.) en utilisant le nouveau format?

29
demandé sur Community 2016-10-09 15:36:50

3 réponses

si vous avez curl avec le support HTTP/2 et openssl avec le support ECDSA installé sur votre machine, vous pouvez utiliser le script suivant pour tester les notifications push en utilisant une clé D'Auth APNs:

#!/bin/bash

deviceToken=b27371497b85611baf9052b4ccfb9641ab7fea1d01c91732149c99cc3ed9342f

authKey="./APNSAuthKey_ABC1234DEF.p8"
authKeyId=ABC1234DEF
teamId=TEAM123456
bundleId=com.example.myapp
endpoint=https://api.development.push.apple.com

read -r -d '' payload <<-'EOF'
{
   "aps": {
      "badge": 2,
      "category": "mycategory",
      "alert": {
         "title": "my title",
         "subtitle": "my subtitle",
         "body": "my body text message"
      }
   },
   "custom": {
      "mykey": "myvalue"
   }
}
EOF

# --------------------------------------------------------------------------

base64() {
   openssl base64 -e -A | tr -- '+/' '-_' | tr -d =
}

sign() {
   printf ""| openssl dgst -binary -sha256 -sign "$authKey" | base64
}

time=$(date +%s)
header=$(printf '{ "alg": "ES256", "kid": "%s" }' "$authKeyId" | base64)
claims=$(printf '{ "iss": "%s", "iat": %d }' "$teamId" "$time" | base64)
jwt="$header.$claims.$(sign $header.$claims)"

curl --verbose \
   --header "content-type: application/json" \
   --header "authorization: bearer $jwt" \
   --header "apns-topic: $bundleId" \
   --data "$payload" \
   $endpoint/3/device/$deviceToken

NOTE: j'utilise une légère variation de ce script pour tester sur macOS avec tire-lait versions de curl et openssl: http://thrysoee.dk/apns /

43
répondu Jess Thrysoee 2017-07-23 07:20:17

vous pouvez envoyer une notification push par NODE JS en utilisant la clé D'authentification Apple Push Notification (Sandbox & Production). Apple a fourni un tutoriel dans ce lien

ce tutoriel a toutes les étapes pour créer la clé D'authentification Apple Push Notification et configurer un serveur local pour exécuter le code JS de noeud pour envoyer la notification push. Vous pouvez lancer le code dans votre machine locale et tester la notification push.

Espérons que cela aidera.

9
répondu Teena nath Paul 2016-10-22 20:02:55

Voilà en Php à quoi il ressemble. Ce script renvoie le code d'état de 200 ok ainsi que l'id du token généré.

// THE FINAL SCRIPT WITHOUT DEPENDENCIES!!! ...except curl with http2
$device_token = "a0abd886etc...";
//echo $key;
$kid      = "YOURKEYID";
$teamId   = "YOURTEAMID";
$app_bundle_id = "your.app.bundle";
$base_url = "https://api.development.push.apple.com";

$header = ["alg" => "ES256", "kid" => $kid];
$header = base64_encode(json_encode($header));

$claim = ["iss" => $teamId, "iat" => time()];
$claim = base64_encode(json_encode($claim));

$token = $header.".".$claim;
// key in same folder as the script
$filename = "KeyFromApple.p8";
$pkey     = openssl_pkey_get_private("file://{$filename}");
$signature;
openssl_sign($token, $signature, $pkey, 'sha256');
$sign = base64_encode($signature);

$jws = $token.".".$sign;

$message = '{"aps":{"alert":"You are welcome.","sound":"default"}}';

function sendHTTP2Push($curl, $base_url, $app_bundle_id, $message, $device_token, $jws) {

    $url = "{$base_url}/3/device/{$device_token}";
    // headers
    $headers = array(
        "apns-topic: {$app_bundle_id}",
        'Authorization: bearer ' . $jws
    );
    // other curl options
    curl_setopt_array($curl, array(
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
        CURLOPT_URL => $url,
        CURLOPT_PORT => 443,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POST => TRUE,
        CURLOPT_POSTFIELDS => $message,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => FALSE,
        CURLOPT_HEADER => 1
    ));
    // go...
    $result = curl_exec($curl);
    if ($result === FALSE) {
        throw new Exception("Curl failed: " .  curl_error($curl));
    }
    print_r($result."\n");
    // get response
    $status = curl_getinfo($curl);
    return $status;
}
// open connection
$curl = curl_init();
sendHTTP2Push($curl, $base_url, $app_bundle_id, $message, $device_token, $jws);
3
répondu Nicolas Manzini 2017-10-12 13:32:42