在cURL命令中获取Firebase Cloud Messaging中的未授权错误401

时间:2017-03-06 08:15:34

标签: php curl firebase firebase-cloud-messaging

我将发送Firebase云消息传递,而我遇到的问题是我收到了未经授权的错误401.

我从Firebase网站获得了安全密​​钥,然后进行了设置。设备令牌已经在数据库中,我从数据库读取没有问题。 到目前为止,这是我的代码:

<?php

function send_notification($tokens, $message)
{
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array('registration_ids' => $tokens, 'data' => $message);
    $headers = array('Authorization: key=' . "My Firebase key", 'Content-Type: application/json');
    echo "work well before init curl";
    $ch = curl_init();
    echo "init well";
    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, $fields);
    echo "init finishe well";
    $result = curl_exec($ch);
    echo "Execute to get result";
    if ($result === false) {
        die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);
    echo "function finished well";
    return $result;
}

$conn = mysqli_connect("localhost", "root", "mysql_password", "FCM") or die("Error connecting");

$sql = " Select Token From users";
$result = mysqli_query($conn, $sql);
$tokens = array();
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $tokens[] = $row["Token"];
    }
}
mysqli_close($conn);
$message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
$message_status = send_notification($tokens, $message);
echo $message_status;
?>

2 个答案:

答案 0 :(得分:6)

使用FCM时,您必须使用Firebase Console Cloud Messaging 标签中的服务器密钥作为Authorization的值你的要求。

答案 1 :(得分:0)

使用https://developers.google.com/instance-id/reference/server上的文档,我想使用https://iid.googleapis.com/iid/info/IID_TOKEN来获取有关应用程序实例的信息。

在我的应用代码中,我使用它来获取IDD_TOKEN

// Get token using example from https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/java/MainActivity.java.
// [START retrieve_current_token]
FirebaseInstanceId.getInstance().getInstanceId()
    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
        @Override
        public void onComplete(@NonNull Task<InstanceIdResult> task) {
            if (!task.isSuccessful()) {
                Log.w(TAG, "getInstanceId failed", task.getException());
                return;
            }
            // Get new Instance ID token
            String token = task.getResult().getToken();
            System.out.println("task.getResult().getToken() = "+token);
            // Log and toast
            String msg = getString(R.string.msg_token_fmt, token);
            Log.d(TAG, msg);
            Toast.makeText(FirstActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });
// [END retrieve_current_token]

然后,在Android Studio日志中,我找到了令牌(我正在更改令牌的值,因为我不想在此处发布真实的令牌):

I/System.out: task.getResult().getToken() = bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH

这意味着IDD_TOKENbepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH。因此,在我的PHP代码中,我使用了以下代码:

$curlUrl = "https://iid.googleapis.com/iid/info/bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH?details=true";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:key=[My server key]'));
//getting response from server
$response = curl_exec($ch);
print_r($response);

在哪里找到[My server key]?您可以在https://console.firebase.google.com/上找到它。转到Cloud Messaging标签,然后在Project credentials部分中,找到Server key

enter image description here

结果是这样的:

{“ applicationVersion”:“ 50”,“ connectDate”:“ 2019-05-09”,“ attestStatus”:“ NOT_ROOTED”,“ application”:“ [我的软件包名称]”,“范围”:“ * “,” authorizedEntity“:” [我的Firebase发件人ID]“,” rel“:{” topics“:{”多伦多“:{” addDate“:” 2019-05-09“}}},” appSigner“:” [My appSigner]“,” platform“:” ANDROID“}

是正确的。我可以说这些值与我连接的设备的IID_TOKEN相对应,我可以识别出一切正确。我可以确认我已将设备订阅了该主题,并且一切正常!我能够使用https://iid.googleapis.com/iid/info/IID_TOKEN来获取与我使用Firebase连接的Android设备相对应的应用程序实例的信息。