FCM - Implementation away from curl_init() in GAE

2019-09-16 16:12发布

As I could notice Google not supporting Curl implementation, I must move away from Curl implementation as I have explained in the post - [FCM could not be sent on GAE due to PHP error - call to undefined function curl_init()

I am trying for URL fetch as an example given at Google cloud platform documentation - [https://cloud.google.com/appengine/docs/standard/php/issue-requests][1]

Still, I am unable to break the barrier to work with FCM due to poor knowledge in PHP.

Below, is what I have attempted -

<?php

// Establishing FCM connection here to send a token received over to another device.
function send_fcm_notification_url_fetch    ($tokens,$message) {

    $url = "https://fcm.googleapis.com/fcm/send";
    $fields = array('registration_ids' => '<device_token_id>', 
    'data' => 'Hi');
    $queryParam = http_build_query($fields);


    $headers = array('Authorization:key = <firebase_server_key>',
                     'Content-Type: application/json');


    $context = array('http' => array( 'method' => 'POST', 'header' => $headers, 'content' => $queryParam ) );

$context = stream_context_create($context);
$result = file_get_contents($url,false,$context);
echo $result;
return $result;
}

?>

But despite of above, I am getting below error -

Warning: file_get_contents(https://fcm.googleapis.com/fcm/send): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in D:\wamp64\www\androidtrials\send_fcm_notification_url_fetch.php on line ##.

I am not sure what is going wrong. Been through multiple search, but nothing yielded me to meet my requirement. Has anybody done FCM messaging using PHP, but not using curl ? Thanks for your attention, looking for help.

1条回答
做个烂人
2楼-- · 2019-09-16 16:41

Below code worked. The way I was composing JSON request to FCM was incorrect. Below is implementation of URL fetch (non-curl) for FCM. At present tested at client WAMP configuration.

<?php

// Establishing FCM connection here to send a token received over to another device.
function send_fcm_notification_url_fetch    ($tokens,$message) {

    $url = "https://fcm.googleapis.com/fcm/send";
    $fields = array('registration_ids' => $tokens, 'data' => $message);

    $headers = "Authorization:key = <firebase_server_key>\r\n".
                     "Content-Type: application/json\r\n".
                     "Accept: application/json\r\n";

    $postData = json_encode($fields);

    $context = array('http' => array( 'method' => 'POST', 'header' => $headers, 'content' => $postData ) );

$context = stream_context_create($context);
$result = file_get_contents($url,false,$context);

return $result;
}

?>

To be tested with Google App Engine soon. Suspect no reason, why it shouldnt work there ...

查看更多
登录 后发表回答