Field "to" must be a JSON string [Firebase] - php

I'm trying to send notification using a cron job. I migrated from GCM to FCM. In my server side, I changed https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send and also updated on how to request the data changing registration_ids to to. Checking the json passed it is a valid json but I'm having an error Field "to" must be a JSON string. Is there anyway to solve this?
Here is my code
function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $apiKey
);
$message = array(
'to' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($message)
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}

Try explicitly converting $registrationIDs to string.
$message = array(
'to' => (string)$registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
Edited Answer
The 'to' parameter requires a string - which is the recipient of the message.
The $registrationIDs could be passed a separate parameter (as string array) to 'registration_ids'
Edit your code to something like this:
$recipient = "YOUR_MESSAGE_RECIPIENT";
$message = array(
'to' => $recipient,
'registration_ids' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
Where $recipient is
a registration token, notification key, or topic.
Refer this:
Firebase Cloud Messaging HTTP Protocol

Try making to as a string:
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
...
},
}

// if you are using an array like
$fcm_ids = array();
$fcm_ids[] = "id_1";
$fcm_ids[] = "id_2";
$fcm_ids[] = "id_3";
//.
//.
//.
$fcm_ids[] = "id_n";
// note: limit is 1000 to send notifications to multiple ids at once.
// in your messsage send notification function use ids like this
$json_data = [
"to" => implode($fcm_ids),
"notification" => [
"title" => $title,
"body" => $body,
],
"data" => [
"str_1" => "something",
"str_2" => "something",
.
.
.
"str_n" => "something"
]
];

I had a similar problem. It turns out when I retrieved the Registration Token from my Firebase database (using this Firebase PHP Client), it was returned with double quotes at the beginning and at the end of the token. So I had to remove the first and last characters from the token before I could use it. The code below solved my problem
substr($registrationToken, 1, -1)

Related

How to add attachment to mailgun API using PHP

I have been using the mailgun API to send emails in my PHP application, When I add the attachment parameter as per the documentation, I got an error:Invalid resource type: array in /var/www/html/vendor/guzzlehttp/psr7/src/functions.php
Can someone assist?
$mgClient = new Mailgun('xxx');
$domain = "xxx";
$parameters = array(
'from' => 'xxx',
'to' => $to,
'subject' => $subject,
'text' => $text,
'attachment' = [
[
'filePath' => $attachment,
'filename' => $file_name,
]
];
);
$result = #$mgClient->sendMessage("$domain", $parameters);
I found a solution by adding the attachment array as a third parameter of the sendMessage()
$mgClient->sendMessage("$domain", $parameters, ['attachment' => ['filePath' => $file_path]]);

Empty Payload. JSON content expected (guzzle, php, azur active directory and outlook)

