PHP stream_context_create() equivalent in perl - php

I am following a tutorial https://blog.serverdensity.com/how-to-build-an-apple-push-notification-provider-server-tutorial/ to implement connectivity with apple APNS server. The tutorial provided a php code for this:
// Open the connection
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
// Send the payload
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
// Close Resources
socket_close($apns);
fclose($apns);
I want to write this in Perl. What is the best equivalent of PHP's stream_context_create(). I tried something like the below, but didnt work.
use IO::Socket::SSL;
my $client = IO::Socket::SSL->new(
# where to connect
PeerHost => "gateway.sandbox.push.apple.com",
PeerPort => "2195",
SSL_cert_file =>'localcert.pem',
) or die "failed connect or ssl handshake: $!,$SSL_ERROR";

Related

APNS notification using swift

iOS 11.x Swift 4.0
Yes, I know there a dozens solutions out there that will send push notifications for you, but I am looking to create a native solution.
Now I managed to put some PHP code together that works, within it I construct a APNS payload and then pack it's way off to Apple, which of course sends it to my client. It is only 10 lines of code, but now I need to convert it to Swift.
$payload='{
"aps": {
"alert":{
"title": "Yo",
"body":"Stay Cool" },
"badge":99,
"category":"new.category",
"sound": "default"
},
"misc": "tag"
}';
$apnsHost = 'gateway.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-dev.pem';
$deviceToken = '7effd4dfc158d922c867c1e3c99fd46296e2b1afcd080a63a2da398bce1c9bb3';
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
echo $error;
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
?>
I find this answer on SO which looks like my man, but no ... there is no certificate [.pem] on this is there?
How should Secure Transport TLS be used with BSD sockets in Swift?
I am out my depth right now? Any help/pointers to the right path desperately needed?

PHP apple push notification fail when multiple

I have written a function to send push notifications to iOS devices. It sends pushes to more than 100 devices for now. However sometimes it is not sending push notifications. When I debug through the process I identified based on push notification the whole process fails. but the issues is all push tokens are in valid format. So my initial code was like this.
$certificatePath = CERTIFICATE_PATH . "/".APN_CERTIFICATE_FILE;
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $certificatePath);
stream_context_set_option($streamContext, 'ssl', 'passphrase', APN_PASSWORD);
$apns = stream_socket_client(APN_HOST . ':' . APN_PORT , $error, $errorString, 2, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $streamContext);
if (!$apns) {
echo "Failed to connect $err $errstrn";
return false;
}
$payload = array();
$payload['aps'] = array('alert' =>$message,'title'=>$title, 'sound' => 'default','data'=>array());
$payload = json_encode($payload);
foreach ($pushTokens as $pushToken)
{
$pushToken = str_replace(' ', '', $pushToken);
if(!ctype_xdigit($pushToken))
continue;
$apnsMessage = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $pushToken)) . pack ("n",strlen($payload)) . $payload;
$rst = fwrite($apns, $apnsMessage);
}
fclose($apns);
As a fix I changed the code to different way. I know this code is expensive since it open and close connection for every push notification.
$certificatePath = CERTIFICATE_PATH . "/".APN_CERTIFICATE_FILE;
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $certificatePath);
stream_context_set_option($streamContext, 'ssl', 'passphrase', APN_PASSWORD);
$payload = array();
$payload['aps'] = array('alert' =>$message,'title'=>$title, 'sound' => 'default','data'=>array());
$payload = json_encode($payload);
foreach ($pushTokens as $pushToken)
{
$apns = stream_socket_client(APN_HOST . ':' . APN_PORT , $error, $errorString, 2, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $streamContext);
if (!$apns) {
echo "Failed to connect $err $errstrn";
return false;
}
$pushToken = str_replace(' ', '', $pushToken);
if(!ctype_xdigit($pushToken))
continue;
$apnsMessage = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $pushToken)) . pack ("n",strlen($payload)) . $payload;
$rst = fwrite($apns, $apnsMessage);
fclose($apns);
}
I am wondering if it is an issue with fwrite or somewhere else. Appreciate if someone can help me with my first method as it is speed, and run with minimum resources.

Unable to send push notification to ios using php

