POST JSON Object with multiple headers in php - php

Request header
Content-Type: application/json
Authorization: Bearer [access token]
Accept: application/json
if send unicode string with message, please set Content-Type charset to UTF-8
Following is a sample request of send service.
URL-https://example.com/requests
Method - POST
Body
{
"outboundSMSMessageRequest": {
"address": [
"tel:+94771234567"
],
"senderAddress": "tel:12345678",
"outboundSMSTextMessage": {
"message": "Test Message"
},
"clientCorrelator": "123456",
"receiptRequest": {
"notifyURL": "http://128.199.174.220:1080/sms/report",
"callbackData": "some-data-useful-to-the-requester"
},
"senderName": "ACME Inc."
}
}
How to post and get responce

ajax
headers: {
'X-HTTP-Method-Override': 'POST',
'Content-Type': 'application/json'
},
or vanilla js
How to create javascript POST request to server with Headers and Data

Related

How can I send push notification from PHP website to iOS and Android?

How I can send push notification from PHP website to iOS devices and Android devices?
Is there any tutorial for that?
You can use several premade services for push notifications like Firebase Messaging, One Signal, etc. For Firebase cloud Messaging Integration with PHP, please visit this Link. After setting up, Just Send this POST request with the user token
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...PbJ_uNasm
{
"message": {
"token" : <token of destination app>,
"notification": {
"title": "FCM Message",
"body": "This is a message from FCM"
},
"webpush": {
"headers": {
"Urgency": "high"
},
"notification": {
"body": "This is a message from FCM to web",
"requireInteraction": "true",
"badge": "/badge-icon.png"
}
}
}
}
or Send a Push Notification using topic
https://fcm.googleapis.com//v1/projects/<YOUR-PROJECT-ID>/messages:send
Content-Type: application/json
Authorization: bearer <YOUR-ACCESS-TOKEN>
{
"message": {
"topic": "matchday"
"notification": {
"title": "Background Message Title",
"body": "Background message body"
},
"webpush": {
"fcm_options": {
"link": "https://dummypage.com"
}
}
}
}
For One Signal, Visit this Link for more information. Also, alternatively, you can use web sockets, if you don't want premade services.

Firebase Notofication Request Various To

There is a way to send in a firebase notidication request, various to
header:
Content-Type: application/json
Authorization: key=
Body:
{ "data":
{
"title": "Firebase notification",
"detail": "I am firebase notification. you can customise me. enjoy"
},
"to" : "c_ejgKg_0rY:APA91bEtp77PP99UuDvza1gKOKAmfqVg3ZHflWYQUGPQJFCvWy3Ortswv45MjtT8LQaRoebLqSXPTeaO21hm7QVnG694GgVmALbK5LIDAsyohKlTFlQSlwcdYQmPS5GnLGjLwfA3b34z",
"sound":"default"
}
here an example of the request, please help me, thank you
Use registration_ids instead...
Firebase Cloud Messaging HTTP protocol | Firebase
header:
Content-Type: application/json
Authorization: key =
Body:
{
"data":
{
"title": "Firebase notification",
"detail": "I am firebase notification. you can customise me. enjoy"
},
"registration_ids" : [
"c_ejgKg_0rY:APA91bEtp77PP99UuDvza1gKOKAmfqVg3ZHflWYQUGPQJFCvWy3Ortswv45MjtT8LQaRoebLqSXPTeaO21hm7QVnG694GgVmALbK5LIDAsyohKlTFlQSlwcdYQmPS5GnLGjLwfA3b34z"
],
"sound":"default"
}

How to fix "unexpected end of input" error when fetching json string output from PHP script [duplicate]

