使用 PHP 通过 APNs 发送 iOS 推送通知

Posted

技术标签:

【中文标题】使用 PHP 通过 APNs 发送 iOS 推送通知【英文标题】:Using PHP to send iOS Push Notifications via APNs 【发布时间】:2018-01-06 19:15:59 【问题描述】:

我已经在我的项目中实现了推送通知,到目前为止一切正常。我试过通过 Pusher 发送通知,结果很好。 但我必须通过 php 发送它们,这还不能正常工作。 我找到了很多关于如何实现这一点的旧解释,但似乎没有一个对我有用。

这是我正在尝试使用的:

    // APNs Push testen auf Token
$deviceToken = $_GET['key']; // Device-Token

// Payload erstellen und JSON codieren
$payload['aps'] = array('alert' => 'TitleText', 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);

$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'certificate.pem';

// Stream erstellen
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'certificate.cer', $apnsCert);

$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
if ($apns)

  // Nachricht erstellen und senden
  $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
  fwrite($apns, $apnsMessage);

  // Verbindung schliessen
  fclose($apns);

else

  echo "Fehler!";
  var_dump($error);
  var_dump($errorString);

【问题讨论】:

【参考方案1】:

尝试使用这个 php 脚本,确保 .pem 证书在运行时与该 php 脚本在同一路径中退出,同时获得正确的设备令牌

 <?php
        /* We are using the sandbox version of the APNS for development. For production
        environments, change this to ssl://gateway.push.apple.com:2195 */
        $apnsServer = 'ssl://gateway.sandbox.push.apple.com:2195';
        /* Make sure this is set to the password that you set for your private key
        when you exported it to the .pem file using openssl on your OS X */
        $privateKeyPassword = '1234';
        /* Put your own message here if you want to */
        $message = 'Welcome to ios 7 Push Notifications';
        /* Pur your device token here */
        $deviceToken =
        '05924634A8EB6B84437A1E8CE02E6BE6683DEC83FB38680A7DFD6A04C6CC586E';
        /* Replace this with the name of the file that you have placed by your PHP
        script file, containing your private key and certificate that you generated
        earlier */
        $pushCertAndKeyPemFile = 'PushCertificateAndKey.pem';
        $stream = stream_context_create();
        stream_context_set_option($stream,
        'ssl',
        'passphrase',
        $privateKeyPassword);
        stream_context_set_option($stream,
        'ssl',
        'local_cert',
        $pushCertAndKeyPemFile);

        $connectionTimeout = 20;
        $connectionType = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
        $connection = stream_socket_client($apnsServer,
        $errorNumber,
        $errorString,
        $connectionTimeout,
        $connectionType,
        $stream);
        if (!$connection)
        echo "Failed to connect to the APNS server. Error no = $errorNumber<br/>";
        exit;
         else 
        echo "Successfully connected to the APNS. Processing...</br>";
        
        $messageBody['aps'] = array('alert' => $message,
        'sound' => 'default',
        'badge' => 2,
        );
        $payload = json_encode($messageBody);
        $notification = chr(0) .
        pack('n', 32) .
        pack('H*', $deviceToken) .
        pack('n', strlen($payload)) .
        $payload;
        $wroteSuccessfully = fwrite($connection, $notification, strlen($notification));
        if (!$wroteSuccessfully)
        echo "Could not send the message<br/>";
        
        else 
        echo "Successfully sent the message<br/>";
        
        fclose($connection);

  ?>

【讨论】:

嘿汗,感谢您的帮助。但它似乎不起作用:/我收到数字 0 的错误。我也试过这个:'stream_context_set_option($stream, 'ssl', 'cafile', 'entrust_2048_ca.cer'); ´ 这也无济于事。 开发还是发行? 我使用分布 $apnsServer = 'ssl://gateway.push.apple.com:2195'; 从头开始做所有事情后,它再次工作。谢谢!【参考方案2】:

这是脚本的新更新,因为 Apple 更改了通知 url:

<?php
    if ( defined("CURL_VERSION_HTTP2") && (curl_version()["features"] & CURL_VERSION_HTTP2) !== 0) 
        $ch = curl_init();
        $body ['aps'] = array (
            "alert" => array (
                "title"  => "hii",
            ),
            "sound"  => "default"
        );
        $curlconfig = array(
            CURLOPT_URL => "https://api.development.push.apple.com/3/device/device_token",
            CURLOPT_RETURNTRANSFER =>true,
            CURLOPT_POSTFIELDS => json_encode($body),
            CURLOPT_SSLCERT =>"apns.pem",
            CURLOPT_SSLCERTPASSWD => "123456",
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
            CURLOPT_VERBOSE => true
        );
        curl_setopt_array($ch, $curlconfig);
        $res = curl_exec($ch);
        if ($res === FALSE) 
                echo('Curl failed: ' . curl_error($ch));
        
        curl_close($ch);
    else
        echo "No HTTP/2 support on client.";
    
       
    ?>

谢谢,希望对你有帮助!!!。

【讨论】:

【参考方案3】:
<?php

    function sendFCM($body, $title, $id, $StudentAdmissionId, $activitytype) 
        $url = "https://fcm.googleapis.com/fcm/send";
        $token = $id;
        $serverKey = 'AAAA8XYL2Y8:APA91bF1fsddfgffdssdsdfsdsdsda8zyWJTgs0OSeiRlk9WQqLwKn51VkMH_XSbpRuiCTU-Fdi2hoV8JY8ST7gCBQe4dlMFASDbr5Oci1bLmg9tyl5dlxyFDauWWCMItUNdFGWO_CWhpHwSIbvbqYwlCnoRd7ucB';
        $notification = array(
            'title' => $title,
            'text' => $body,
            'sound' => 'default',
            'badge' => 1,
            'category' => $activitytype,
            'content-available' => 1
        );
        $arrayToSend = array(
            'to' => $token,
            'notification' => $notification,
            'priority' => 'high'
        );
        $json = json_encode($arrayToSend);
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key=' . $serverKey;
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        //Send the request
        echo $response = curl_exec($ch);
        //Close request
        if ($response === FALSE) 
            die('FCM Send Error: ' . curl_error($ch));
        
        curl_close($ch);
        mysql_query("INSERT INTO `tbl_notifications`(`n_activity_name`,`n_user_id`,`n_device_id`, `n_notification`) VALUES ('$activitytype','$StudentAdmissionId','$id','$response')");
        // #Echo Result Of FireBase Server
        return $response;
    

?>

将此用于 php 和 mysql 后端,以同时在 android 和 ios 上推送通知

这里apns服务器的token存储在db中,传递给发送fcm

【讨论】:

以上是关于使用 PHP 通过 APNs 发送 iOS 推送通知的主要内容,如果未能解决你的问题,请参考以下文章

iOS APNs 推送通知 - 开发

与 APNS 服务器交互以向 iOS 设备发送推送通知的最简单方法是啥?

PHP - APNs 消息已交付但在 iOS 设备上未收到

发送 507 推送消息后 APNS 关闭连接

带有 PHP 的 iOS 13 APNS

设备离线时,apns 丢弃了旧的推送通知