skip to Main Content

I want to subscribe to a firebase fcm topic with PHP and I change my old code to this one:

// Path to your service account key file (JSON)
        $serviceAccountFile = PAD_PLUGIN_DIR . 'positive-notch-181410-2bc8875c71a4.json';
        
        // Your FCM Topic name
        $topicName = get_the_category($post_id)[0]->slug;
        
        // Device token to subscribe
        $deviceToken = 'fuEMCQmCT_m0H3fdoXqD9m:APA91bGITP85Q6y3Zg3_Ls9bjbPKMBylwHads9hQbkzDJCeeOtlHfJZqxX4hIAJMeOoKYCfm59ki95tOpNViORr6cy4ATuCaDAubCkj1pdXzQsrI1lMeesZYRt-B_vCJO6R55NLfZRoM';
        
        // Initialize Google Client
        $client = new Google_Client();
        $client->setAuthConfig($serviceAccountFile);
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
        
        // Get an OAuth2 access token
        $accessToken = $client->fetchAccessTokenWithAssertion();
        $accessTokenString = $accessToken['access_token'];
        
        $subscriptionUrl = 'https://iid.googleapis.com/iid/v1:batchAdd';
    
        $data = [
            'to' => '/topics/blabla',
            'registration_tokens' => [$deviceToken]
        ];
    
        $ch = curl_init($subscriptionUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $accessTokenString,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200) {
            echo "Successfully subscribed to topic.";
        } else {
            echo "Failed to subscribe: " . $response;
        }
        
        exit;

I followed all the instructions step by step but I cannot subscribe to fcm topic, but I get 401 error every time. Authentication using server key is deprecated. Please use an OAuth2 token instead. .

I ensured also if the $accessTokenString is valid and not expired, and it is.

Of course I have a Google Cloud project with FCM enabled and a service account JSON key file.

Does somebody know which is the problem?

Thanks

2

Answers


  1. Based on this article try adding this to the header

    access_token_auth: true
    
    Login or Signup to reply.
  2. so what was your solution, I have same problem here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search