user975561
user975561

Reputation: 514

Communicate with APNS from PHP

I would like to communicate with the Apple Push Notification Service from a PHP script. But I keep getting following error:

Warning: stream_socket_client(): Unable to set private key file

I have a .pem-file which looks like this:

-----BEGIN CERTIFICATE-----
     Encrypted String
-----END CERTIFICATE-----
     Bag Attributes
     friendlyName: ...
     localKeyID: ...
     Key Attributes: ...
-----BEGIN RSA PRIVATE KEY-----
     Proc-Type: ...
     DEK-Info: ...

     Encrypted String
-----END RSA PRIVATE KEY-----

I am running the PHP script from sudo. It can find my .pem file, because if I remove it, I get a "handshake failure" error instead.

What could be wrong here?

Upvotes: 0

Views: 1571

Answers (2)

user975561
user975561

Reputation: 514

I got it working. It turns out I exported my private key which I generated for the push notifications instead of the corresponding certificate.

Upvotes: 0

Jordi Kroon
Jordi Kroon

Reputation: 2597

I recently made a script to send remote pushnotifications. This is how I did it:

  $message = "A cool message!";
  $deviceid = "";

  $count = 0;

  $ctx = stream_context_create();
  stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-dev.pem'); 

  $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

  if (!$fp) {
     echo 'Failed to connect ' . $err . $errstr;
  } else {

     $payloads['aps'] = array('alert' => $message, 'badge' => 1, 'sound' => 'default');
     $payload = json_encode($payloads);

     $msg = chr(0) . pack('n',32) . pack('H*', $deviceid) . pack('n',strlen($payload)) . $payload;
     fwrite($fp, $msg);
     $count += 1;
     fclose($fp);

  }   

  echo 'Sended: ' . $count;

Upvotes: 1

Related Questions