I am trying to send a push notification to IOS using php and Yii framework. I created a function as follows to get data and send notification. $data is an array which contains a message and an array inside to keep registration IDs (device tokens). I ran it on my localhost but notification is not sent to my device. By the way, the output of my function is an integer value and I cannot recognize if the message has been sent or what!?
Is there anything wrong in my code?
private function _pushIOS($data)
{
// Create a connection
$apnsHost = $this->_notificationUrl;
$apnsPort = 2195;
$apnsCert = Yii::app()->controller->createUrl('/').'/my_certificate_dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
if (!$apns)
exit("Failed to connect: $error $errorString" . PHP_EOL);
foreach($data['registration_ids'] as $deviceToken) {
$body = array();
$body['aps'] = array(
'alert' => $data['data']['message'],
'badge' => 1,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($apns, $apnsMessage, strlen($apnsMessage));
}
// Close the socket and connection to the server
#socket_close($apns);
fclose($apns);
return json_decode($result);
}
Finally, I got the answer. The problem was with the pem file path. Absolute path must be passed to the function to work. The following line should be replaced:
$apnsCert = Yii::app()->controller->createUrl('/').'/my_certificate_dev.pem';
Correct path:
$apnsCert = dirname(Yii::app()->request->scriptFile).'/my_certificate_dev.pem';

Python equivalent to php's stream_context_create

I am following a tutorial that requires me to open a socket and send a payload with a certificate: http://blog.serverdensity.com/how-to-build-an-apple-push-notification-provider-server-tutorial/.
I am having a bit of difficulty in figuring out how to do the following with python:
// Open the connection
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
// Send the payload
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
// Close Resources
socket_close($apns);
fclose($apns);
I've used python-requests in the past. But only for simple get requests.
Can I use python-requests to rewrite the above code in python, or is there something better suited for this task?
Looking at the PHP documentation fo stream_context_create, and the tutorial you're following I think what you're trying to accomplish is opening a SSL secured socket connection to gatway.sandbox.push.apple.com.
I think the python module you want to look at is the ssl module. There's an example of connecting to a server from a client, probably setting the keyfile and certfile options of ssl.wrap_socket() to the certificate you created and registered to talk to the apple server.

Enhanced Apple Push Notification: Response error at provider server

i am working on a project in PHP which requires me to push an alert notification on APNS server. I have used enhanced push notification format. but I am not receiving response as specified by the APNS docs. I am getting response in three digits usually 133, 132, 154, 138, etc. Which I concluded to be Status signs, eg. 133 is 1, 3, 3. but now I have also received 139. so I doubt that my interpretation of response is wrong. But I am not getting where it is wrong. And important thing is though I am receiving these responses Alert is getting pushed and I am receiving notification on my iPhone as well as on iPad.
My code is as follows:
$payload['aps'] = array('alert' => $message, 'badge' => 1, 'sound' => 'default');
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195; // default port
$apnsCert = 'apns-dev.pem'; // APNS crtificate.
$passPhrase = '';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
stream_context_set_option($streamContext, 'ssl', 'passphrase', $passPhrase);
try{
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);
if (!$apns) {
print "Failed to connect {$error} {$errorString}\n";
}
else {
// Sending the payload
$apnsMessage = chr(0) . pack('n', 1) . pack('n', $nid) . pack('n', time() + 604800) . pack('n', 32) . pack('H*', str_replace(' ', '', $alert_device_token)) . pack('n', strlen($payload)) . $payload;
echo 'APNS Message: ' . $apnsMessage;
$fwrite = fwrite($apns, $apnsMessage);
echo 'APNS response: ' . $fwrite;
And when this get executed i got the following response printed on the browser:
APNS Message: ��=ŸÂ� òc6–U:õŸŠ ¸Þ ÷ćÚ0ßqšÊzÂífÕnZ�`{"aps":{"alert":"Your EUR\/USD SELL alert price has been reached!","badge":1,"sound":"default"}}APNS response: 139
Can anyone please tell me what does this 139 means here. am doing anything wrong here.
The echoed "139" is the return value of fwrite(). It's the number of bytes written by fwrite()
See: PHP: fwrite

Categories