I am trying to send notification using php to Android Application, and which is working fine without sound. I am receiving the notification both foreground and background as expected.
Here is the PHP code,
<?php
$token = $_GET['token'];
$action = $_GET['action'];
$msgTitle = $_GET['msgTitle'];
$msgDescription = $_GET['msgDescription'];
$notificationTitle = $_GET['notificationTitle'];
require './google-api-php-client-2.2.2/vendor/autoload.php';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setAuthConfig('./testPrjoectAPP-firebase-adminsdk-9hn21-22c1b3f426.json');
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$httpClient = $client->authorize();
$project = "testPrjoectAPP";
$message = [
"message" => [
"notification" => [
"body" => "Message FCM",
"title" => $notificationTitle
],
"token" => $token,
"data" => [
"action" => $action,
"msgTitle" => $msgTitle,
"msgDescription" => $msgDescription
]
]
];
$response = $httpClient->post("https://fcm.googleapis.com/v1/projects/{$project}/messages:send", ['json' => $message]);
echo$response->getReasonPhrase(); // OK
?>
But when I add sound parameter to notification payload and execute php I am getting Bad Request error from php.
.
$message = [
"message" => [
"notification" => [
"body" => "Message FCM",
"title" => $notificationTitle,
"sound" => "default"
],
// Send with token is not working
"token" => $token,
"data" => [
"action" => $action,
"msgTitle" => $msgTitle,
"msgDescription" => $msgDescription
]
]
];
Edit
Here is the error message I got while printing with
data: "{\n \"error\": {\n \"code\": 400,\n \"message\": \"Invalid JSON payload received. Unknown name \\\"sound\\\" at 'message.notification': Cannot find field.\",\n \"status\": \"INVALID_ARGUMENT\",\n \"details\": [\n {\n \"#type\": \"type.googleapis.com/google.rpc.BadRequest\",\n \"fieldViolations\": [\n {\n \"field\": \"message.notification\",\n \"description\": \"Invalid JSON payload received. Unknown name \\\"sound\\\" at 'message.notification': Cannot find field.\"\n }\n ]\n }\n ]\n }\n}\n"
As per my comment, You have to use your JSON like following way.
Solution:
The appearance of message in your JSON indicates you are using the HTTP v1 API. The documentation you linked is for the legacy API.
The HTTP v1 API JSON to send a notification with sound for Android and iOS devices should be:
{
"message":{
"token":"your-token-value",
"notification":{
"title":"Test",
"body":"Test message from server"
},
"android":{
"notification":{
"sound":"default"
}
},
"apns":{
"payload":{
"sound":"default"
}
}
}
}
Reference Link is: Unable to add sound to notification payload
Thank you.
Try this:
{
"message":{
"token":"your-token-value",
"notification":{
"title":"Test",
"body":"Test message from server"
},
"android":{
"notification":{
"sound":"default"
}
},
"apns":{
"payload":{
"sound":"default"
}
}
}
}
Related
I am trying to set up wav -> mp3 conversion through AWS, I've followed documentation closely but I can't find anything about the problem I am facing so hoping someone can help here. Here is my code to start a conversion on AWS:
$job_settings = '{
"TimecodeConfig": {
"Source": "ZEROBASED"
},
"OutputGroups": [
{
"Name": "File Group",
"Outputs": [
{
"ContainerSettings": {
"Container": "RAW"
},
"AudioDescriptions": [
{
"AudioTypeControl": "FOLLOW_INPUT",
"AudioSourceName": "Audio Selector 1",
"CodecSettings": {
"Codec": "MP3",
"Mp3Settings": {
"Bitrate": 192000,
"Channels": 2,
"RateControlMode": "CBR",
"SampleRate": 48000
}
},
"LanguageCodeControl": "FOLLOW_INPUT"
}
]
}
],
"OutputGroupSettings": {
"Type": "FILE_GROUP_SETTINGS",
"FileGroupSettings": {
"Destination": "{DESTINATION}"
}
}
}
],
"AdAvailOffset": 0,
"Inputs": [
{
"AudioSelectors": {
"Audio Selector 1": {
"Tracks": [
1
],
"Offset": 0,
"DefaultSelection": "DEFAULT",
"SelectorType": "TRACK",
"ProgramSelection": 1
}
},
"FilterEnable": "AUTO",
"PsiControl": "USE_PSI",
"FilterStrength": 0,
"DeblockFilter": "DISABLED",
"DenoiseFilter": "DISABLED",
"InputScanType": "AUTO",
"TimecodeSource": "ZEROBASED",
"FileInput": "{INPUT}"
}
]
}';
//Job starts here
$job_settings = json_decode($job_settings, true);
$convert_client = new MediaConvertClient(array(
'version' => '2017-08-29',
'region' => $this->login_details->region,
'credentials' => $this->credentials
));
try {
$res = $convert_client->describeEndpoints([]);
} catch(AwsException $e) {
//echo $e->getMessage();
return null;
}
//print_r($res);
$single_endpoint = $res['Endpoints'][0]['Url'];
$convert_client = new MediaConvertClient(array(
'version' => '2017-08-29',
'region' => $this->login_details->region,
'credentials' => $this->credentials,
'endpoint' => $single_endpoint
));
$res = $client->createJob(array(
"Role" => "arn:aws:iam::{$this->login_details->account_number}:role/MediaConvert_Default_Role",
"Settings" => $job_settings,
"Queue" => "arn:aws:mediaconvert:{$this->login_details->region}:{$this->login_details->account_number}:queues/Default"
));
I grabbed the JSON by creating a conversion job on AWS Console and copying the JSON of the job, the destination and input tags are replaced in the json before decoding to assoc array however I am getting an error of the following:
Error executing "CreateJob" on "aws_url"; AWS HTTP error: Client error: POST aws_url resulted in a 400 Bad Request response: { "errorType": "BadRequestException", "httpStatus" : 400, "requestId" : "-----------", (truncated...) BadRequestException (client): /outputGroups/0/outputs/0/audioDescriptions/0/codecSettings: Should match exactly one schema defined in "oneOf" | /outputGroups/0/outputs/0/audioDescriptions/0/codecSettings: Should have at least 2 properties | /outputGroups/0/outputs/0/audioDescriptions/0/codecSettings/codec: Should be equal to one of the allowed values in ["PASSTHROUGH","OPUS","VORBIS"]
This is using aws-3.93.3 PHP SDK. Any idea why this happens? Of course the job runs perfectly fine if ran through console.
Actually I just found what I suspected was the case; this version of the library does not yet support MP3 ingestion as outlined here:
https://github.com/aws/aws-sdk-php/blob/master/CHANGELOG.md
Updating to the newest version solved this issue.
I'm trying to create subscriptions with microsoft graph in php, however I am unable to see what is going wrong at this point.
The code is breaking at the following:
protected $http_subscribe = "https://graph.microsoft.com/v1.0/subscriptions";
public function getSubscriptions()
{
if(empty($this->token)) {
dd('no token supplied'); //some debugging
}
$date = $this->endTimeDate->format('Y-m-d'); //This is Carbon date
$time = $this->endTimeDate->format('H:i:s.u');
$response = $this->client->request('POST', $this->http_subscribe, [
'headers' => [
'Authorization' => 'Bearer ' . $this->token,
'Content-Type' => "application/json"
], 'form_params' => [
"changeType" => "created,updated",
"notificationUrl" => "https://website.test/notify",
"resource" => "me/mailFolders('Inbox')/messages",
"expirationDateTime" => $date.'T'.$time,
"clientState" => "secretClientValue"
]
]);
dd($response);
}
The full error I'm getting is:
"""
{\r\n
"error": {\r\n
"code": "BadRequest",\r\n
"message": "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.",\r\n
"innerError": {\r\n
"request-id": "063d9947-80fd-461d-a70e-q0bd8eee9d56",\r\n
"date": "2018-08-07T08:20:54"\r\n
}\r\n
}\r\n
}
"""
Now I get what the error says, my json would be invalid, however this array is in correct json format, I'm using Guzzle as my Client.
You should use json option. Try this:
$response = $this->client->request('POST', $this->http_subscribe, [
'headers' => [
'Authorization' => 'Bearer ' . $this->token,
],
'json' => [
"changeType" => "created,updated",
"notificationUrl" => "https://website.test/notify",
"resource" => "me/mailFolders('Inbox')/messages",
"expirationDateTime" => $date.'T'.$time,
"clientState" => "secretClientValue",
],
]);
I am sending a POST request to the following resource and getting a 400. I understand what the error means, but still am unsure why I'm getting it when a GET request to the same resource works.
/lists/{list_id}/members
Here is a exerpt of the code:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', // <-- Drop in a GET here and it works, other than it's not the behavior I need.
env('MAILCHIMP_API_URL') . 'lists/' . env('MAILCHIMP_LIST_KEY') . '/members',
[
'auth' => ['app', env('MAILCHIMP_API_KEY')],
'query' => [
'email_address' => 'donnie#test.com',
'email_type' => 'html',
'status' => 'subscribed',
]
]);
dd($response->getStatusCode());
Response
Client error: `POST https://XXXX.api.mailchimp.com/3.0/lists/XXXX/members?email_address=donnie%40test.com&email_type=html&status=subscribed`
resulted in a `400 Bad Request`
response: {
"type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title": "Invalid Resource",
"status": 400,
"detail": "The resource submitted could not be validated. For field-specific details, see the 'errors' array.",
"instance": "f32e7076-b970-4f5c-82c6-eec5875e83b4",
"errors": [{
"field": "",
"message": "Schema describes object, NULL found instead"
}]
}
You are sending a POST request with query parameters. You need to send JSON encoded body!
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', // <-- Drop in a GET here and it works, other than it's not the behavior I need.
env('MAILCHIMP_API_URL') . 'lists/' . env('MAILCHIMP_LIST_KEY') . '/members',
[
'auth' => ['app', env('MAILCHIMP_API_KEY')],
'json' => [
'email_address' => 'donnie#test.com',
'email_type' => 'html',
'status' => 'subscribed',
]
]);
dd($response->getStatusCode());
I want write data to my sheet:
$spreadsheetId = 'xxx';
$range = 'Test!A1:D5';
$values = [
'range' => "A1",
'majorDimension' => 'DIMENSION_UNSPECIFIED',
'values' => [
["Item", "Cost", "Stocked", "Ship Date"],
["Wheel", "$20.50", "4", "3/1/2016"],
["Door", "$15", "2", "3/15/2016"],
["Engine", "$100", "1", "30/20/2016"],
],
];
$body = new Google_Service_Sheets_ValueRange(array(
'values' => $values
));
$params = array(
'valueInputOption' => 'RAW'
);
$result = $service->spreadsheets_values->update($spreadsheetId, $range, $body, $params);
But in log i see:
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"range\" at 'data.values': Cannot find field.\nInvalid JSON payload received. Unknown name \"major_dimension\" at 'data.values': Cannot find field.",
"errors": [
{
"message": "Invalid JSON payload received. Unknown name \"range\" at 'data.values': Cannot find field.\nInvalid JSON payload received. Unknown name \"major_dimension\" at 'data.values': Cannot find field.",
"domain": "global",
"reason": "badRequest"
}
],
"status": "INVALID_ARGUMENT"
}
}
What am I doing wrong? I will be grateful for the example code that works for you :)
In the examples there is not enough information( https://developers.google.com/sheets/api/guides/values#writing_to_a_single_range)
You're almost there. Don't forget to include the sheet name
"range": "Sheet1!A1:D5"
Check the Basic Writing guide for more samples.
Try this:
$spreadsheetId = 'xxx';
$range = 'Test!A1:D5';
$values = [
["Item", "Cost", "Stocked", "Ship Date"],
["Wheel", "$20.50", "4", "3/1/2016"],
["Door", "$15", "2", "3/15/2016"],
["Engine", "$100", "1", "30/20/2016"],
];
$updateBody = new Google_Service_Sheets_ValueRange([
'range' => $range,
'majorDimension' => 'ROWS',
'values' => $values,
]);
$valueInputOption = 'USER_ENTERED'; // Or RAW
$params = [
'valueInputOption' => $valueInputOption
];
$result = $this->sheetsService->spreadsheets_values->update(
$spreadsheetID,
$updateRange,
$updateBody,
$params
);
Not the case here, but I have solved a similar issue by removing NULL values from the items inside of the values array.
Google's PHP library seems to have a hard time parsing these values and ends up generating an invalid JSON payload.
I'm trying to create a card with my webhook service. my website is in php but I don't know how to respond to api.ai in a way to display my result in card format on client's phone. I ask my question with more detail in here.
Considering, you know receiving and checking action from Api.ai request in php
For responding with the card, you can use this:
$request== file_get_contents("php://input");
$messages=[];
// Building Card
array_push($messages, array(
"type"=> "basic_card",
"platform"=> "google",
"title"=> "Card title",
"subtitle"=> "card subtitle",
"image"=>[
"url"=>'http://image-url',
"accessibility_text"=>'image-alt'
],
"formattedText"=> 'Text for card',
"buttons"=> [
[
"title"=> "Button title",
"openUrlAction"=> [
"url"=> "http://url redirect for button"
]
]
]
)
);
// Adding simple response (mandatory)
array_push($messages, array(
"type"=> "simple_response",
"platform"=> "google",
"textToSpeech"=> "Here is speech and additional msg for card"
)
);
$response=array(
"source" => $request["result"]["source"],
"speech" => "Speech for response",
"messages" => $messages,
"contextOut" => array()
);
json_encode($response);
Make sure you don't push more than one card and have 'simple response' with it.