Heim  >  Artikel  >  php教程  >  通过apple 的apns推送信息

通过apple 的apns推送信息

WBOY
WBOYOriginal
2016-06-06 19:37:471131Durchsuche

通过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 '推送成功!';
    }
}
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:Modoer_3.5_MC最新20150313Nächster Artikel:PHP写简单的新闻发布系统