简体   繁体   中英

Getting Unauthorized Error 401 in Firebase Cloud Messaging in cURL command

I'm going to send Firebase Cloud Messaging and the problem that I'm facing is I get an Unauthorized Error 401.

I got the security key from my Firebase website then set it. The device token is already in database and I read from database with no problem. This is my code so far:

<?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;
?>

使用FCM时,必须使用Firebase控制台Cloud Messaging选项卡中显示的服务器密钥作为请求中的Authorization值。

Using the documentation at https://developers.google.com/instance-id/reference/server , I wanted to use https://iid.googleapis.com/iid/info/IID_TOKEN to get information about app instances.

In the code of my app, I used this to get the 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]

Then in the Android Studio logs, I found the token (I am changing the value of the token because I do not want to post the real one here):

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

This means that the IDD_TOKEN was bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH . So in my PHP code I used this:

$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);

Where is the [My server key] found? You can find it at https://console.firebase.google.com/ . Go to the Cloud Messaging tab, and in the Project credentials section, you will find the Server key :

在此输入图像描述

The result was this:

{"applicationVersion":"50","connectDate":"2019-05-09","attestStatus":"NOT_ROOTED","application":"[My package name]","scope":"*","authorizedEntity":"[My Firebase Sender ID]","rel":{"topics":{"Toronto":{"addDate":"2019-05-09"}}},"appSigner":"[My appSigner]","platform":"ANDROID"}

That is correct. I can tell that those values correspond to my IID_TOKEN for the device that I connected, I can recognize that and everything is correct. I can confirm that I subscribed my device to that topic and everything works correctly! I was able to use https://iid.googleapis.com/iid/info/IID_TOKEN to get information about my app instances corresponding to an Android device that I connected using Firebase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM