New APNS Provider API and PHP

前端 未结 7 1238
余生分开走
余生分开走 2020-12-08 01:10

I started creating some code based upon this for sending push notifications from PHP.

However now that I have understood there is a new API which utilizes HTTP/2 and

7条回答
  •  Happy的楠姐
    2020-12-08 01:39

    With the new HTTP/2 APNS provider API, you can use curl to send push notifications.

    EDIT

    Before proceeding (as noted by @Madox), openssl >= 1.0.2e of should be installed (from package preferably). Verify with the command

    openssl version
    

    a) Your version of PHP should be >= 5.5.24 so that the constant CURL_HTTP_VERSION_2_0 is defined.

    b) Make sure that you have curl version 7.46+ installed in your system with

    curl --version
    

    c) Curl should have http/2 support enabled. In the output when typing the previous command, you should see a line like this one:

    Features: IDN IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets 
    

    if HTTP2 doesn't show up, you can follow this excellent tutorial to install http/2 for curl https://serversforhackers.com/video/curl-with-http2-support

    Verify that curl detected openssl >= 1.0.2e, doing curl --version should output something like this:

    curl 7.47.1 (x86_64-pc-linux-gnu) libcurl/7.47.1 OpenSSL/1.0.2f zlib/1.2.8 libidn/1.28 nghttp2/1.8.0-DEV librtmp/2.3
    

    e) Once you everything installed, you can test it in the command line:

    curl -d '{"aps":{"alert":"hi","sound":"default"}}' \ 
    --cert : \ 
    -H "apns-topic: " \ 
    --http2  \ 
    https://api.development.push.apple.com/3/device/
    

    f) Here is a sample code in PHP that I have successfully tried:

    if(defined('CURL_HTTP_VERSION_2_0')){
    
        $device_token   = '...';
        $pem_file       = 'path to your pem file';
        $pem_secret     = 'your pem secret';
        $apns_topic     = 'your apns topic. Can be your app bundle ID';
    
    
        $sample_alert = '{"aps":{"alert":"hi","sound":"default"}}';
        $url = "https://api.development.push.apple.com/3/device/$device_token";
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $sample_alert);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("apns-topic: $apns_topic"));
        curl_setopt($ch, CURLOPT_SSLCERT, $pem_file);
        curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $pem_secret);
        $response = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        //On successful response you should get true in the response and a status code of 200
        //A list of responses and status codes is available at 
        //https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH107-SW1
    
        var_dump($response);
        var_dump($httpcode);
    
    }
    

提交回复
热议问题