PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/php/apns.php

https://bitbucket.org/jitdxpert/speeddialweb
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
  1. <?php
  2. error_reporting(-1);
  3. ini_set('display_errors', 'On');
  4. $arSendData = [];
  5. $arSendData['aps']['alert']['title'] = sprintf("Notification Title");
  6. $arSendData['aps']['alert']['body'] = sprintf("Body text");
  7. $device_token = '871fb8729ee1109d157fc4ef484cfbee5d4ba671d27fdb3e57defce589bb9d9e'; // Device token
  8. //Config
  9. $arParam = [];
  10. $arParam['teamId'] = 'MG4Y3EEQKV';
  11. $arParam['authKeyId'] = 'P5FA6G76B5';
  12. $arParam['apns-topic'] = 'com.mobiblocks.JeannaGabellini';
  13. $arParam['a8_key'] = '
  14. -----BEGIN PRIVATE KEY-----
  15. MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQguJjb2sIIMvguDWO/
  16. S27MCh/NFko5gU1xxrLnh/WxFDOgCgYIKoZIzj0DAQehRANCAARFJEQlPZJ5il7o
  17. 2CzKdG1iLG2fDx5BiIy0kmIIV3ps9UNvqaiwwPRtleyDLXbFSpEM3M8vVQWRoVC2
  18. vZjrULss
  19. -----END PRIVATE KEY-----
  20. ';
  21. $arClaim = ['iss'=>$arParam['teamId'], 'iat'=>time()];
  22. $arParam['header_jwt'] = JWT::encode($arClaim, $arParam['a8_key'], $arParam['authKeyId'], 'RS256');
  23. $stat = push_to_apns($arParam, $arSendData, $device_token);
  24. if($stat == false){
  25. exit();
  26. }
  27. exit();
  28. function push_to_apns($arParam, $arSendData, $device_token){
  29. $sendDataJson = json_encode($arSendData);
  30. $endPoint = 'https://api.development.push.apple.com/3/device';
  31. // Preparing request header for APNS
  32. $ar_request_head[] = sprintf("content-type: application/json");
  33. $ar_request_head[] = sprintf("authorization: bearer %s", $arParam['header_jwt']);
  34. $ar_request_head[] = sprintf("apns-topic: %s", $arParam['apns-topic']);
  35. $url = sprintf("%s/%s", $endPoint, $device_token);
  36. $ch = curl_init($url);
  37. curl_setopt($ch, CURLOPT_POSTFIELDS, $sendDataJson);
  38. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
  39. curl_setopt($ch, CURLOPT_HTTPHEADER, $ar_request_head);
  40. $response = curl_exec($ch);
  41. $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  42. if(empty(curl_error($ch))){
  43. return false;
  44. }
  45. curl_close($ch);
  46. return true;
  47. }
  48. class JWT
  49. {
  50. public static $leeway = 0;
  51. public static $timestamp = null;
  52. public static $supported_algs = array(
  53. 'HS256' => array('hash_hmac', 'SHA256'),
  54. 'HS512' => array('hash_hmac', 'SHA512'),
  55. 'HS384' => array('hash_hmac', 'SHA384'),
  56. 'RS256' => array('openssl', 'SHA256'),
  57. );
  58. public static function decode($jwt, $key, $allowed_algs = array())
  59. {
  60. $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
  61. if (empty($key)) {
  62. throw new InvalidArgumentException('Key may not be empty');
  63. }
  64. if (!is_array($allowed_algs)) {
  65. throw new InvalidArgumentException('Algorithm not allowed');
  66. }
  67. $tks = explode('.', $jwt);
  68. if (count($tks) != 3) {
  69. throw new UnexpectedValueException('Wrong number of segments');
  70. }
  71. list($headb64, $bodyb64, $cryptob64) = $tks;
  72. if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
  73. throw new UnexpectedValueException('Invalid header encoding');
  74. }
  75. if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
  76. throw new UnexpectedValueException('Invalid claims encoding');
  77. }
  78. $sig = static::urlsafeB64Decode($cryptob64);
  79. if (empty($header->alg)) {
  80. throw new UnexpectedValueException('Empty algorithm');
  81. }
  82. if (empty(static::$supported_algs[$header->alg])) {
  83. throw new UnexpectedValueException('Algorithm not supported');
  84. }
  85. if (!in_array($header->alg, $allowed_algs)) {
  86. throw new UnexpectedValueException('Algorithm not allowed');
  87. }
  88. if (is_array($key) || $key instanceof \ArrayAccess) {
  89. if (isset($header->kid)) {
  90. $key = $key[$header->kid];
  91. } else {
  92. throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
  93. }
  94. }
  95. // Check the signature
  96. if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
  97. throw new SignatureInvalidException('Signature verification failed');
  98. }
  99. // Check if the nbf if it is defined. This is the time that the
  100. // token can actually be used. If it's not yet that time, abort.
  101. if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
  102. throw new BeforeValidException(
  103. 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
  104. );
  105. }
  106. if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
  107. throw new BeforeValidException(
  108. 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
  109. );
  110. }
  111. // Check if this token has expired.
  112. if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
  113. throw new ExpiredException('Expired token');
  114. }
  115. return $payload;
  116. }
  117. public static function encode($payload, $key, $keyId = null, $alg = 'RS256', $head = null)
  118. {
  119. $header = array('alg' => 'ES256', 'kid' => $keyId);
  120. if ($keyId !== null) {
  121. $header['kid'] = $keyId;
  122. }
  123. if ( isset($head) && is_array($head) ) {
  124. $header = array_merge($head, $header);
  125. }
  126. $segments = array();
  127. $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
  128. $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
  129. $signing_input = implode('.', $segments);
  130. $signature = static::sign($signing_input, $key, $alg);
  131. $segments[] = static::urlsafeB64Encode($signature);
  132. return implode('.', $segments);
  133. }
  134. public static function sign($msg, $key, $alg = 'RS256')
  135. {
  136. if (empty(static::$supported_algs[$alg])) {
  137. throw new DomainException('Algorithm not supported');
  138. }
  139. list($function, $algorithm) = static::$supported_algs[$alg];
  140. switch($function) {
  141. case 'hash_hmac':
  142. return hash_hmac($algorithm, $msg, $key, true);
  143. case 'openssl':
  144. $signature = '';
  145. $success = openssl_sign($msg, $signature, $key, $algorithm);
  146. if (!$success) {
  147. throw new DomainException("OpenSSL unable to sign data");
  148. } else {
  149. return $signature;
  150. }
  151. }
  152. }
  153. private static function verify($msg, $signature, $key, $alg)
  154. {
  155. if (empty(static::$supported_algs[$alg])) {
  156. throw new DomainException('Algorithm not supported');
  157. }
  158. list($function, $algorithm) = static::$supported_algs[$alg];
  159. switch($function) {
  160. case 'openssl':
  161. $success = openssl_verify($msg, $signature, $key, $algorithm);
  162. if (!$success) {
  163. throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string());
  164. } else {
  165. return $signature;
  166. }
  167. case 'hash_hmac':
  168. default:
  169. $hash = hash_hmac($algorithm, $msg, $key, true);
  170. if (function_exists('hash_equals')) {
  171. return hash_equals($signature, $hash);
  172. }
  173. $len = min(static::safeStrlen($signature), static::safeStrlen($hash));
  174. $status = 0;
  175. for ($i = 0; $i < $len; $i++) {
  176. $status |= (ord($signature[$i]) ^ ord($hash[$i]));
  177. }
  178. $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
  179. return ($status === 0);
  180. }
  181. }
  182. public static function jsonDecode($input)
  183. {
  184. if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  185. $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
  186. } else {
  187. $max_int_length = strlen((string) PHP_INT_MAX) - 1;
  188. $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
  189. $obj = json_decode($json_without_bigints);
  190. }
  191. if (function_exists('json_last_error') && $errno = json_last_error()) {
  192. static::handleJsonError($errno);
  193. } elseif ($obj === null && $input !== 'null') {
  194. throw new DomainException('Null result with non-null input');
  195. }
  196. return $obj;
  197. }
  198. public static function jsonEncode($input)
  199. {
  200. $json = json_encode($input);
  201. if (function_exists('json_last_error') && $errno = json_last_error()) {
  202. static::handleJsonError($errno);
  203. } elseif ($json === 'null' && $input !== null) {
  204. throw new DomainException('Null result with non-null input');
  205. }
  206. return $json;
  207. }
  208. public static function urlsafeB64Decode($input)
  209. {
  210. $remainder = strlen($input) % 4;
  211. if ($remainder) {
  212. $padlen = 4 - $remainder;
  213. $input .= str_repeat('=', $padlen);
  214. }
  215. return base64_decode(strtr($input, '-_', '+/'));
  216. }
  217. public static function urlsafeB64Encode($input)
  218. {
  219. return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
  220. }
  221. private static function handleJsonError($errno)
  222. {
  223. $messages = array(
  224. JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  225. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  226. JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
  227. );
  228. throw new DomainException(
  229. isset($messages[$errno])
  230. ? $messages[$errno]
  231. : 'Unknown JSON error: ' . $errno
  232. );
  233. }
  234. private static function safeStrlen($str)
  235. {
  236. if (function_exists('mb_strlen')) {
  237. return mb_strlen($str, '8bit');
  238. }
  239. return strlen($str);
  240. }
  241. }