PHP实现IOS消息推送

PHP实现IOS消息推送

参数含义

参数 含义
deviceToken 目标设备的令牌
  /**
     * @param bool $is_dev
     * @param array $data
     * @param string $bundle_id
     * @return bool|int|void
     * iOS推送
     */
    public function ios_push($is_dev = TRUE, $data = array(), $bundle_id = ''){
        $deviceToken = $this->deviceToken; //没有空格
        $body = array("aps" => array("alert" => $data['message'],"badge" => $data['badge'],"sound"=>$data['sound']));  //推送方式,包含内容和声音

        #$gateway_prod = 'tls://gateway.push.apple.com:2195';
        #$gateway_sand = 'tls://gateway.sandbox.push.apple.com:2195';

        $gateway_prod = 'ssl://gateway.push.apple.com:2195';
        $gateway_sand = 'ssl://gateway.sandbox.push.apple.com:2195';

        $gateway = $gateway_sand;
        if(!$is_dev) {
            $gateway = $gateway_prod;
        }
        $ctx = stream_context_create();
         //如果在Windows的服务器上,寻找pem路径会有问题,路径修改成这样的方法:
         //$pem = dirname(__FILE__) . '/' . 'aps_development.pem';
         //linux 的服务器直接写pem的路径即可
        $file = 'aps_development.pem';
        if(!$is_dev) {
            $file = 'aps.pem';
        }
        $dir = dirname(dirname(dirname(__DIR__ )))."/extend/certs/";
        $filepath = $dir . $file;
        if(!empty($bundle_id)) {
            $dir_bundle = $dir . $bundle_id . '/';
            $file_bundle = $dir_bundle . $file;
            if(is_dir($dir_bundle) && is_file($file_bundle)) {
                $filepath = $file_bundle;
            }
        }
        $pass = "";

        #dump($filepath);exit;
        #stream_context_set_option($ctx,"ssl","local_cert","apns-dev.pem");
        #stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
        stream_context_set_option($ctx, 'ssl', 'local_cert', $filepath);
        stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
        $err = 'ftp';
        $errstrn = '';
         //此处有两个服务器需要选择,如果是开发测试用,选择第二名sandbox的服务器并使用Dev的pem证书,如果是正是发布,使用Product的pem并选用正式的服务器
        $fp = stream_socket_client($gateway, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        $fp = stream_socket_client($gateway, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        if (!$fp) {
            echo "Failed to connect $err $errstrn";
            return;
        }
        print "Connection OK\n";
        $payload = json_encode($body);
        $msg = chr(0) . pack("n",32) . pack("H*", str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
        echo "sending message :" . $payload ."\n";
        $res = fwrite($fp, $msg,strlen($msg));
        fclose($fp);
        return $res;
    }

你可能感兴趣的:(php)