close

 

以 PHP 實做 Apple APNs 及 Android GCM 的 Push Notification 呼叫

本篇以 PHP 針對 Android / Apple 行動裝置的訊息推播呼叫(Push Notification)程式,編寫兩隻簡單的 class 呼叫。此範例程式碼僅供參考使用,依各人使用狀況可自行修改內容並使用。此兩者實際測試過皆可正常傳送。

如有需要可參考官方介紹

更詳細的申請使用及程式編寫部分等有空在補上,以下直接提供程式碼部分。

 

Apple APNs 發送代碼

 /*
    Community Cloud System Class

    @filename : apple.pn.class.php
    @author   : kerash
    @date     : 2013.06.26
    Apple Push Notification Service code
    [Push notification through APNs in php]
 */
class ApplePNs
{
    // Apple Push Notification Server path for push notification 
    var $ApplePushNotificationServer = "ssl://gateway.push.apple.com:2195";

    // Apple .pem file name
    var $PEMfile = "";
    // .pem pass phrase
    var $PEMpassphrase = "";

    // notify sound
    var $aps_sound = "default";
    // notify badge
    var $aps_badge = "0";

    function __Construct($pem)
    {
        if(!empty($pem))
        {
            if(strrpos($pem,".pem")===FALSE) {
                $pem .= ".pem";
            }
            $this->PEMfile = $pem;
        }
    }

    function set_pem  ($pem)   { $this->PEMfile = $pem; }
    function set_pass ($passphrase) { $this->PEMpassphrase = $passphrase; }
    function set_sound($sound) {$this->aps_sound = $sound; }
    function set_badge($badge) {$this->aps_badge = $badge; }

    function pushNotification($devices , $msg , $ntfyType = "")
    {

        $device_id  = $devices;
        $message    = $msg;
        $notifyType = $ntfyType;

        /* if data is null , then return false */
        if( count($device_id) <= 0 or trim($message) == "")
        {             return false;         }

         $ctx = stream_context_create();
         stream_context_set_option($ctx, 'ssl', 'local_cert', $this->PEMfile);
        if($this->PEMpassphrase!=""){
          stream_context_set_option($ctx, 'ssl', 'passphrase', $this->PEMpassphrase);
        }

        $fp = stream_socket_client( $this->ApplePushNotificationServer, $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

        if (!$fp) { return false; }

        $aps_struct['aps'] = array(
            'alert' => $message,
            'badge' => $this->aps_badge,
            'sound' => $this->aps_sound
        );

        if(!empty($notifyType))
        {
              $aps_struct["dataType"] = $notifyType;
        }
        $payload = json_encode($aps_struct);

        // Build the binary notification
        $msg = chr(0) . pack('n', 32) . pack('H*', $device_id) . pack('n', strlen($payload)) . $payload;
        // Send it to the server
        $result = fwrite($fp, $msg, strlen($msg));

        // Close the connection to the server
        fclose($fp);

        if (!$result)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

使用方式

  1. $apns = new ApplePNs( pem 檔案 )
  2. (option) 設定 badge , sound , passphrase … 等
  3. $apns->pushNotification( device token , message , [option] ntfyType );
  4. pushNotification 回傳 true or false

Android GCM 發送代碼

/*
Community Cloud System Class

  @filename : android.pn.class.php
  @author   : kerash
  @date     : 2013.06.26

Android Push Notification Service code
[Push notification through GCM in php]
*/
Class AndroidPNs
{
  /*
    Set the api key for using push service.
    Note that if you send by "cUrl" , you should ask a "Browser Key"!
    $apiKey = "";
  */
  var $GOOGLE_API_KEY = "";

  // Google Cloud Messaging Service path for push notification 
  var $GOOGLE_CLOUD_MESSAGING = "https://android.googleapis.com/gcm/send";

  // content type for your data format
  var $contentType = "application/json";

  function __Construct ( $apiKey )
  {
        $this->GOOGLE_API_KEY = $apiKey;
  }

  /* the main function to send message */
  function pushNotification($devices, $msg, $ntfyType = "")
  {
      $device_id  = $devices;
      $message    = $msg;
      $notifyType = $ntfyType;

      /* 
         there are example data.
         if un note this section , you can use some fake data for testign 
         $device_id  = array("50");
         $message    = "test";
         $notifyType = "packages";
      */
      if(!is_array($device_id)) { $device_id = array($device_id); }

      /* if data is null , then return false */
      if( count($device_id) <= 0 or trim($message) == "") { return false; }
       $post_fields = array(
            "registration_ids"=>$device_id,
            "data" => array("dataType"=>$notifyType,"message"=>$message)
       );

      /* initial the curl object */
      $curl = curl_init();
      curl_setopt($curl , CURLOPT_URL , $this->GOOGLE_CLOUD_MESSAGING);
      curl_setopt($curl , CURLOPT_POST , true );
      curl_setopt($curl , CURLOPT_RETURNTRANSFER , true );
      curl_setopt($curl , CURLOPT_SSL_VERIFYPEER , false );
      curl_setopt($curl , CURLOPT_HTTPHEADER  , 
            array( "Content-Type: ".$this->contentType ,
                "Authorization: key=".$this->GOOGLE_API_KEY)
        );
      curl_setopt($curl , CURLOPT_POSTFIELDS , json_encode( $post_fields) );
      $pushResult = curl_exec( $curl );
      if($pushResult)
      {
        $pushResultArray = json_decode($pushResult,true);

        /* check if notify send success */
        if($pushResultArray["success"]==0)
        {
            return false;
        }
        else
        {
            return true;
        }

      }
      else
      {
        return false;
      }

  }
}

使用方式:

  1. $gcm = new AndroidPNs( Google_API_Key );
  2. $gcm->pushNotification( register_id , message , [option] datatype );
  3. pushNotification 回傳 true or false

基本上使用只要 include 代碼後依照 function 呼叫即可。至於 pushNotification 的第三個參數是我個人使用時額外加上的,如果不需要其實以可以自行去除。

若語法有疑問或錯誤的部份也請不吝提供意見,我會立即修正,謝謝。

 

 

轉載自:http://blog.kerash.tw/2013/06/%E4%BB%A5-php-%E5%AF%A6%E5%81%9A-apple-apns-%E5%8F%8A-android-gcm-%E7%9A%84-push-notification-%E5%91%BC%E5%8F%AB/

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 駱韋仲 的頭像
    駱韋仲

    尼古丁中毒

    駱韋仲 發表在 痞客邦 留言(0) 人氣()