CloudObjects / Directory / Firebase Integration / FCM Send API 1.0
Sign in

FCM Send API 1.0

a phpmae:ControllerClass, agws:WebAPI & phpmae:Class in Firebase Integration

The FCM Send API is used to send messages through Firebase Cloud Messaging. This API is typically mounted by and called from an application's underlying service.

Public PHP Methods
  • connect(Application $app)

    No documentation available.

Source Code
<?php

use Silex\Application, Silex\Api\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use GuzzleHttp\Client;
use CloudObjects\SDK\NodeReader;

/**
 * Implementation for coid://firebase.cloudobjects.io/FCMSendAPI/1.0
 */
class FCMSendAPI implements ControllerProviderInterface {

  public function connect(Application $app) {
    $controllers = $app['controllers_factory'];

    $controllers->post('/send', function(Request $r) use ($app) {
      $reader = new NodeReader([ 'prefixes' => [ 'fb' => 'coid://firebase.cloudobjects.io/' ] ]);
      $fcmServerKey = $reader->getFirstValueString($app['accessor.namespace.object'], 'fb:FCMServerKey');
      if (!isset($fcmServerKey)) {
        $app['context']->setLogCode('NoFCMServerKey');
        $app->abort(500, "No FCM Server Key found.");
      }

      // Initialize Client
      $client = new Client([
        'base_uri' => 'https://fcm.googleapis.com/fcm/',
        'headers' => [ 'Authorization' => 'key='.$fcmServerKey ]
      ]);

      // Check all account connections to detect whether they are FCMEnabled
      foreach ($app['context']->getAllAccountConnections() as $ac) {
        if ($reader->getFirstValueString($ac, 'fb:FCMEnabled') == 'true'
            && $reader->getFirstValueString($ac, 'fb:FCMRegistrationId') != null) {
          
          $to = $reader->getFirstValueString($ac, 'fb:FCMRegistrationId');
          try {
            if ($r->getContent()[0] == "{") {
              // JSON request
              $data = json_decode($r->getContent(), true);
              $data['to'] = $to;

              $fcmApiResponse = json_decode($client->post('send', [
                  'json' => $data
                ])->getBody(), true);

              if ($fcmApiResponse['success'] == 1) {
                $app['context']->setLogCode('Sent');
                return $app->json(array('sent' => true, 'id' => $fcmApiResponse['results'][0]['message_id']));
              } else {
                $app['context']->setLogCode('Error');
                return $app->json(array('sent' => false, 'reason' => $fcmApiResponse));
              }
              
            } else {
              // Form Post / plain text request
              $data = array_merge([ 'registration_id' => $to ], $r->request->all());

              $fcmApiResponse = $client->post('send', [
                  'form_params' => $data
                ])->getBody()->getContents();

              parse_str($fcmApiResponse, $fcmResponseFields);

              if (isset($fcmResponseFields['id'])) {
                $app['context']->setLogCode('Sent');
                return $app->json(array('sent' => true, 'id' => $fcmResponseFields['id']));
              } else {
                $app['context']->setLogCode('Error');
                return $app->json(array('sent' => false, 'reason' => $fcmApiResponse));
              }
          }

          } catch (\Exception $e) {
            return $app->json(array('sent' => false, 'reason' => $e->getMessage()));
          }
        }
      }
     
      $app['context']->setLogCode('N/A');
      return $app->json(array('sent' => false, 'reason' => 'No Registration ID.'));
    });

    return $controllers;
  }
}
Meta
URI / COID
coid://firebase.cloudobjects.io/FCMSendAPI/1.0 content_copy
Revision
6-45871399824ad96224b9b66ab71026fd content_copy
Last updated
2017-02-14 11:38 (UTC)
Usage permission
co:Public