最近公司push推送升级,用苹果http2进行推送,http2的好处就不说了,这些网上都可以查到,但是真正在项目中用的,用php写的还是特别少,因此,写出来跟大家分享,废话不说了,直接上代码:

pushMessage.php

<?php

class PushMessage {
//发送apns server时发送消息的键
const APPLE_RESERVED_NAMESPACE = 'aps';

/*
* 连接apns地址
* 'https://api.push.apple.com:443/3/device/', // 生产环境
* 'https://api.development.push.apple.com:443/3/device/' // 沙盒环境
*
**/
private $_appleServiceUrl;
//证书
private $_sProviderCertificateFile;
//要发送到的device token
private $_deviceTokens = array();
//额外要发送的内容
private $_customProperties;
//私钥密码
private $_passPhrase;
//要推送的文字消息
private $_pushMessage;
//要推送的语音消息
private $_pushSoundMessage;
//设置角标
private $_nBadge;
//发送的头部信息
private $_headers = array();
private $_errors;
//推送的超时时间,如果超过了这个时间,就自动不推送了,单位为秒
private $_expiration;
//apple 唯一标识
private $_apns_topic;
//10:立即接收,5:屏幕关闭,在省电时才会接收到的。如果是屏幕亮着,是不会接收到消息的。而且这种消息是没有声音提示的
private $_priority;
//cURL允许执行的最长秒数
private $_timeout;
//curl单连接
private $_hSocket;
//curl多连接
private $_multi_hSocket;
/**< @type integer Status code for internal error (not Apple). */
const STATUS_CODE_INTERNAL_ERROR = 999;

const ERROR_WRITE_TOKEN = 1000;
//apple server 返回的错误信息
protected $_aErrorResponseMessages = array(
200 => 'Sussess',
400 => 'Bad request',
403 => 'There was an error with the certificate',
405 => 'The request used a bad :method value. Only POST requests are supported',
410 => 'The device token is no longer active for the topic',
413 => 'The notification payload was too large',
429 => 'The server received too many requests for the same device token',
500 => 'Internal server error',
503 => 'The server is shutting down and unavailable',
self::STATUS_CODE_INTERNAL_ERROR => 'Internal error',
self::ERROR_WRITE_TOKEN => 'Writing token error',
);

public function __construct() {}

/*
* 连接apple server
* @params certificate_file 证书
* @params pass_phrase 私钥密码
* @params apple_service_url 要发送的apple apns service
* @params expiration 推送的超时时间,如果超过了这个时间,就自动不推送了,单位为秒
* @params apns-topic apple标识
**/
public function connServer($params) {
if (empty($params['certificate_file'])) {
return false;
}
$this->_sProviderCertificateFile = $params['certificate_file'];
$this->_appleServiceUrl = $params['apple_service_url'];
$this->_passPhrase = $params['pass_phrase'];
$this->_apns_topic = $params['apns-topic'];
$this->_expiration = $params['expiration'];
$this->_priority = $params['priority'];
$this->_timeout = $params['timeout'];

$this->_headers = array(
'apns-topic:'. $params['apns-topic'],
'apns-priority'. $params['priority'],
'apns-expiration'. $params['expiration']
);

$this->_multi_hSocket = curl_multi_init();

if (!$this->_multi_hSocket) {
$this->_errors['connServer']['cert'] = $this->_sProviderCertificateFile;
$this->_errors['connServer']['desc'] = "Unable to connect to '{$this->_appleServiceUrl}': $this->_multi_hSocket";
$this->_errors['connServer']['nums'] = isset($this->_errors['connServer']['nums']) ? intval($this->_errors['connServer']['nums']) : 0;
$this->_errors['connServer']['nums'] += 1;

return false;
}

return $this->_multi_hSocket;
}

/*
* 断连
*
**/
public function disconnect() {
if (is_resource($this->_multi_hSocket)) {
curl_multi_close($this->_multi_hSocket);
}
if (!empty($this->_hSocket)) {
foreach ($this->_hSocket as $val) {
if (is_resource($val)) {
curl_close($val);
}
}

$this->_hSocket = array();
return true;
}

return false;
}

//设置发送文字消息
public function setMessage($message) {
$this->_pushMessage = $message;
}

//设置发送语音消息
public function setSound($sound_message = 'default') {
$this->_pushSoundMessage = $sound_message;
}

//获取要发送的文字消息
public function getMessage() {
if (!empty($this->_pushMessage)) {
return $this->_pushMessage;
}
return '';
}

//获取语音消息
public function getSoundMessage() {
if (!empty($this->_pushSoundMessage)) {
return $this->_pushSoundMessage;
}
return '';
}

/*
* 接收device token 可以是数组,也可以是单个字符串
*
**/
public function addDeviceToken($device_token) {
if (is_array($device_token) && !empty($device_token)) {
$this->_deviceTokens = $device_token;
} else {
$this->_deviceTokens[] = $device_token;
}
}

//返回要获取的device token
public function getDeviceToken($key = '') {
if ($key !== '') {
return isset($this->_deviceTokens[$key]) ? $this->_deviceTokens[$key] : array();
}
return $this->_deviceTokens;
}

//设置角标
public function setBadge($nBadge) {
$this->_nBadge = intval($nBadge);
}

//获取角标
public function getBadge() {
return $this->_nBadge;
}

/*
* 用来设置额外的消息
* @params custom_params array $name 不能和 self::APPLE_RESERVED_NAMESPACE('aps')样,
*
**/
public function setCustomProperty($custom_params) {
foreach ($custom_params as $name=>$value) {
if (trim($name) == self::APPLE_RESERVED_NAMESPACE) {
$this->_errors['setCustomProperty'][] = $name.'设置不成功,'.$name.'不可以设置成 aps.';
}
$this->_customProperties[trim($name)] = $value;
}
}

/*
* 用来获取额外设置的值
* @params string $name
*
**/
public function getCustomProperty($name = '') {
if ($name !== '') {
return isset($this->_customProperties[trim($name)]) ? $this->_customProperties[trim($name)] : '';
}

return $this->_customProperties;
}

/**
* 组织发送的消息
*
*/
protected function getPayload() {
$aPayload[self::APPLE_RESERVED_NAMESPACE] = array();

if (isset($this->_pushMessage)) {
$aPayload[self::APPLE_RESERVED_NAMESPACE]['alert'] = $this->_pushMessage;
}
if (isset($this->_pushSoundMessage)) {
$aPayload[self::APPLE_RESERVED_NAMESPACE]['sound'] = (string)$this->_pushSoundMessage;
}
if (isset($this->_nBadge)) {
$aPayload[self::APPLE_RESERVED_NAMESPACE]['badge'] = (int)$this->_nBadge;
}

if (is_array($this->_customProperties) && !empty($this->_customProperties)) {
foreach($this->_customProperties as $sPropertyName => $mPropertyValue) {
$aPayload[$sPropertyName] = $mPropertyValue;
}
}

return json_encode($aPayload);
}

/*
* 推送消息
*
**/
public function send() {
if (empty($this->_multi_hSocket)) {
return false;
}

if (isset($this->_errors['connServer'])) {
unset($this->_errors['connServer']);
}

if (empty($this->_deviceTokens)) {
$this->_errors['send']['not_deviceTokens']['desc'] = 'No device tokens';
$this->_errors['send']['not_deviceTokens']['time'] = date("Y-m-d H:i:s",time());
return false;
}

if (empty($this->getPayload())) {
$this->_errors['send']['not_message']['desc'] = 'No message to push';
$this->_errors['send']['not_message']['time'] = date("Y-m-d H:i:s",time());
return false;
}

$hArr = array();
foreach ($this->_deviceTokens as $key=>$token) {
$sendMessage = $this->getPayload();
$this->_hSocket[$key] = curl_init();
if (!defined(CURL_HTTP_VERSION_2_0)) {
define(CURL_HTTP_VERSION_2_0, 3);
}
curl_setopt($this->_hSocket[$key], CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($this->_hSocket[$key], CURLOPT_SSLCERT, $this->_sProviderCertificateFile);
curl_setopt($this->_hSocket[$key], CURLOPT_SSLCERTPASSWD, $this->_passPhrase);
curl_setopt($this->_hSocket[$key], CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($this->_hSocket[$key], CURLOPT_TIMEOUT, $this->_timeout);
curl_setopt($this->_hSocket[$key], CURLOPT_URL, $this->_appleServiceUrl . $token);
curl_setopt($this->_hSocket[$key], CURLOPT_POSTFIELDS, $sendMessage);
curl_setopt($this->_hSocket[$key], CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($this->_hSocket[$key], CURLOPT_RETURNTRANSFER, 1);

if (!$this->_hSocket[$key]) {
$this->_errors['send']['cert'] = $this->_sProviderCertificateFile;
$this->_errors['send']['desc'][$key] = "Unable to connect to '{$this->_appleServiceUrl}': $this->_hSocket[$key]";
} else {
array_push($hArr, $this->_hSocket[$key]);
curl_multi_add_handle($this->_multi_hSocket,$this->_hSocket[$key]);
}
}
if (empty($hArr)) {
$this->_errors['send']['hSocket'] = "all socket link faild";
$this->_errors['send']['time'] = date("Y-m-d H:i:s", time());

return false;
}

$running = null;
do {
curl_multi_exec($this->_multi_hSocket, $running);
} while ($running > 0);

foreach ($hArr as $h) {
$info = curl_getinfo($h);
$response_errors = curl_multi_getcontent($h);
if ($info['http_code'] !== 200) {
$device_token = explode('/',$info['url']);
$this->_writeErrorMessage(json_decode($response_errors, true), $info['http_code'], array_pop($device_token));
}
curl_multi_remove_handle($this->_multi_hSocket, $h);
}

$this->_deviceTokens = array();
return true;
}

//获取发送过程中的错误
public function getError() {
return $this->_errors;
}

/*
* 读取错误信息
*@params res_errors 发送失败的具体信息
*@params res_code 响应头返回的错误code
*@params token 发送失败的device token
**/
protected function _writeErrorMessage($res_errors, $res_code, $token) {
$errors = array(
'reason' => $res_errors,
'response_code' => $res_code,
'token' => $token,
'time' => date("Y-m-d H:i:s",time())
);
if (isset($this->_aErrorResponseMessages[$res_code])) {
$errors['msg'] = $this->_aErrorResponseMessages[$res_code];
}
$this->_errors['send']['response'][] = $errors;

$this->disconnect();
sleep(0.5);
$this->_resConnect();
}

//重新连接
protected function _resConnect() {
$conn_res = $this->connServer(array(
'certificate_file' => $this->_sProviderCertificateFile,
'apple_service_url' => $this->_appleServiceUrl,
'pass_phrase' => $this->_passPhrase,
'priority' => $this->_priority,
'apns-topic' => $this->_apns_topic,
'expiration' => $this->_expiration,
'timeout' => $this->_timeout
));

if (!$conn_res) {
$this->_errors['connServer']['res_conn_nums'] = isset($this->_errors['connServer']['res_conn_nums']) ? intval($this->_errors['connServer']['res_conn_nums']) : 0;
$this->_errors['connServer']['res_conn_nums'] += 1;
if ($this->_errors['connServer']['res_conn_nums'] >=5) {
return false;
}

return $this->_resConnect();
}
if (isset($this->_errors['connServer'])) {
unset($this->_errors['connServer']);
}
return true;
}

}

使用:

include "pushMessage.php";

$obj = new PushMessage();

$params = array(

  'certificate_file' =>证书路径 ,// .pem 文件

  'apple_service_url' => // 生产环境: 'https://api.push.apple.com:443/3/device/'  沙盒环境 'https://api.development.push.apple.com:443/3/device/'

  'pass_phrase' => //这个是证书的私钥密码
  'apns-topic'  => //apple唯一标识,这个不是随便的字符串,应该是申请苹果推送的时候有的吧,具体不清楚,这个要问负责人

  'expiration' =>0,  //推送的超时时间,如果超过了这个时间,就自动不推送了,单位为秒, 一般默认为0

  'priority'  => 10,//10:立即接收,5:屏幕关闭,在省电时才会接收到的。如果是屏幕亮着,是不会接收到消息的。而且这种消息是没有声音提示的,一般为10

  'timeout' => 30,//curl超时时间,单位为秒

);

//设置发送的文字还是声音或者角标什么的按自己的需求调用

$obj->connServer($params);

$obj->setMessage = "要发送的文字";

$obj->setSound = "要发送的声音";

$obj->addDeviceToken= array();//或者单个的device token, 要发送到的apple token

$obj->setBadge = 1;//设置角标

$obj->setCustomProperty = array('a'=>'b');//其他额外发送的参数

$obj->getPayload(); //组织发送

$obj->send();//发送

$obj->getError();//获取发送过程中的错误

$obj->disconnect();//断连

注意:转载请注明出处,谢谢!

apns-http2-php,苹果push升级到http2的更多相关文章

  1. http2及server push

      本文主要研究下java9+springboot2+undertow2启用http2及server push maven <parent> <groupId>org.spri ...

  2. nginx openssl升级支持http2

    阿里云openssl升级,实现nginx主动推送 nginx主动推送能够有效减少不必要的报文传输,减少用户请求次数,以达到更快访问速度 现有版本检查 [root@node3 ~]# openssl v ...

  3. 再谈HTTP2性能提升之背后原理—HTTP2历史解剖

    即使千辛万苦,还是把网站升级到http2了,遇坑如<phpcms v9站http升级到https加http2遇到到坑>. 因为理论相比于 HTTP 1.x ,在同时兼容 HTTP/1.1 ...

  4. golang apns升级到http2

    记录一下golang中升级apns,使用http2替换http1.1的详细过程. apns使用http2的好处就不用再说了,网上一搜一堆信息.苹果的apns推送在2015年8月就支持了http2协议, ...

  5. APNS IOS PHP 苹果推送

    IOS---APNS 消息推送实践 首先,需要一个pem的证书,该证书需要与开发时签名用的一致. 具体生成pem证书方法如下: 1. 登录到 iPhone Developer Connection P ...

  6. nginx如何启用对HTTP2的支持 | nginx如何验证HTTP2是否已启用

    nginx启用HTTP2特性 查看当前nginx的编译选项 1 #./nginx -V 2   3 nginx version: nginx/1.9.15 4 built by gcc 5.4.0 2 ...

  7. ios APNS注册失败 本地push

    - (void)addLocalNotice:(NSString *)titlepush { if (@available(iOS 10.0, *)) { UNUserNotificationCent ...

  8. 记升级一次的http2学习

    首先,就先对比下http2和http1.X的区别和升级它的优势吧. 在 HTTP .X 中,为了性能考虑,我们会引入雪碧图.将小图内联.使用多个域名等等的方式.这一切都是因为浏览器限制了同一个域名下的 ...

  9. http2 技术整理 nginx 搭建 http2 wireshark 抓包分析 server push 服务端推送

    使用 nginx 搭建一个 http2 的站点,准备所需: 1,域名 .com .net 均可(国内域名需要 icp 备案) 2,云主机一个,可以自由的安装配置软件的服务器 3,https 证书 ht ...

随机推荐

  1. 多态&&父类调用子类特有的方法

    /* 多态 1.没有继承就没有多态 2.代码的体现:父类类型的指针指向子类对象 3.好处:如果函数\方法参数使用的是父类对象,可以传入父类.子类对象 4.局限性: 1>父类类型的变量,不能直接调 ...

  2. 使用JAXP进行sax解析

    package cn.liuning.sax; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactor ...

  3. socket编程实现HTTP请求

    利用c++语言+socket实现HTTP请求,请求获得的数据效果图如下: HTTP协议的下一层是TCP,根据HTTP协议只需要利用TCP发送下面的数据到达目标主机,目标主机就会发送相应的数据到客户端. ...

  4. 【BZOJ】【1070】【SCOI2007】修车

    网络流/费用流 好神奇的建模= = 关键就是把每个技术员拆成n个点,表示这个技术员倒数第几个修的车子.. 考虑第i个工人,他修第j辆车只对后面要修的车有影响,而前面修过的车已经对当前没有影响了.而这个 ...

  5. ffmpeg参数解释

    基本选项: -formats 输出所有可用格式 -f fmt 指定格式(音频或视频格式) -i filename 指定输入文件名,在linux下当然也能指定: 0.0(屏幕录制)或摄像头 -y 覆盖已 ...

  6. Unity3d游戏中添加移动MM支付SDK问题处理

    原地址:http://www.tuicool.com/articles/I73QFb 由于移动mm的SDK将部分资源文件放在jar包中,导致Unity无法识别,提示failed to find res ...

  7. 词法分析器flex的使用

    词法分析器flex的功能说起来就是一句话,将正则表达式转化为c代码. flex编译成功后会生成一个flex.exe的可执行文件.此时,我们需要一个定义了正则表达式 动作的input文件.例如test. ...

  8. mysql中文乱码解决

    有时服务端显示中文正常,但在客户端却显示?乱码, 首先,系统字符集, echo $LANG vi .bash_profile export $LANG=en_us.utf8 另一个是, mysql的, ...

  9. DevOps 和技术债务偿还自动化

    当企业想要迁移到一个 DevOps 模型时,经常需要偿还高等级的技术债务 说得更明确一点,机构往往陷入「技术债务的恶性循环」中,以至于任何迅速.敏捷的迁移方式都无法使用.这是技术债务中的希腊债务危机水 ...

  10. POJ2104 K-th Number Range Tree

    又是区间第k大,这次选择这道题是为以后写线段树套平衡树铺路的.Range Tree可以理解成线段树套vector吧,相当于每个结点多存了对应区间的一个排好序的序列.画一下就会知道空间的消耗是nlogn ...