Newer
Older
Import / applications / MakePDF / Website / payment / impl / send_push.php
<?php

//
// General background info:
//   https://blog.stackpath.com/build-apple-push-notification-provider-server/
// However the connection method is outdated, the HTTPS method works instead.
// Basic certificate steps are:
// 
// 1) On apple developer site, login and generate a push notification certificate
// 2) Download it and import it in to keychain, then from keychain export both
// the certificate and the private key.
// 3) Convert the p12 format to PEM and recombine:
//    $ openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12
//    $ openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12
//    $ openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem
//    $ cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem
//
// The code is based on this up to date way to send the request:
//   https://gist.github.com/valfer/18e1052bd4b160fed86e6cbb426bb9fc
//
//! @param $message  the payload to send (JSON)
//! @return          the status code
function SendPushNotification($message)
{
  // Apple's push notification server url
  $http2_server = 'https://api.development.push.apple.com';   // or 'api.push.apple.com' if production
  $app_bundle_id = 'com.subflexion.blockyfroggy';
  $apns_cert = '/home/subflexion_public/WickedDocs/Website/apns-dev.pem';
  $token = 'bce35bab3eb4000de0b1c08364ab4e6d89f274832a4dfe2d514b06ab149ae24a';
  $message = '{"aps":{"alert":"' . $message . '","sound":"default"}}';

  // open connection
  if (!defined('CURL_HTTP_VERSION_2_0'))
  {
    define('CURL_HTTP_VERSION_2_0', 3);
  }
  $http2ch = curl_init();
  curl_setopt($http2ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);

  // url (endpoint)
  $url = "{$http2_server}/3/device/{$token}";

  // certificate
  $cert = realpath($apns_cert);

  // headers
  $headers = array(
    "apns-topic: {$app_bundle_id}",
    "User-Agent: My Sender"
  );

  // other curl options
  curl_setopt_array($http2ch, array(
    CURLOPT_URL => "{$url}",
    CURLOPT_PORT => 443,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POST => TRUE,
    CURLOPT_POSTFIELDS => $message,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSLCERT => $cert,
    CURLOPT_HEADER => 1
  ));

  // go...
  $result = curl_exec($http2ch);
  if ($result === FALSE) {
    throw new Exception('Curl failed with error: ' . curl_error($http2ch));
  }

  // get respnse
  $status = curl_getinfo($http2ch, CURLINFO_HTTP_CODE);
  
  // close connection
  curl_close($http2ch);
  return $status;
}

?>