I am using ParseAPI (https://parse.com/docs/rest/guide#objects-updating-objects) and I'm attempting to update an object with their rest api. I get a response back from parse saying the object was updated, however no change was made.
Can someone please guide me in the correct direction?
Thank you!!
<?php
$url = ' https://api.parse.com/1/classes/GameScore/Ed1nuqPvcm';
$appId = 'my app id';
$restKey = 'my rest key';
$headers = array(
"Content-Type: application/json",
"X-Parse-REST-API-Key: " . $restKey,
"X-Parse-Application-Id: " . $appId
);
$data = array('pass' => 'hi');
$jsonDataEncoded = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonDataEncoded));
$response = curl_exec($ch);
echo $response;
?>
Related
I'm getting error : Missing or incorrectly formatted payload
I'm generating device token from Apple DeviceCheck API in swift language with real device and also passing Transaction ID to this php api.
jwt token generating successfully with this code but further code not working with apple query bit api.
This is my server side code in php :
<?php
require_once "vendor/autoload.php";
use Zenstruck\JWT\Token;
use Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256;
use \Ramsey\Uuid\Uuid;
$deviceToken = (isset($_POST["deviceToken"]) ? $_POST["deviceToken"] : null);
$transId = (isset($_POST["transId"]) ? $_POST["transId"] : null);
function generateJWT($teamId, $keyId, $privateKeyFilePath) {
$payload = [
"iss" => $teamId,
"iat" => time()
];
$header = [
"kid" => $keyId
];
$token = new Token($payload, $header);
return (string)$token->sign(new ES256(), $privateKeyFilePath);
}
$teamId = "#####";// I'm passing My team id
$keyId = "#####"; // I'm passing my key id
$privateKeyFilePath = "AuthKey_4AU5LJV3.p8";
$jwt = generateJWT($teamId, $keyId, $privateKeyFilePath);
function postReq($url, $jwt, $bodyArray) {
$header = [
"Authorization: Bearer ". $jwt
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyArray); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$server_output = curl_exec($ch);
//$info = curl_getinfo($ch);
// print_r($info);
//echo 'http code: ' . $info['http_code'] . '<br />';
//echo curl_error($ch);
curl_close($ch);
return $server_output;
}
$body = [
"device_token" => $deviceToken,
"transaction_id" => $transId,
"timestamp" => ceil(microtime(true)*1000)
];
$myjsonis = postReq("https://api.development.devicecheck.apple.com/v1/query_two_bits", $jwt, $body);
echo $myjsonis;
?>
Where is problem in this code? Or any other solution in php code.
Is there anything that I'm missing.
I just checked the Docs. They don't want POST fields like a form, they want a JSON body instead. Here's a snippet of code that you should be able to tweak to do what you require:
$data = array("name" => "delboy1978uk", "age" => "41");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
Actually, looking again at your code, it could be as simple as running json_encode() on your array.
I'm trying to POST an image on Mastodon (specifically on Humblr) but I cannot get the media_id, the response is null, but I'm not sure where the problem is.
I can publish text, no problem, so the authentication part is fine, I only have the problem with the image, the only difference I can see in the documentation is that "Media file encoded using multipart/form-data".
Here's my code so far...
$headers = ['Authorization: Bearer '.$settings['access_token'] , 'Content-Type: multipart/form-data'];
$mime_type = mime_content_type($urlImage);
$cf = curl_file_create($urlImage,$mime_type,'file');
$media_data = array( "file" => $cf);
$ch_status = curl_init();
curl_setopt($ch_status, CURLOPT_URL, "https://humblr.social/api/v1/media");
curl_setopt($ch_status, CURLOPT_POST, 1);
curl_setopt($ch_status, CURLOPT_POSTFIELDS, $media_data);
curl_setopt($ch_status, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_status, CURLOPT_HTTPHEADER, $headers);
$media_status = json_decode(curl_exec($ch_status));
echo "Response: ".json_encode($media_status);
From this I want to extract the $media_status-> media_id
I don't really know much about 'multipart/form-data' to be honest.
Am I missing something?
This took some trial and error for me as well. Here's what worked for me (PHP 7.3):
$curl_file = curl_file_create('/path/to/file.jpg','image/jpg','file.jpg');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://instanceurl.com/api/v1/media');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer YOUR_TOKEN_HERE',
'Content-Type: multipart/form-data'
]);
$body = [
'file' => $curl_file
];
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$response = curl_exec($ch);
if (!$response) {
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
echo 'Response Body: ' . $response . PHP_EOL;
curl_close($ch);
I am currently trying to post a message on my Discord channel trying to use a cURL POST type. The issue that I am getting when I run my code is that it is giving me a 401 error saying I'm unauthorized. I am running my PHP code on a webserver using xampp localhost. I also went in and tried to authorize my application bot via URL link (https://discordapp.com/oauth2/authorize?client_id=MYAPPLICATIONID&scope=bot&permissions=8) and have successfully added the bot into my channel. Have a look at my code
$data = array("Authorization: Bot" => $clientSecret, 'content' => 'Test Message');
$data_string = json_encode($data);
$ch = curl_init('https://discordapp.com/api/v6/channels/'.$myChannel.'/messages');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$answer = curl_exec($ch);
echo $answer;
if (curl_error($ch)) {
echo curl_error($ch);
}
I get $clientSecret from the application page to reveal my client secret token and $myChannel is my discords channel/server id.
NOTE: I have modeled my code off another stackoverflow answer given here discord php curl login Fail . So I am unsure if I am using the correct syntax for the an application bot
Here is full code (Without cURL). Just replace the string WEBHOOK_HERE with your bot's webhook:
<?php
$message = $_POST['message'];
$data = ['content' => $message];
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents('WEBHOOK_HERE', false, $context);
?>
<form method="post">
Type your message here :<br><input type="text" name="message"><br>
<input type="submit" value="Submit">
</form>
I'm new here so I hope you enjoy the code!
Close! Your solution has an error.
<?php
$myChannel = "CHANNEL_ID";
$myToken = "TOKEN";
$msg = 'Test Message';
$data = array('content' => $msg);
$data_string = json_encode($data);
$ch = curl_init('https://discordapp.com/api/v6/channels/' . $myChannel . '/messages');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Bot ' . $myToken
)
);
$answer = curl_exec($ch);
echo $answer;
if (curl_error($ch)) {
echo curl_error($ch);
}
?>
I just tested this on my server and it worked. with Bot ' . $token it failed.
I actually had a tough time searching the web for this, without using webhooks. I wanted to post the message as a bot, not a webhook. The error was with your authorization, as it needs to be in the header... So I'm posting the correct solution here for future googlers.
<?php
$myChannel = "CHANNEL_ID";
$myToken = "TOKEN";
$msg = 'Test Message';
$data = array('content' => $msg);
$data_string = json_encode($data);
$ch = curl_init('https://discord.com/api/v6/channels/' . $myChannel . '/messages');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Bot ' . $myToken
)
);
$answer = curl_exec($ch);
echo $answer;
if (curl_error($ch)) {
echo curl_error($ch);
}
?>
This is what I wrote to get it and attempt to send a push notification:
<?php
//send FCM notification
$fcmToken = "My device token";
$fcmKey = "My Firebase Cloud Messaging Server Key";
//I tried curl like this but I barely understand it and it wouldn't work
//curl -X POST --header "Authorization: key=$fcmKey" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"$fcmToken\",\"notification\":{\"body\":\"Yellow\"},\"priority\":10}"
echo "starting curl <hr>";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: key=$fcmKey","Content-Type: application/json","to: $fcmToken","notification:{\"body\":\"Yellow\"}","priority: 10" )); //setting custom header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
echo "curlResult: " . $result;
curl_close($curl);
echo "<hr>curl end";
?>
The output I got was like this, why?:
starting curl <hr>curlResult: <HTML>
<HEAD>
<TITLE>Moved Temporarily</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Moved Temporarily</H1>
The document has moved here.
</BODY>
</HTML>
<hr>curl end
Thanks in advance for any help!
I'm not sure what exactly made the difference but I ended up following the answer on this post to get it to work:
Firebase Cloud Messaging, issues in receiving notification
For preservation this is what it said:
<?php
function send_notification ($tokens)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$priority="high";
$notification= array('title' => 'Some title','body' => 'hi' );
$fields = array(
'registration_ids' => $tokens,
'notification' => $notification
);
$headers = array(
'Authorization:key=xxxxxxxxxxxxx',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// echo json_encode($fields);
$result = curl_exec($ch);
echo curl_error($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$tokens = array('RECEIVER-TOKEN-1'
,'RECEIVER_TOKEN-2');
$message_status = send_notification($tokens);
echo $message_status;
I am trying to send TOAST (PUSH) notification to Windows Phone Application (8.1) from PHP application. Configuration for the notification is done right . Configuration is validated with (http://31daysofwindows8.com/push) and it works fine. However when I use following code, I get notification as a string "New Notification". This notification does not have header, default image as it should be .Also what we observed is when XML payload is commented and a simple string is send, the same notification is receieved. I doubt the XML payload what is send is not right. Please guide me
$tokenRequest = curl_init();
curl_setopt($tokenRequest, CURLOPT_URL, 'https://login.live.com/accesstoken.srf');
curl_setopt($tokenRequest, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
//FIELDS
$fields = array(
'grant_type' => 'client_credentials',
'client_id' => 'our client id',
'client_secret' => 'our client secret',
'scope' => 'notify.windows.com'
);
$fields_string = "";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
curl_setopt($tokenRequest, CURLOPT_RETURNTRANSFER, true);
curl_setopt($tokenRequest,CURLOPT_POST, count($fields));
curl_setopt($tokenRequest,CURLOPT_POSTFIELDS, $fields_string);
$output = json_decode(curl_exec($tokenRequest));
curl_close($tokenRequest);
echo "<br>";
echo "<br>";
$accessToken = $output->{'access_token'};
$sendPush = curl_init();
curl_setopt($sendPush, CURLOPT_URL, 'our URI here');
//TOAST MESSAGE
$toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
"<wp:Notification xmlns:wp=\"WPNotification\">" .
"<wp:Toast>" .
"<wp:Text1>Text...</wp:Text1>" .
"<wp:Text2>text..</wp:Text2>" .
"</wp:Toast>" .
"</wp:Notification>";
curl_setopt($sendPush, CURLOPT_HEADER, true);
echo $toastMessage;
$headers = array('Content-Type: text/xml',,"Content-Type: text/xml", "X-WNS-Type: wns/toast","Content-Length: " . strlen($toastMessage),"X-NotificationClass:2" ,"X-WindowsPhone-Target: toast","Authorization: Bearer $accessToken");
curl_setopt($sendPush, CURLOPT_HTTPHEADER, $headers);
curl_setopt($sendPush, CURLOPT_RETURNTRANSFER, true);
curl_setopt($sendPush,CURLOPT_POST, true);
curl_setopt($sendPush, CURLOPT_POSTFIELDS, $toastMessage));
$output = curl_exec($sendPush);
$info = curl_getinfo($sendPush);
echo($info['request_header']);
echo "<br>";
//var_dump(curl_getinfo($sendPush, CURLINFO_HTTP_CODE));
echo "<br>";
//var_dump(curl_getinfo($sendPush, CURLINFO_HEADER_OUT));
echo "<br>";
curl_close($sendPush);
The resultant XML payload is as following
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<wp:Notification
xmlns:wp=\"WPNotification\">
<wp:Toast>
<wp:Text1>Sharvin</wp:Text1>
<wp:Text2>Notif</wp:Text2>
</wp:Toast>
</wp:Notification>"
Try to change your toastMessage to :
$toastMessage = "<toast>".
"<visual>".
"<binding template=\"ToastText01\">".
"<text id=\"1\">".$message."</text>".
"</binding>".
"</visual>".
"</toast>";
You can find all the toast catalogue here https://msdn.microsoft.com/en-us/library/windows/apps/hh761494.aspx?f=255&MSPPError=-2147217396
Try to use below code, This code is well tested and working in many apps.
public function sendPushNotification($notify_url, $msg, $type) {
$delay = 1;
$msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
"<wp:Notification xmlns:wp=\"WPNotification\">" .
"<wp:Toast>" .
"<wp:typessss>".$type."</wp:typessss>" .
"<wp:Datassss>".$msg."</wp:Datassss>" .
"</wp:Toast>" .
"</wp:Notification>";
$sendedheaders = array(
'Content-Type: text/xml',
'Accept: application/*',
'X-WindowsPhone-Target: toast',
"X-NotificationClass: $delay"
);
$req = curl_init();
curl_setopt($req, CURLOPT_HEADER, true);
curl_setopt($req, CURLOPT_HTTPHEADER,$sendedheaders);
curl_setopt($req, CURLOPT_POST, true);
curl_setopt($req, CURLOPT_POSTFIELDS, $msg);
curl_setopt($req, CURLOPT_URL, $notify_url);
curl_setopt($req, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($req);
//echo '<pre>';
//print_r($response); die;
curl_close($req);
}