/php/apns.php
PHP | 278 lines | 235 code | 37 blank | 6 comment | 46 complexity | 3329b9f11ea61f8e0c34bb41ee351b34 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1
- <?php
- error_reporting(-1);
- ini_set('display_errors', 'On');
- $arSendData = [];
- $arSendData['aps']['alert']['title'] = sprintf("Notification Title");
- $arSendData['aps']['alert']['body'] = sprintf("Body text");
- $device_token = '871fb8729ee1109d157fc4ef484cfbee5d4ba671d27fdb3e57defce589bb9d9e'; // Device token
- //Config
- $arParam = [];
- $arParam['teamId'] = 'MG4Y3EEQKV';
- $arParam['authKeyId'] = 'P5FA6G76B5';
- $arParam['apns-topic'] = 'com.mobiblocks.JeannaGabellini';
- $arParam['a8_key'] = '
- -----BEGIN PRIVATE KEY-----
- MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQguJjb2sIIMvguDWO/
- S27MCh/NFko5gU1xxrLnh/WxFDOgCgYIKoZIzj0DAQehRANCAARFJEQlPZJ5il7o
- 2CzKdG1iLG2fDx5BiIy0kmIIV3ps9UNvqaiwwPRtleyDLXbFSpEM3M8vVQWRoVC2
- vZjrULss
- -----END PRIVATE KEY-----
- ';
- $arClaim = ['iss'=>$arParam['teamId'], 'iat'=>time()];
- $arParam['header_jwt'] = JWT::encode($arClaim, $arParam['a8_key'], $arParam['authKeyId'], 'RS256');
- $stat = push_to_apns($arParam, $arSendData, $device_token);
- if($stat == false){
- exit();
- }
- exit();
- function push_to_apns($arParam, $arSendData, $device_token){
- $sendDataJson = json_encode($arSendData);
- $endPoint = 'https://api.development.push.apple.com/3/device';
- // Preparing request header for APNS
- $ar_request_head[] = sprintf("content-type: application/json");
- $ar_request_head[] = sprintf("authorization: bearer %s", $arParam['header_jwt']);
- $ar_request_head[] = sprintf("apns-topic: %s", $arParam['apns-topic']);
- $url = sprintf("%s/%s", $endPoint, $device_token);
- $ch = curl_init($url);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $sendDataJson);
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $ar_request_head);
- $response = curl_exec($ch);
- $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- if(empty(curl_error($ch))){
- return false;
- }
- curl_close($ch);
- return true;
- }
- class JWT
- {
- public static $leeway = 0;
- public static $timestamp = null;
- public static $supported_algs = array(
- 'HS256' => array('hash_hmac', 'SHA256'),
- 'HS512' => array('hash_hmac', 'SHA512'),
- 'HS384' => array('hash_hmac', 'SHA384'),
- 'RS256' => array('openssl', 'SHA256'),
- );
- public static function decode($jwt, $key, $allowed_algs = array())
- {
- $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
- if (empty($key)) {
- throw new InvalidArgumentException('Key may not be empty');
- }
- if (!is_array($allowed_algs)) {
- throw new InvalidArgumentException('Algorithm not allowed');
- }
- $tks = explode('.', $jwt);
- if (count($tks) != 3) {
- throw new UnexpectedValueException('Wrong number of segments');
- }
- list($headb64, $bodyb64, $cryptob64) = $tks;
- if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
- throw new UnexpectedValueException('Invalid header encoding');
- }
- if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
- throw new UnexpectedValueException('Invalid claims encoding');
- }
- $sig = static::urlsafeB64Decode($cryptob64);
- if (empty($header->alg)) {
- throw new UnexpectedValueException('Empty algorithm');
- }
- if (empty(static::$supported_algs[$header->alg])) {
- throw new UnexpectedValueException('Algorithm not supported');
- }
- if (!in_array($header->alg, $allowed_algs)) {
- throw new UnexpectedValueException('Algorithm not allowed');
- }
- if (is_array($key) || $key instanceof \ArrayAccess) {
- if (isset($header->kid)) {
- $key = $key[$header->kid];
- } else {
- throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
- }
- }
- // Check the signature
- if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
- throw new SignatureInvalidException('Signature verification failed');
- }
- // Check if the nbf if it is defined. This is the time that the
- // token can actually be used. If it's not yet that time, abort.
- if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
- throw new BeforeValidException(
- 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
- );
- }
- if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
- throw new BeforeValidException(
- 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
- );
- }
- // Check if this token has expired.
- if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
- throw new ExpiredException('Expired token');
- }
- return $payload;
- }
- public static function encode($payload, $key, $keyId = null, $alg = 'RS256', $head = null)
- {
- $header = array('alg' => 'ES256', 'kid' => $keyId);
- if ($keyId !== null) {
- $header['kid'] = $keyId;
- }
- if ( isset($head) && is_array($head) ) {
- $header = array_merge($head, $header);
- }
- $segments = array();
- $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
- $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
- $signing_input = implode('.', $segments);
- $signature = static::sign($signing_input, $key, $alg);
- $segments[] = static::urlsafeB64Encode($signature);
- return implode('.', $segments);
- }
- public static function sign($msg, $key, $alg = 'RS256')
- {
- if (empty(static::$supported_algs[$alg])) {
- throw new DomainException('Algorithm not supported');
- }
- list($function, $algorithm) = static::$supported_algs[$alg];
- switch($function) {
- case 'hash_hmac':
- return hash_hmac($algorithm, $msg, $key, true);
- case 'openssl':
- $signature = '';
- $success = openssl_sign($msg, $signature, $key, $algorithm);
- if (!$success) {
- throw new DomainException("OpenSSL unable to sign data");
- } else {
- return $signature;
- }
- }
- }
- private static function verify($msg, $signature, $key, $alg)
- {
- if (empty(static::$supported_algs[$alg])) {
- throw new DomainException('Algorithm not supported');
- }
- list($function, $algorithm) = static::$supported_algs[$alg];
- switch($function) {
- case 'openssl':
- $success = openssl_verify($msg, $signature, $key, $algorithm);
- if (!$success) {
- throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string());
- } else {
- return $signature;
- }
- case 'hash_hmac':
- default:
- $hash = hash_hmac($algorithm, $msg, $key, true);
- if (function_exists('hash_equals')) {
- return hash_equals($signature, $hash);
- }
- $len = min(static::safeStrlen($signature), static::safeStrlen($hash));
- $status = 0;
- for ($i = 0; $i < $len; $i++) {
- $status |= (ord($signature[$i]) ^ ord($hash[$i]));
- }
- $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
- return ($status === 0);
- }
- }
- public static function jsonDecode($input)
- {
- if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
- $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
- } else {
- $max_int_length = strlen((string) PHP_INT_MAX) - 1;
- $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
- $obj = json_decode($json_without_bigints);
- }
- if (function_exists('json_last_error') && $errno = json_last_error()) {
- static::handleJsonError($errno);
- } elseif ($obj === null && $input !== 'null') {
- throw new DomainException('Null result with non-null input');
- }
- return $obj;
- }
- public static function jsonEncode($input)
- {
- $json = json_encode($input);
- if (function_exists('json_last_error') && $errno = json_last_error()) {
- static::handleJsonError($errno);
- } elseif ($json === 'null' && $input !== null) {
- throw new DomainException('Null result with non-null input');
- }
- return $json;
- }
- public static function urlsafeB64Decode($input)
- {
- $remainder = strlen($input) % 4;
- if ($remainder) {
- $padlen = 4 - $remainder;
- $input .= str_repeat('=', $padlen);
- }
- return base64_decode(strtr($input, '-_', '+/'));
- }
- public static function urlsafeB64Encode($input)
- {
- return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
- }
- private static function handleJsonError($errno)
- {
- $messages = array(
- JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
- JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
- JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
- );
- throw new DomainException(
- isset($messages[$errno])
- ? $messages[$errno]
- : 'Unknown JSON error: ' . $errno
- );
- }
- private static function safeStrlen($str)
- {
- if (function_exists('mb_strlen')) {
- return mb_strlen($str, '8bit');
- }
- return strlen($str);
- }
- }