首頁 > php教程 > php手册 > 主體

通过apple 的apns推送信息

WBOY
發布: 2016-06-06 19:37:47
原創
1130 人瀏覽過

通过apple的apns推送信息 无 ?phpclass phpApns{ /** * @var string 证书地址 */ protected $cert_path; /** * @var string 使用的密码 */ protected $password; /** * @var bool 是否是沙箱 */ protected $is_sandbox; /** * @var string 正式推送服务器 */

通过apple 的apns推送信息
<?php
class phpApns
{
    /**
     * @var string 证书地址
     */
    protected $cert_path;

    /**
     * @var string 使用的密码
     */
    protected $password;

    /**
     * @var bool 是否是沙箱
     */
    protected $is_sandbox;

    /**
     * @var string 正式推送服务器
     */
    protected $publish_uri = 'ssl://gateway.push.apple.com:2195';

    /**
     * @var string 沙箱推送服务器
     */
    protected $sandbox_uri = 'ssl://gateway.sandbox.push.apple.com:2195';

    /**
     * @param string $cert_path 使用的证书地址
     * @param bool $is_sandbox 是否是沙箱
     */
    public function __construct($cert_path = '', $password, $is_sandbox = false)
    {
        if (false == is_file($cert_path))
        {
            die("证书文件不存在!");
        }

        $this->cert_path  = $cert_path;
        $this->password   = $password;
        $this->is_sandbox = $is_sandbox;
    }

    /**
     * @param $device_token 设备的token
     * @param $msg 发送的消息
     * @param string $sound 推送的提示声音
     */
    public function pushMessage($device_token, $msg, $sound = 'default')
    {
        $apns = stream_context_create();
        stream_context_set_option($apns, 'ssl', 'local_cert', $this->cert_path);
        stream_context_set_option($apns, 'ssl', 'passphrase', $this->password);
        if ($this->is_sandbox)
        {
            $uri = $this->sandbox_uri;
        }
        else
        {
            $uri = $this->publish_uri;
        }

        // 设置60s的超时
        $fp = stream_socket_client($uri, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $apns);
        if (!$fp)
        {
            $errMsg = "连接打开失败: ($err)$errstr";
            die($errMsg);
        }

        // 组成发送apns的信息流
        $body['aps'] = array(
            'alert' => $msg,
            'sound' => $sound
        );
        $json        = json_encode($body);
        // 转成二进制流
        $message     = chr(0) . pack('n', 32) . pack('H*', $device_token) . pack('n', strlen($json)) . $json;

        $result = fwrite($fp, $message, strlen($message));
        if (!$result)
        {
            die('信息推送失败!');
        }

        fclose($fp);
        echo '推送成功!';
    }
}
登入後複製
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!