class.gcmpushmessage.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /*
  3. Class to send push notifications using Google Cloud Messaging for Android
  4. Example usage
  5. -----------------------
  6. $an = new GCMPushMessage($apiKey);
  7. $an->setDevices($devices);
  8. $response = $an->send($message);
  9. -----------------------
  10. $apiKey Your GCM api key
  11. $devices An array or string of registered device tokens
  12. $message The mesasge you want to push out
  13. @author Matt Grundy
  14. Adapted from the code available at:
  15. http://stackoverflow.com/questions/11242743/gcm-with-php-google-cloud-messaging
  16. */
  17. class GCMPushMessage {
  18. var $url = 'https://android.googleapis.com/gcm/send';
  19. var $serverApiKey = "";
  20. var $devices = array();
  21. /*
  22. Constructor
  23. @param $apiKeyIn the server API key
  24. */
  25. function GCMPushMessage($apiKeyIn){
  26. $this->serverApiKey = $apiKeyIn;
  27. }
  28. /*
  29. Set the devices to send to
  30. @param $deviceIds array of device tokens to send to
  31. */
  32. function setDevices($deviceIds){
  33. if(is_array($deviceIds)){
  34. $this->devices = $deviceIds;
  35. } else {
  36. $this->devices = array($deviceIds);
  37. }
  38. }
  39. /*
  40. Send the message to the device
  41. @param $message The message to send
  42. @param $data Array of data to accompany the message
  43. */
  44. function send($message, $data = false){
  45. if(!is_array($this->devices) || count($this->devices) == 0){
  46. $this->error("No devices set");
  47. }
  48. if(strlen($this->serverApiKey) < 8){
  49. $this->error("Server API Key not set");
  50. }
  51. $fields = array(
  52. 'registration_ids' => $this->devices,
  53. 'data' => array( "message" => $message ),
  54. );
  55. if(is_array($data)){
  56. foreach ($data as $key => $value) {
  57. $fields['data'][$key] = $value;
  58. }
  59. }
  60. $headers = array(
  61. 'Authorization: key=' . $this->serverApiKey,
  62. 'Content-Type: application/json'
  63. );
  64. // Open connection
  65. $ch = curl_init();
  66. // Set the url, number of POST vars, POST data
  67. curl_setopt( $ch, CURLOPT_URL, $this->url );
  68. curl_setopt( $ch, CURLOPT_POST, true );
  69. curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
  70. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
  71. curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
  72. // Execute post
  73. $result = curl_exec($ch);
  74. // Close connection
  75. curl_close($ch);
  76. return $result;
  77. }
  78. function error($msg){
  79. echo "Android send notification failed with error:";
  80. echo "\t" . $msg;
  81. exit(1);
  82. }
  83. }