?phpclass phpApns{ /** * @var string 证书地址 */ protected $cert_path; /** * @var string 使用的密码 */ protected $password; /** * @var bool 是否是沙箱 */ protected $is_sandbox; /** * @var string 正式推送服务器 */ protec
<?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 '推送成功!';
}
}
