【问题标题】:GCM with PHP (Google Cloud Messaging)GCM 与 PHP(谷歌云消息)
【发布时间】:2012-06-29 20:39:57
【问题描述】:

更新: GCM 已弃用,请使用 FCM

如何将新的Google Cloud Messaging 集成到 PHP 后端?

【问题讨论】:

  • 我编写了一个小型 OOP 库,其中包含 GCM 服务器的实现。希望它会对某人有所帮助:) 在 GitHub 上查看 - github.com/CodeMonkeysRu/GCMMessage
  • @HelmiB:我在网站上试过你的代码,它执行没有任何错误,但 $result 是空的。消息也不会传递。请帮我。我真的很需要它。
  • 我的 GCMMessage 分支支持指数备份,这是使用 Google 的 API 所必需的。它使用 redis 服务器对消息进行排队,并支持新的端点以及 iOS:github.com/stevetauber/php-gcm-queue
  • 它非常简单,您只需要一个应用服务器、GCM 服务器和一个托管该服务的应用程序。参考这个例子。这里 localhost 充当应用服务器feelzdroid.com/2016/02/…

标签: php android firebase-cloud-messaging google-cloud-messaging


【解决方案1】:

此代码将通过 PHP CURL 向多个注册 ID 发送 GCM 消息。

// Payload data you want to send to Android device(s)
// (it will be accessible via intent extras)    
$data = array('message' => 'Hello World!');

// The recipient registration tokens for this notification
// https://developer.android.com/google/gcm/    
$ids = array('abc', 'def');

// Send push notification via Google Cloud Messaging
sendPushNotification($data, $ids);

function sendPushNotification($data, $ids) {
    // Insert real GCM API key from the Google APIs Console
    // https://code.google.com/apis/console/        
    $apiKey = 'abc';

    // Set POST request body
    $post = array(
                    'registration_ids'  => $ids,
                    'data'              => $data,
                 );

    // Set CURL request headers 
    $headers = array( 
                        'Authorization: key=' . $apiKey,
                        'Content-Type: application/json'
                    );

    // Initialize curl handle       
    $ch = curl_init();

    // Set URL to GCM push endpoint     
    curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');

    // Set request method to POST       
    curl_setopt($ch, CURLOPT_POST, true);

    // Set custom request headers       
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Get the response back as string instead of printing it       
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Set JSON post data
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));

    // Actually send the request    
    $result = curl_exec($ch);

    // Handle errors
    if (curl_errno($ch)) {
        echo 'GCM error: ' . curl_error($ch);
    }

    // Close curl handle
    curl_close($ch);

    // Debug GCM response       
    echo $result;
}

【讨论】:

  • 它几乎在这里工作,但我没有在电话上收到任何消息。我想调试它,但我不知道为什么我的 $result 总是为空...
  • 我在哪里可以获得注册 ID?
  • 感谢您的回答!如果这对任何人都有用,我将它整合到一个 PHP 对象框架中:github.com/kaiesh/GCM_PHP
  • @Sit 禁用 SSL 证书检查总是一个坏主意。如果您的服务器无法验证 SSL 证书,请使用此技术告诉 cURL 期望什么证书:unitstep.net/blog/2009/05/05/… 或强制 cURL 使用 cURL 网站上的最新 cacert.pem,使用如下内容:gist.github.com/gboudreau/5206966
  • 这有帮助:curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
