Skip to content

Instantly share code, notes, and snippets.

@theosp
Last active December 21, 2015 06:49
Show Gist options
  • Save theosp/6267129 to your computer and use it in GitHub Desktop.
Save theosp/6267129 to your computer and use it in GitHub Desktop.
<?php
function sendMessageViaApplePush($apns_environment, $certificate, $pushToken, $messageText) {
if ($apns_environment == "development") {
$serverURL = 'gateway.sandbox.push.apple.com:2195';
} else {
$serverURL = 'gateway.push.apple.com:2195';
}
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $certificate);
$fp = stream_socket_client(
'ssl://' . $serverURL, $err, $errstr, 60,
STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if ($fp == null) {
$ans['success'] = '0';
$ans['error_description'] = "Failed to connect to apple server: $err $errstr";
$ans['data'] = 'null';
$jsonAns = json_encode($ans);
echo $jsonAns;
//die();
}
$body['aps'] = array(
'alert' => $messageText,
'sound' => 'default'
);
$payload = json_encode($body);
$apnsMessage =
$msg = chr(1) // command (1 byte)
. pack('N', 0)
. pack('N', time() + 86400)
. pack('n', 32) // token length (2 bytes)
. pack('H*', $pushToken)//) // device token (32 bytes)
. pack('n', strlen($payload)) // payload length (2 bytes)
. $payload; // the JSON payload
$result = @fwrite($fp, $msg, strlen($msg));
if (!$result) {
$ans['success'] = '0';
$ans['error_description'] = 'Fail to send push via IOS';
$ans['data'] = 'null';
$jsonAns = json_encode($ans);
echo $jsonAns;
} else {
$ans['success'] = '1';
$ans['error_description'] = 'null';
$ans['data'] = 'Success to send push via IOS';
$jsonAns = json_encode($ans);
echo $jsonAns;
}
fclose($fp);
}
sendMessageViaApplePush("production", "prod-ipad.pem", "", "Hello");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment