apns-http2-php, Apple push upgrade to HTTP2

Source: Internet
Author: User

Recent company push push upgrade, with Apple HTTP2 Push, HTTP2 the benefits of not say, these online can be found, but really in the project, with PHP written or very little, so write to share with you, nonsense don't say, directly on the code:

pushmessage.php

<?php

Class Pushmessage {
Key to send message when sending APNs server
Const APPLE_RESERVED_NAMESPACE = ' APS ';

/*
* Connect APNs address
* ' https://api.push.apple.com:443/3/device/',//Production environment
* ' https:// api.development.push.apple.com:443/3/device/'//Sandbox environment
*
**/
Private $_appleserviceurl;
//Certificate
Private $_sprovidercertificatefile;
//device token to send to
private $_devicetokens = Array ();
Additional content to send
private $_customproperties;
//private key password
private $_passphrase;
The text message to be pushed
private $_pushmessage;
The voice message to be pushed
private $_pushsoundmessage;
Set the corner label
Private $_nbadge;
Header message sent
private $_headers = Array ();
Private $_errors;
//Push timeout time, if more than this time, automatically do not push, units in seconds
Private $_expiration;
Apple uniquely identifies
private $_apns_topic;
10: Receive now, 5: The screen is off and will be received when the power is saved. If the screen is on, the message will not be received. And this message is a
private $_priority without a sound hint;
The maximum number of seconds that curl allows to execute
private $_timeout;
/**< @type integer Status code for internal error (not Apple). */
Const ST Atus_code_internal_error = 999;

Const ERROR_WRITE_TOKEN = 1000;
Error message returned by Apple server
Protected $_aerrorresponsemessages = Array (
"Sussess",
' Bad Request ',
403 = ' There was a error with the certificate ',
405 = ' The request used a Bad:method value. Only POST requests is 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 ',
$ = ' 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 () {}

/*
* Connect to Apple Server
* @params Certificate_file Certificate
* @params pass_phrase private key password
* @params Apple_service_url the Apple APNs service to be sent
* @params Expiration Push timeout, if more than this time, will automatically not push, units in seconds
* @params apns-topic Apple logo
**/
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->_hsocket = Curl_init ();
if (!defined (curl_http_version_2_0)) {
Define (CURL_HTTP_VERSION_2_0, 3);
}
curl_setopt ($this->_hsocket, curlopt_http_version, curl_http_version_2_0);
curl_setopt ($this->_hsocket, Curlopt_sslcert, $this->_sprovidercertificatefile);
curl_setopt ($this->_hsocket, curlopt_sslcertpasswd, $this->_passphrase);
curl_setopt ($this->_hsocket, Curlopt_sslkeytype, ' PEM ');
curl_setopt ($this->_hsocket, curlopt_timeout, $this->_timeout);

if (! $this->_hsocket) {
$this->_errors[' connserver ' [' cert '] = $this->_sprovidercertificatefile;
$this->_errors[' connserver ' [' desc '] = "Unable to connect to ' {$this->_appleserviceurl} ': $this->_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->_hsocket;
}

/*
* Broken Connection
*
**/
Public Function disconnect () {
if (Is_resource ($this->_hsocket)) {
Return Curl_close ($this->_hsocket);
}
return false;
}

Set Send text message
Public Function Setmessage ($message) {
$this->_pushmessage = $message;
}
Set up send voice messages
Public Function Setsound ($sound _message = ' default ') {
$this->_pushsoundmessage = $sound _message;
}

Gets the text message to send
Public Function GetMessage () {
if (!empty ($this->_pushmessage)) {
return $this->_pushmessage;
}
Return ';
}

Get voice messages
Public Function Getsoundmessage () {
if (!empty ($this->_pushsoundmessage)) {
return $this->_pushsoundmessage;
}
Return ';
}

/*
* Receive device token can be an array, or it can be a single string
*
**/
Public Function Adddevicetoken ($device _token) {
if (Is_array ($device _token) &&!empty ($device _token)) {
$this->_devicetokens = $device _token;
} else {
$this->_devicetokens[] = $device _token;
}
}

Returns the device token to get
Public Function Getdevicetoken ($key = ") {
if ($key!== ") {
return Isset ($this->_devicetokens[$key])? $this->_devicetokens[$key]: Array ();
}
return $this->_devicetokens;
}

Set the corner label
Public Function Setbadge ($nBadge) {
$this->_nbadge = intval ($nBadge);
}
Get the corner label
Public Function Getbadge () {
return $this->_nbadge;
}

/*
* Used to set additional messages
* @params custom_params array $name can not and Self::apple_reserved_namespace (' APS ') sample,
*
**/
Public Function SetCustomProperty ($custom _params) {
foreach ($custom _params as $name = + $value) {
if (Trim ($name) = = Self::apple_reserved_namespace) {
$this->_errors[' SetCustomProperty ' [] = $name. ' Settings not successful, '. $name. ' Can not be set to APS. ';
}
$this->_customproperties[trim ($name)] = $value;
}
}

/*
* Values to get extra settings
* @params string $name
*
**/
Public Function getcustomproperty ($name = ") {
if ($name!== ") {
return Isset ($this->_customproperties[trim ($name)])? $this->_customproperties[trim ($name)]: ";
}

return $this->_customproperties;
}

/**
* Messages sent by the organization
*
* @return @type array the payload dictionary.
*/
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);
}

/*
* Push Message
*
**/
Public function Send () {
if (! $this->_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;
}

$tmpfile = Tmpfile ();
foreach ($this->_devicetokens as $token) {
$sendMessage = $this->getpayload ();
curl_setopt ($this->_hsocket, Curlopt_url, $this->_appleserviceurl. $token);
curl_setopt ($this->_hsocket, Curlopt_postfields, $sendMessage);
curl_setopt ($this->_hsocket, Curlopt_httpheader, $this->_headers);
curl_setopt ($this->_hsocket, Curlopt_file, $tmpfile);

$response _info = curl_exec ($this->_hsocket);
$response _code = curl_getinfo ($this->_hsocket,curlinfo_http_code);

if (! $response _info) {
$this->_errors[' send ' [' Exec_curl '] [' desc '] = "curl Connect Faild";
$this->_errors[' send ' [' Exec_curl '] [' time '] = Date ("Y-m-d h:i:s", Time ());
}

$response _errors = Array ();
Fseek ($tmpfile, 0);
while (($line = fgets ($tmpfile))!== false) {
$response _errors[] = Json_decode ($line, true);
}

if ($response _code! = 200) {
$this->_writeerrormessage ($response _errors, $response _code, $token);
}
}

Fclose ($tmpfile);
$this->_devicetokens = Array ();
return true;
}

Get errors during send
Public Function GetError () {
return $this->_errors;
}

/*
* Read error message
* @params res_errors Send the details of the failure
* @params Res_code response header returned error code
* @params token to send failed device tokens
**/
protected function _writeerrormessage ($res _errors, $res _code, $token) {
if (Isset ($this->_aerrorresponsemessages[$res _code])) {
$this->_errors[' send ' [' response '] [] = Array (
' Reason ' = $res _errors,
' Response_code ' = $res _code,
' msg ' = $this->_aerrorresponsemessages[$res _code],
' token ' = $token,
' Time ' = Date ("Y-m-d h:i:s", Time ())
);
} else {
$this->_errors[' send ' [' response '] [] = Array (
' Reason ' = $res _errors,
' Response_code ' = $res _code,
' token ' = $token,
' Time ' = Date ("y-m-d h:i:s")
);
}

$this->disconnect ();
Sleep (0.5);
$this->_resconnect ();
}

Re-connect
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;
}

}

Use:

Include "pushmessage.php";

$obj = new Pushmessage ();

$params = Array (

' Certificate_file ' = certificate path,//. Pem file

' Apple_service_url ' =//Production environment: ' https://api.push.apple.com:443/3/device/' sandbox environment ' https:// api.development.push.apple.com:443/3/device/'

' Pass_phrase ' =//This is the certificate's private key password
' Apns-topic ' =//apple Unique logo, this is not a random string, should be the application of Apple push the time some of it, specifically unclear, this to ask the person in charge

' Expiration ' =>0,//Push the timeout time, if more than this time, will automatically not push, units in seconds, the general default is 0

' Priority ' = 10,//10: Receive now, 5: The screen is off and will be received when the power is saved. If the screen is on, the message will not be received. And this kind of message is no sound hint, generally 10

' Timeout ' = 30,//curl time-out, in seconds

);

Set the text to be sent or a sound or a corner label to call on your own request

$obj->connserver ($params);

$obj->setmessage = "text to send";

$obj->setsound = "sounds to be sent";

$obj->adddevicetoken= Array ();//or a single device token to be sent to the Apple token

$obj->setbadge = 1;//Set the corner label

$obj->setcustomproperty = Array (' a ' = = ' B ');//Other additional parameters sent

$obj->getpayload (); Organization Send

$obj->send ();//Send

$obj->geterror ();//Get errors during the send process

$obj->disconnect ();//Broken connection

Note: reprint please indicate the source, thank you!

apns-http2-php, Apple push upgrade to HTTP2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.