I am a student in programming and I have difficulties with my projects, little documentation meets my expectations and I would need help.
in this project I have to send from my application the token, the json flow on outlook to schedule a meeting
about Project : the principle is on a page to create a meeting which will then be linked to the outlook calendar this document helped me a lot https://learn.microsoft.com/fr-fr/graph/api/calendar-post-events?view=graph-rest-1.0&tabs=http https://youtu.be/orVsKsRs2Us
(data is on another page)
the whole function
public function Postcalendrier($ID,$data) {
$token=$_SESSION['token'];
$ID=$_SESSION["ID"];
$calendarGroup="/calendarGroups/{myID}/";
$calendar="calendars/{myID}/events";
$urlcalendar="https://graph.microsoft.com/v1.0/users/".$ID;
$url=$urlcalendar.$calendarGroup.$calendar;
$headers = [
'Authorization' => 'Bearer '.$token->access_token,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
$json = json_encode([$data])
$reponse = $this->guzzle->request('POST', $url,['headers' =>
$headers,'json' => $json],['debug' => true]);
return $response->getStatusCode();
}
$data = array(
"subject" => $Subject,
"body" => array(
"contentType" => "HTML",
"content" => $Content
),
"start" => array(
"dateTime" => $StartDateTime."T".$StartHourTime.":00",
"timeZone" => "$localDatetime"
),
"end" => array(
"dateTime" => $StartDateTime."T".$EndHourTime.":00",
"timeZone" => "$localDatetime"
),
"location" => array(
"displayName" => $Location
),
"attendees"=> [array(
"emailAddress"=> array(
"address"=> $addressmail,
"name"=>$prenom
),
"type"=> "required"
)]
);
I get this error message
Empty Payload. JSON content expected
so I tried with a different JSON but
I got this message instead and I don't really understand it
code UnableToDeserializePostBody message were unable to deserialize
this is my new json
$json = [
'json' => json_encode([$data])
];
thank you for your attention

AWS SES on PHP error: Unable to determine service/operation name to be authorized

I am trying to send email using AWS SES using the following PHP script:
<?php
require_once("phar://aws.phar");
use Aws\Ses\SesClient;
//Open client
$client = SesClient::factory(array(
"key" => "key",
"secret" => "secret",
"region" => "region"
));
$subject = "subject";
$messageText = "text message";
$messageHtml = "<h1>formatted message</h1>";
//Send email
try{
$response = $client->sendEmail(
array(
'Source' => 'verified_email#domain.com',
'Destination' => array(
'ToAddresses' => array('an_address#domain.com')
),
'Message' => array(
'Subject' => array('Data' => $subject),
'Body' => array('Text' => array('Data' => $messageText)),
'Html' => array('Data' => $messageHtml)
)
)
);
}catch(Exception $e){
//An error happened and the email did not get sent
echo($e->getMessage());
}
?>
Whenever I run this, it goes to the catch clause and prints to the screen the message:
Unable to determine service/operation name to be authorized
This doesn't really give me any information on what's wrong and there's no documentation on the API page about this. Any ideas?

Linkedin Invitation API Internal server error

Yo!
I'm trying to use the linkedin invitation api to allow users to conncect on linkedin from my application using email-addresses. I am able to find people, access the api and so on. I can't get the invites to work though. I am using php (Laravel).
I based myself on the example from the linkedin documentation ( Linkedin Invite API ). I send my data in a post using JSON (that contains the same info as their example).
I ask permission to use w_messages, the post works and my variables contain the correct information. I get a Internal Server error as a result.
$data = array(
"recipients" => array(
"values" => array(
"person" => array(
"_path" => "/people/email=".$email,
"first-name" => $firstname,
"last-name" => $lastname
)
)
),
"subject" => "Bla",
"body"=> "BlaBLa",
"item-content" => array(
"invitation-request" => array(
"connect-type" => "friend"
)
)
);
$dataString = json_encode($data);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n".
"Connection: close\r\n" .
"Content-length: " . strlen($dataString) . "\r\n",
'content' => $dataString
)
);
$params = array('oauth2_access_token' => Session::get('access_token'),
'format' => 'json'
);
$url = "https://api.linkedin.com/v1/people/~/mailbox".'?' . http_build_query($params);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
Log::info($result);
return Response::json(array("invite" => "sent"));
I assume I'm doing something wrong but don't really know where to look.
Looks like you doing this manually, have you tried using a tried & tested third party library like simple-linkedinphp - A PHP-based wrapper for the LinkedIn API.
https://code.google.com/p/simple-linkedinphp/wiki/Reference
Usage:
// Connect
$API_CONFIG = array(
'appKey' => '<your application key here>',
'appSecret' => '<your application secret here>',
'callbackUrl' => NULL
);
$linkedin = new LinkedIn($API_CONFIG);
// Send Invite
$linkedin->invite($method, $recipient, $subject, $body, $type = 'friend');
Doc: https://code.google.com/p/simple-linkedinphp/wiki/Reference

Retrieving JSON response using HTTPful library for Laravel

I am currently building a e-mail client (inbound and outbound sending) using Mandrill as the e-mail sending / inbound service and Laravel 3.x.
In order to send messages, I am using the HTTPful bundle with the Mandrill using the following code in my mail/compose POST method.
$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array(
'key' => '{removedAPIkey}',
'message' => array (
'to' => array( array( "email" => $_to ) ),
'from_name' => Auth::user()->name,
'from_email' => Auth::user()->email,
'subject' => $_subject,
'html' => $_body
),
'async' => true
);
$request = Httpful::post($url)->sendsJson()->body($data)->send();
Link to better formatted code above: http://paste.laravel.com/m79
Now as far as I can tell from the API log, the request is correctly made (with the expected JSON) and a response of the following format is sent back:
[
{
"email": "test#test.com",
"status": "queued",
"_id": "longmessageID"
}
]
However, what I am trying to do is access the response from the request (specifically the _id attribute), which is in JSON. Now as far as I'm aware, the HTTPful class should do this automatically (using json_decode()). However, accessing:
$request->_id;
is not working and I'm not entirely sure how to get this data out (it is required so I can record this for soft-bounce, hard-bounce and rejection messages for postmaster-like functionality)
Any assistance would be appreciated.
Edit
Using the following code, results in the mail being sent but an error returned:
$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array(
'key' => '{removedAPIkey}',
'message' => array (
'to' => array( array( "email" => $_to ) ),
'from_name' => Auth::user()->name,
'from_email' => Auth::user()->email,
'subject' => $_subject,
'html' => $_body
),
'async' => true
);
$request = Httpful::post($url)->sendsJson()->body($data)->send();
if ( $request[0]->status == "queued" ) {
$success = true;
}
Results in an exception being thrown: Cannot use object of type Httpful\Response as array
I must say, a huge thanks to Aiias for his assistance. I managed to fix this myself (I must have spent hours looking at this). For anyone who wants to know, the HTTPful bundle has a body array, where the response is kept. Therefore, the code below works:
$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array(
'key' => '{removedAPIkey}',
'message' => array (
'to' => array( array( "email" => $_to ) ),
'from_name' => Auth::user()->name,
'from_email' => Auth::user()->email,
'subject' => $_subject,
'html' => $_body
),
'async' => true
);
$request = Httpful::post($url)->sendsJson()->body($data)->send();
if ( $request->body[0]->status == "queued" ) {
$success = true;
}
Again, huge thanks to Aiias for clearing some major confusion up for me!

Categories