【解决方案2】:
<?php
    // Replace with the real server API key from Google APIs
    $apiKey = "your api key";

    // Replace with the real client registration IDs
    $registrationIDs = array( "reg id1","reg id2");

    // Message to be sent
    $message = "hi Shailesh";

    // Set POST variables
    $url = 'https://android.googleapis.com/gcm/send';

    $fields = array(
        'registration_ids' => $registrationIDs,
        'data' => array( "message" => $message ),
    );
    $headers = array(
        'Authorization: key=' . $apiKey,
        'Content-Type: application/json'
    );

    // Open connection
    $ch = curl_init();

    // Set the URL, number of POST vars, POST data
    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt( $ch, CURLOPT_POST, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // curl_setopt($ch, CURLOPT_POST, true);
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    // Execute post
    $result = curl_exec($ch);

    // Close connection
    curl_close($ch);
    echo $result;
    //print_r($result);
    //var_dump($result);
?>

【讨论】:

  • 嗨 Shailesh Giri,使用 Browser key 可以正常工作,但如果是 Server key,它会显示 Unauthorized Error 401。你能帮帮我吗?
  • 服务器的预期结果是什么?我没有得到任何回应!设备也没有显示任何消息。
  • curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 是一个很大的禁忌。如果由于某种原因,运行此 PHP 代码的服务器无法验证 Google 服务器使用的 SSL 证书,您可以告诉 cURL 使用什么来验证。示例:unitstep.net/blog/2009/05/05/…
【解决方案3】:

这很容易做到。 Elad Nava 放在这里的页面上的cURL 代码有效。 Elad 收到了commented about the error

描述在处理该收件人的邮件时发生的错误的字符串。可能的值与上表中记录的相同,加上“不可用”(意味着 GCM 服务器很忙,无法处理该特定收件人的消息,因此可以重试)。

我已经设置了一个似乎正在运行的服务(ish),到目前为止,我所得到的只是谷歌无法获得的回报。这很可能很快就会改变。

要回答这个问题,请使用 PHP,确保 Zend Framework 在您的包含路径中,然后使用以下代码:

<?php
    ini_set('display_errors',1);
    include"Zend/Loader/Autoloader.php";
    Zend_Loader_Autoloader::getInstance();

    $url = 'https://android.googleapis.com/gcm/send';
    $serverApiKey = "YOUR API KEY AS GENERATED IN API CONSOLE";
    $reg = "DEVICE REGISTRATION ID";

    $data = array(
            'registration_ids' => array($reg),
            'data' => array('yourname' => 'Joe Bloggs')
    );

    print(json_encode($data));

    $client = new Zend_Http_Client($url);
    $client->setMethod('POST');
    $client->setHeaders(array("Content-Type" => "application/json", "Authorization" => "key=" . $serverApiKey));
    $client->setRawData(json_encode($data));
    $request = $client->request('POST');
    $body = $request->getBody();
    $headers = $request->getHeaders();
    print("<xmp>");
    var_dump($body);
    var_dump($headers);

我们有它。在 Zend Framework PHP 中使用 Google 的新 GCM 的工作(很快就会工作)示例。

【讨论】:

  • 大规模更新!显然使用带有 IP 限制的 API 密钥集无法正常工作。我刚刚在服务器端交换了我的 API 密钥,以使用 API 控制台中名为“浏览器应用程序密钥(带引用者)”的密钥,你猜怎么着!它通过了。这是我返回的内容: {"multicast_id":8466657113827057558,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1341067903035991%921c249a66d6cf16"}] }
  • 现在开启和关闭。我每天收到大约 3500 条消息,到目前为止没有问题需要报告。
  • +1 Elad .. 您必须使用 BROWSER 应用程序 API 密钥来访问 SERVER 应用程序!谢谢谷歌,真的很有帮助 FAIL :( (浪费了很多小时)
【解决方案4】:

找了很久终于搞清楚我到底需要什么,使用PHP作为服务器端脚本语言连接到GCM,下面的教程将让我们清楚地知道如何设置我们需要的一切开始使用 GCM

Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

【讨论】:

    【解决方案5】:

    实际上,我现在在 Zend_Mobile 树的一个分支中工作:https://github.com/mwillbanks/Zend_Mobile/tree/feature/gcm

    这将与 ZF 1.12 一起发布,但是,它应该为您提供一些很好的示例来说明如何做到这一点。

    这是一个关于它如何工作的快速演示......

    <?php
    require_once 'Zend/Mobile/Push/Gcm.php';
    require_once 'Zend/Mobile/Push/Message/Gcm.php';
    
    $message = new Zend_Mobile_Push_Message_Gcm();
    $message->setId(time());
    $message->addToken('ABCDEF0123456789');
    $message->setData(array(
        'foo' => 'bar',
        'bar' => 'foo',
    ));
    
    $gcm = new Zend_Mobile_Push_Gcm();
    $gcm->setApiKey('MYAPIKEY');
    
    $response = false;
    
    try {
        $response = $gcm->send($message);
    } catch (Zend_Mobile_Push_Exception $e) {
        // all other exceptions only require action to be sent or implementation of exponential backoff.
        die($e->getMessage());
    }
    
    // handle all errors and registration_id's
    foreach ($response->getResults() as $k => $v) {
        if ($v['registration_id']) {
            printf("%s has a new registration id of: %s\r\n", $k, $v['registration_id']);
        }
        if ($v['error']) {
            printf("%s had an error of: %s\r\n", $k, $v['error']);
        }
        if ($v['message_id']) {
            printf("%s was successfully sent the message, message id is: %s", $k, $v['message_id']);
        }
    }
    

    【讨论】:

    • 好的!这很好。但是我怎样才能获得用户的令牌。我猜您正在使用令牌作为registrationID。在我的 Android 应用中,服务器 URL 是什么?
    • 是的tokens是注册ID;这特别是因为该库试图保持某种抽象,因为它还实现了 APNS 和 MPNS。服务器 URL 是您最终制作的任何内容;这只是为发送提供了粘合剂,您需要编写一个区域,您将在其中发布注册 ID 并将其保存在某处。从那里你可以利用上面的代码实际向应用发送推送通知。
    【解决方案6】:

    很多教程已经过时,甚至当前的代码也没有说明设备注册 ID 何时更新或设备取消注册。如果这些项目未选中,最终将导致阻止接收消息的问题。 http://forum.loungekatt.com/viewtopic.php?t=63#p181

    【讨论】:

      【解决方案7】:

      你也可以试试这段代码,source:

      <?php
          define("GOOGLE_API_KEY", "AIzaSyCJiVkatisdQ44rEM353PFGbia29mBVscA");
          define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send");
      
          function send_gcm_notify($reg_id, $message) {
              $fields = array(
                  'registration_ids'  => array( $reg_id ),
                  'data'              => array( "message" => $message ),
              );
      
              $headers = array(
                  'Authorization: key=' . GOOGLE_API_KEY,
                  'Content-Type: application/json'
              );
      
              $ch = curl_init();
              curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
              curl_setopt($ch, CURLOPT_POST, true);
              curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
              curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
      
              $result = curl_exec($ch);
              if ($result === FALSE) {
                  die('Problem occurred: ' . curl_error($ch));
              }
      
              curl_close($ch);
              echo $result;
          }
      
          $reg_id = "APA91bHuSGES.....nn5pWrrSz0dV63pg";
          $msg = "Google Cloud Messaging working well";
      
          send_gcm_notify($reg_id, $msg);
      

      【讨论】:

      • 您的代码显示错误“出现问题:无法连接到 74.125.142.95:权限被拒绝”。有什么问题?
      【解决方案8】:
      <?php
      
      function sendMessageToPhone($deviceToken, $collapseKey, $messageText, $yourKey) {    
          echo "DeviceToken:".$deviceToken."Key:".$collapseKey."Message:".$messageText
                  ."API Key:".$yourKey."Response"."<br/>";
      
          $headers = array('Authorization:key=' . $yourKey);    
          $data = array(    
              'registration_id' => $deviceToken,          
              'collapse_key' => $collapseKey,
              'data.message' => $messageText);  
          $ch = curl_init();    
      
          curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");    
          if ($headers)    
              curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    
          curl_setopt($ch, CURLOPT_POST, true);    
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
      
          $response = curl_exec($ch);    
          var_dump($response);
          $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);    
          if (curl_errno($ch)) {
              return false;
          }    
          if ($httpCode != 200) {
              return false;
          }    
          curl_close($ch);    
          return $response;    
      }  
      
      $yourKey = "YOURKEY";
      $deviceToken = "REGISTERED_ID";
      $collapseKey = "COLLAPSE_KEY";
      $messageText = "MESSAGE";
      echo sendMessageToPhone($deviceToken, $collapseKey, $messageText, $yourKey);
      ?>
      

      在上面的脚本中只需更改:

      “YOURKEY”到 API 密钥到 API 控制台的服务器密钥。
      “REGISTERED_ID”与您设备的注册 ID
      “COLLAPSE_KEY”与您需要的密钥
      “MESSAGE”带有您要发送的消息

      如果您在这方面遇到任何问题,请告诉我,我可以使用相同的脚本成功获得通知。

      【讨论】:

        【解决方案9】:

        您可以使用 packagist 上提供的这个 PHP 库:

        https://github.com/CoreProc/gcm-php

        安装后你可以这样做:

        $gcmClient = new GcmClient('your-gcm-api-key-here');
        
        $message = new Message($gcmClient);
        
        $message->addRegistrationId('xxxxxxxxxx');
        $message->setData([
            'title' => 'Sample Push Notification',
            'message' => 'This is a test push notification using Google Cloud Messaging'
        ]);
        
        try {
        
            $response = $message->send();
        
            // The send() method returns a Response object
            print_r($response);
        
        } catch (Exception $exception) {
        
            echo 'uh-oh: ' . $exception->getMessage();
        
        }
        

        【讨论】:

          【解决方案10】:

          这是我从 CodeMonkeysRU 派生的一个库。

          我分叉的原因是因为 Google 需要指数退避。我使用 redis 服务器对消息进行排队,并在设定的时间后重新发送。

          我还更新了它以支持 iOS。

          https://github.com/stevetauber/php-gcm-queue

          【讨论】:

          • 您好,能否请您指出针对 iOS 所做的更改,与原始库相比,我真的没有看到任何特别之处。
          • @2ndGAB 我分叉的主要原因是指数退避。至于 iOS 的变化,你可以在这里阅读:developers.google.com/cloud-messaging/…
          【解决方案11】:

          这是@Elad Nava发布的上述PHP代码的android代码

          MainActivity.java(启动器活动)

          public class MainActivity extends AppCompatActivity {
              String PROJECT_NUMBER="your project number/sender id";
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
          
          
          
                  GCMClientManager pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
                  pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
                      @Override
                      public void onSuccess(String registrationId, boolean isNewRegistration) {
          
                          Log.d("Registration id", registrationId);
                          //send this registrationId to your server
                      }
          
                      @Override
                      public void onFailure(String ex) {
                          super.onFailure(ex);
                      }
                  });
              }
          }
          

          GCMClientManager.java

          public class GCMClientManager {
              // Constants
              public static final String TAG = "GCMClientManager";
              public static final String EXTRA_MESSAGE = "message";
              public static final String PROPERTY_REG_ID = "your sender id";
              private static final String PROPERTY_APP_VERSION = "appVersion";
              private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
              // Member variables
              private GoogleCloudMessaging gcm;
              private String regid;
              private String projectNumber;
              private Activity activity;
              public GCMClientManager(Activity activity, String projectNumber) {
                  this.activity = activity;
                  this.projectNumber = projectNumber;
                  this.gcm = GoogleCloudMessaging.getInstance(activity);
              }
              /**
               * @return Application's version code from the {@code PackageManager}.
               */
              private static int getAppVersion(Context context) {
                  try {
                      PackageInfo packageInfo = context.getPackageManager()
                              .getPackageInfo(context.getPackageName(), 0);
                      return packageInfo.versionCode;
                  } catch (NameNotFoundException e) {
                      // should never happen
                      throw new RuntimeException("Could not get package name: " + e);
                  }
              }
              // Register if needed or fetch from local store
              public void registerIfNeeded(final RegistrationCompletedHandler handler) {
                  if (checkPlayServices()) {
                      regid = getRegistrationId(getContext());
                      if (regid.isEmpty()) {
                          registerInBackground(handler);
                      } else { // got id from cache
                          Log.i(TAG, regid);
                          handler.onSuccess(regid, false);
                      }
                  } else { // no play services
                      Log.i(TAG, "No valid Google Play Services APK found.");
                  }
              }
              /**
               * Registers the application with GCM servers asynchronously.
               * <p>
               * Stores the registration ID and app versionCode in the application's
               * shared preferences.
               */
              private void registerInBackground(final RegistrationCompletedHandler handler) {
                  new AsyncTask<Void, Void, String>() {
                      @Override
                      protected String doInBackground(Void... params) {
                          try {
                              if (gcm == null) {
                                  gcm = GoogleCloudMessaging.getInstance(getContext());
                              }
                              InstanceID instanceID = InstanceID.getInstance(getContext());
                              regid = instanceID.getToken(projectNumber, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                              Log.i(TAG, regid);
                              // Persist the regID - no need to register again.
                              storeRegistrationId(getContext(), regid);
                          } catch (IOException ex) {
                              // If there is an error, don't just keep trying to register.
                              // Require the user to click a button again, or perform
                              // exponential back-off.
                              handler.onFailure("Error :" + ex.getMessage());
                          }
                          return regid;
                      }
                      @Override
                      protected void onPostExecute(String regId) {
                          if (regId != null) {
                              handler.onSuccess(regId, true);
                          }
                      }
                  }.execute(null, null, null);
              }
              /**
               * Gets the current registration ID for application on GCM service.
               * <p>
               * If result is empty, the app needs to register.
               *
               * @return registration ID, or empty string if there is no existing
               *     registration ID.
               */
              private String getRegistrationId(Context context) {
                  final SharedPreferences prefs = getGCMPreferences(context);
                  String registrationId = prefs.getString(PROPERTY_REG_ID, "");
                  if (registrationId.isEmpty()) {
                      Log.i(TAG, "Registration not found.");
                      return "";
                  }
                  // Check if app was updated; if so, it must clear the registration ID
                  // since the existing regID is not guaranteed to work with the new
                  // app version.
                  int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
                  int currentVersion = getAppVersion(context);
                  if (registeredVersion != currentVersion) {
                      Log.i(TAG, "App version changed.");
                      return "";
                  }
                  return registrationId;
              }
              /**
               * Stores the registration ID and app versionCode in the application's
               * {@code SharedPreferences}.
               *
               * @param context application's context.
               * @param regId registration ID
               */
              private void storeRegistrationId(Context context, String regId) {
                  final SharedPreferences prefs = getGCMPreferences(context);
                  int appVersion = getAppVersion(context);
                  Log.i(TAG, "Saving regId on app version " + appVersion);
                  SharedPreferences.Editor editor = prefs.edit();
                  editor.putString(PROPERTY_REG_ID, regId);
                  editor.putInt(PROPERTY_APP_VERSION, appVersion);
                  editor.commit();
              }
              private SharedPreferences getGCMPreferences(Context context) {
                  // This sample app persists the registration ID in shared preferences, but
                  // how you store the regID in your app is up to you.
                  return getContext().getSharedPreferences(context.getPackageName(),
                          Context.MODE_PRIVATE);
              }
              /**
               * Check the device to make sure it has the Google Play Services APK. If
               * it doesn't, display a dialog that allows users to download the APK from
               * the Google Play Store or enable it in the device's system settings.
               */
              private boolean checkPlayServices() {
                  int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
                  if (resultCode != ConnectionResult.SUCCESS) {
                      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                          GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                                  PLAY_SERVICES_RESOLUTION_REQUEST).show();
                      } else {
                          Log.i(TAG, "This device is not supported.");
                      }
                      return false;
                  }
                  return true;
              }
              private Context getContext() {
                  return activity;
              }
              private Activity getActivity() {
                  return activity;
              }
              public static abstract class RegistrationCompletedHandler {
                  public abstract void onSuccess(String registrationId, boolean isNewRegistration);
                  public void onFailure(String ex) {
                      // If there is an error, don't just keep trying to register.
                      // Require the user to click a button again, or perform
                      // exponential back-off.
                      Log.e(TAG, ex);
                  }
              }
          }
          

          PushNotificationService.java(通知生成器)

          public class PushNotificationService extends GcmListenerService{
          
              public static int MESSAGE_NOTIFICATION_ID = 100;
          
              @Override
              public void onMessageReceived(String from, Bundle data) {
                  String message = data.getString("message");
                  sendNotification("Hi-"+message, "My App sent you a message");
              }
          
              private void sendNotification(String title, String body) {
                  Context context = getBaseContext();
                  NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                          .setSmallIcon(R.mipmap.ic_launcher).setContentTitle(title)
                          .setContentText(body);
                  NotificationManager mNotificationManager = (NotificationManager) context
                          .getSystemService(Context.NOTIFICATION_SERVICE);
                  mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
              }
          }
          

          AndroidManifest.xml

          <?xml version="1.0" encoding="utf-8"?>
          

          <uses-permission android:name="android.permission.INTERNET" />
          <uses-permission android:name="android.permission.WAKE_LOCK" />
          <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
          <permission android:name="com.example.gcm.permission.C2D_MESSAGE"
              android:protectionLevel="signature" />
          <uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
          <application
              android:allowBackup="true"
              android:icon="@mipmap/ic_launcher"
              android:label="@string/app_name"
              android:supportsRtl="true"
              android:theme="@style/AppTheme" >
              <activity android:name=".MainActivity" >
                  <intent-filter>
                      <action android:name="android.intent.action.MAIN" />
          
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>
          
              <service
                  android:name=".PushNotificationService"
                  android:exported="false">
                  <intent-filter>
                      <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                  </intent-filter>
              </service>
          
              <receiver
                  android:name="com.google.android.gms.gcm.GcmReceiver"
                  android:exported="true"
                  android:permission="com.google.android.c2dm.permission.SEND">
                  <intent-filter>
                      <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                      <category android:name="package.gcmdemo" />
                  </intent-filter>
              </receiver>
          </application>
          

          【讨论】:

            【解决方案12】:

            使用这个

             function pnstest(){
            
                            $data = array('post_id'=>'12345','title'=>'A Blog post', 'message' =>'test msg');
            
                            $url = 'https://fcm.googleapis.com/fcm/send';
            
                            $server_key = 'AIzaSyDVpDdS7EyNgMUpoZV6sI2p-cG';
            
                            $target ='fO3JGJw4CXI:APA91bFKvHv8wzZ05w2JQSor6D8lFvEGE_jHZGDAKzFmKWc73LABnumtRosWuJx--I4SoyF1XQ4w01P77MKft33grAPhA8g-wuBPZTgmgttaC9U4S3uCHjdDn5c3YHAnBF3H';
            
                            $fields = array();
                            $fields['data'] = $data;
                            if(is_array($target)){
                                $fields['registration_ids'] = $target;
                            }else{
                                $fields['to'] = $target;
                            }
            
                            //header with content_type api key
                            $headers = array(
                                'Content-Type:application/json',
                              'Authorization:key='.$server_key
                            );
            
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
                            $result = curl_exec($ch);
                            if ($result === FALSE) {
                                die('FCM Send Error: ' . curl_error($ch));
                            }
                            curl_close($ch);
                            return $result;
            
            }
            

            【讨论】:

              【解决方案13】:

              我知道这是一个迟到的答案,但它可能对那些想要使用当前 FCM 格式(GCM 已被弃用)开发类似应用程序的人有用。
              以下 PHP 代码已用于发送主题播客。所有使用上述频道/topis 注册的应用都会收到此推送通知。

              <?php
              
              try{
              $fcm_token = 'your fcm token';
              $service_url = 'https://fcm.googleapis.com/fcm/send';
              $channel = '/topics/'.$adminChannel;
              echo $channel.'</br>';
                    $curl_post_body = array('to' => $channel,
                      'content_available' => true,
                      'notification' => array('click_action' => 'action_open',
                                          'body'=> $contentTitle,
                                          'title'=>'Title '.$contentCurrentCat. ' Updates' ,
                                          'message'=>'44'),
                      'data'=> array('click_action' => 'action_open',
                                          'body'=>'test',
                                          'title'=>'test',
                                          'message'=>$catTitleId));
              
                      $headers = array(
                      'Content-Type:application/json',
                      'Authorization:key='.$fcm_token);
              
                  $ch = curl_init();
                  curl_setopt($ch, CURLOPT_URL, $service_url);
                  curl_setopt($ch, CURLOPT_POST, true);
                  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curl_post_body));
              
                  $result = curl_exec($ch);
                  if ($result === FALSE) {
                      die('FCM Send Error: ' . curl_error($ch));
                      echo 'failure';
                  }else{
              
                  echo 'success' .$result;
                  }
                  curl_close($ch);
                  return $result;
              
              }
              catch(Exception $e){
              
                  echo 'Message: ' .$e->getMessage();
              }
              ?>
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-12-05
                • 1970-01-01
                • 2014-08-15
                • 1970-01-01
                相关资源
                最近更新 更多