GCM with PHP (Google Cloud Messaging)

后端 未结 13 1456
轮回少年
轮回少年 2020-11-22 04:48

Update: GCM is deprecated, use FCM

How can I integrate the new Google Cloud Messaging in a PHP backend?

相关标签:
13条回答
  • 2020-11-22 05:14

    After searching for a long time finally I am able to figure out what I exactly needed, Connecting to the GCM using PHP as a server side scripting language, The following tutorial will give us a clear idea of how to setup everything we need to get started with GCM

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

    0 讨论(0)
  • 2020-11-22 05:18

    Here's a library I forked from CodeMonkeysRU.

    The reason I forked was because Google requires exponential backoff. I use a redis server to queue messages and resend after a set time.

    I've also updated it to support iOS.

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

    0 讨论(0)
  • 2020-11-22 05:19

    Here is android code for PHP code of above posted by @Elad Nava

    MainActivity.java (Launcher Activity)

    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 (Notification generator)

    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>
    

    0 讨论(0)
  • 2020-11-22 05:23
    <?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);
    ?>
    

    In above script just change :

    "YOURKEY" to API key to Server Key of API console.
    "REGISTERED_ID" with your device's registration ID
    "COLLAPSE_KEY" with key which you required
    "MESSAGE" with message which you want to send

    Let me know if you are getting any problem in this I am able to get notification successfully using the same script.

    0 讨论(0)
  • 2020-11-22 05:26

    I know this is a late Answer, but it may be useful for those who wants to develop similar apps with current FCM format (GCM has been deprecated).
    The following PHP code has been used to send topic-wise podcast. All the apps registered with the mentioned channel/topis would receive this Push Notification.

    <?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();
    }
    ?>
    
    0 讨论(0)
  • 2020-11-22 05:28

    use this

     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;
    
    }
    
    0 讨论(0)
提交回复
热议问题