我从新的谷歌通知服务Firebase Cloud Messaging开始。

多亏了这段代码https://github.com/firebase/quickstart-android/tree/master/messaging,我才能从我的Firebase用户控制台发送通知到我的Android设备。

有没有什么API或方法可以在不使用Firebase控制台的情况下发送通知?我的意思是,例如,一个PHP API或类似的东西,直接从我自己的服务器创建通知。


当前回答

下面是我使用CURL的项目中的工作代码。

<?PHP
//Avoid keys confusions!
//firebase Cloud Messaging have 3 different keys: 
//API_KEY, SERVER_KEY and PUSH_KEY ... here we need SERVER_KEY

// SERVER access key from Google firebase Console    
define( 'SERVER_ACCESS_KEY', 'YOUR-SERVER-ACCESS-KEY-GOES-HERE' );


 $registrationIds = array( $_GET['id'] );

  // prep the bundle
 $msg = array
 (
   'message'    => 'here is a message. message',
    'title'     => 'This is a title. title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
 );

 $fields = array
 (
    // use this to method if want to send to topics
    // 'to' => 'topics/all'
    'registration_ids'  => $registrationIds,
     'notification'         => $msg
 );

 $headers = array
 (
    'Authorization: key=' . SERVER_ACCESS_KEY,
    'Content-Type: application/json'
 );

 $ch = curl_init();
 curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
 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 );
 curl_close( $ch );

 echo $result;

其他回答

使用服务api。

URL: https://fcm.googleapis.com/fcm/send

方法类型:POST

标题:

Content-Type: application/json
Authorization: key=your api key

车身/有效载荷:

{
   "notification": {
      "title": "Your Title",
      "text": "Your Text",
      "click_action": "OPEN_ACTIVITY_1"
   },
   "data": {
      "<some_key>": "<some_value>"
   },
   "to": "<device_token>"
}

在你的应用程序中,你可以添加以下代码在你的活动中被调用:

<intent-filter>
    <action android:name="OPEN_ACTIVITY_1" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

也检查答案在Firebase onmessagerreceived未调用时,应用程序在后台

Go to cloud Messaging select:  Server key



function sendGCM($message, $deviceToken) {

    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array (
            'registration_ids' => array (
                $id
            ),
            'data' => array (
                "title" =>  "Notification title",
                "body" =>  $message,
            )
    );
    $fields = json_encode ( $fields );
    $headers = array (
        'Authorization: key=' . "YOUR_SERVER_KEY",
        'Content-Type: application/json'
    );
    $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_POSTFIELDS, $fields );
    $result = curl_exec ( $ch );
    echo $result;

    curl_close ($ch);
}

首先,你需要从android获得一个令牌,然后你可以调用这个php代码,你甚至可以在你的应用程序中为进一步的操作发送数据。

 <?php

// Call .php?Action=M&t=title&m=message&r=token
$action=$_GET["Action"];


switch ($action) {
    Case "M":
         $r=$_GET["r"];
        $t=$_GET["t"];
        $m=$_GET["m"];

        $j=json_decode(notify($r, $t, $m));

        $succ=0;
        $fail=0;

        $succ=$j->{'success'};
        $fail=$j->{'failure'};

        print "Success: " . $succ . "<br>";
        print "Fail   : " . $fail . "<br>";

        break;


default:
        print json_encode ("Error: Function not defined ->" . $action);
}

function notify ($r, $t, $m)
    {
    // API access key from Google API's Console
        if (!defined('API_ACCESS_KEY')) define( 'API_ACCESS_KEY', 'Insert here' );
        $tokenarray = array($r);
        // prep the bundle
        $msg = array
        (
            'title'     => $t,
            'message'     => $m,
           'MyKey1'       => 'MyData1',
            'MyKey2'       => 'MyData2', 

        );
        $fields = array
        (
            'registration_ids'     => $tokenarray,
            'data'            => $msg
        );

        $headers = array
        (
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        );

        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'fcm.googleapis.com/fcm/send' );
        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 );
        curl_close( $ch );
        return $result;
    }


?>

如果您正在使用PHP,我建议使用用于Firebase的PHP SDK: Firebase Admin SDK。为了一个简单的配置,您可以按照以下步骤:

从Firebase获取项目凭证json文件(初始化sdk),并将其包含在项目中。

在项目中安装SDK。我使用composer:

composer require kreait/firebase-php ^4.35

试试SDK文档中云消息会话的任何例子:

use Kreait\Firebase;
use Kreait\Firebase\Messaging\CloudMessage;

$messaging = (new Firebase\Factory())
->withServiceAccount('/path/to/firebase_credentials.json')
->createMessaging();

$message = CloudMessage::withTarget(/* see sections below */)
    ->withNotification(Notification::create('Title', 'Body'))
    ->withData(['key' => 'value']);

$messaging->send($message);

或者你可以使用Firebase的云功能,对我来说,这是实现推送通知的更简单的方法。 重火力点/ functions-samples