I tried a ReactJS fetch call to a REST-API and want to handle the response. The call works, i get a response, which i can see in Chrome Dev Tools:
function getAllCourses() {
fetch('http://localhost:8080/course', {
method: 'POST',
mode: 'no-cors',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
objectClass: 'course',
crud: '2'
})
}).then(function (response) {
console.log(response);
return response.json();
}).catch(function (err) {
console.log(err)
});
}
When i try to handle the response, i got a "SyntaxError: Unexpected end of input" at
return response.json();
The console.log looks like this:
My Response JSON looks like this, it is valid, i checked it with jsonlint:
[
{
"0x1": {
"users": [],
"lectures": [],
"owner": "0x2",
"title": "WWI 14 SEA",
"description": null,
"objectClass": "course",
"id": "course_00001"
},
"0x2": {
"username": "system",
"lectures": [],
"course": null,
"solutions": [],
"exercises": [],
"roles": [
"0x3",
"0x4",
"0x5"
],
"objectClass": "user",
"id": "user_00001"
},
"0x3": {
"roleName": "ROLE_ADMIN",
"objectClass": "role",
"id": "role_00001"
},
"0x4": {
"roleName": "ROLE_STUDENT",
"objectClass": "role",
"id": "role_00002"
},
"0x5": {
"roleName": "ROLE_DOCENT",
"objectClass": "role",
"id": "role_00003"
}
}
]
You need to remove the mode: 'no-cors' setting from your request. Setting no-cors mode is exactly the cause of the problem you’re having.
A no-cors request makes the response type opaque. The log snippet in the question shows that. Opaque means your frontend JavaScript code can’t see the response body or headers.
https://developer.mozilla.org/en-US/docs/Web/API/Request/mode explains:
no-cors — JavaScript may not access any properties of the resulting Response
So the effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”
People sometimes try setting no-cors mode when a response doesn’t include the Access-Control-Allow-Origin response header or else because the request is one that triggers a CORS preflight, and so your browser does an OPTIONS preflight.
But using no-cors mode isn’t a solution to those problems. The solution is either to:
configure the server to which you’re making the request such that it sends the Access-Control-Allow-Origin response header, and such that it handles OPTIONS requests
or set up a CORS proxy using code from https://github.com/Rob--W/cors-anywhere/ or such; see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
In your then you should check if the response is OK before returning response.json:
.then(function (response) {
if (!response.ok) {
return Promise.reject('some reason');
}
return response.json();
})
If you want to have the error message in your rejected promise, you can do something like:
.then(function (response) {
if (!response.ok) {
return response.text().then(result => Promise.reject(new Error(result)));
}
return response.json();
})
I know this answer might be super late and might have been resolved but i just had the same issue today and I just needed to add a ',' at the end of the headers hash and i stopped getting the error
export function addContacts(formData) {
return(dispatch) => {
dispatch({type: 'POSTING_CONTACTS'});
console.log(formData)
return fetch(uri, {
method: 'POST',
body: JSON.stringify({contact: {name: formData.name, phone_number: formData.phoneNumber}}),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then(response => {
return response.json()
}).then(responseJSON => {
console.log(responseJSON)
return dispatch({type: 'ADD_CONTACT', payload: responseJSON});
})
}
}
You can avoid the problem with CORS policy by adding in the header of php or another server endpoint the row:
<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');
// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
// Use $jsonObj
print_r($jsonObj->message);
...
// End php
?>
Model of working fetch code with POST request is:
const data = {
optPost: 'myAPI',
message: 'We make a research of fetch'
};
const endpoint = 'http://example.com/php/phpGetPost.php';
fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
console.info('fetch()', response);
return response;
});
Simply copy the following code and paste it on your web.config file under <system.webServer> tag.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>

Microsoft Graph - POST request error 20132

I can't seem to get a POST request to create assignments using Microsoft Graph.
Both in the Graph Explorer and in PHP I get the same error: "message": "The content of the request is invalid. Common causes are an invalid Content-Type header or no content in the body.",
Endpoint: https://graph.microsoft.com/beta/education/classes/class-id/assignments
Request Headers: content-type: application/json
Body:
{
"dueDateTime": "2014-02-01T00:00:00Z",
"displayName": "Midterm 1",
"instructions": {
"contentType": "Text",
"content": "Read chapters 1 through 3"
},
"grading": {
"#odata.type": "#microsoft.education.assignments.api.educationAssignmentPointsGradeType",
"maxPoints": 100
},
"assignTo": {
"#odata.type": "#microsoft.education.assignments.api.educationAssignmentClassRecipient"
},
"status":"draft",
"allowStudentsToAddResourcesToSubmission": true
}
Any help would be truly appreciated!
Please see image of Graph Explorer below.
Figured it out. Removing the "contentType": "Text" attribute from instructions worked.

POST request through Guzzle php

hi i wanted to make a post request to dropbox.i found there is this guzzle which can be easily send http req using php. here the http code given by dropbox
`POST /2/files/list_folder
Host: https://api.dropboxapi.com
User-Agent: api-explorer-client
Authorization: Bearer <access-token>
Content-Type: application/json
{
"path": "",
"recursive": false,
"include_media_info": true,
"include_deleted": false,
"include_has_explicit_shared_members": false
}`
This is my php code i coded for above request;
$response=$client->request('POST','https://api.dropboxapi.com',
[
'headers'=>[
'Authorization'=>'Bearer '.$API,
'User-Agen'=>'api-explorer-client',
'Content-Type'=>'application/json'
],
'form_params'=>[
'path'=>'',
'recursive'=>'false',
'include_media_info'=> 'true',
'include_deleted'=> 'false',
'include_has_explicit_shared_members'=> 'false'
]
]);
$headers = $response->getHeaders();
$body =$response->getBody();
$print=json_decode($body,true);
//Output headers and body for debugging purposes
var_dump($headers);echo"<br><br>";
var_dump($print);?>
this should give something similar to following ,but i get a small array
{"entries": [
{
".tag": "folder",
"name": "Photos",
"path_lower": "/photos",
"path_display": "/Photos",
"id": "id:bwGPfg_v6ZUAAAAAAAAAOA"
},`
what i missed here?
PS:im new to php related stuff :)
You are sending JSON, not an HTML form. So use 'json' instead of 'form_params'.

Categories