Microsoft Graph API - Uploaded file can not be opened - php

I am trying to upload a file using the Microsoft Graph API. It seems to upload OK, but when trying to open the file I am told that it can not be opened.
Here's the relavent part of my PHP code. I've using Guzzle to make the requests.
$data = file_get_contents($_FILES['foo']['tmp_name']);
$guzzle = new GuzzleHttp\Client();
$sent_options = [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'text/plain'
],
'form_params' => [
base64_encode($data)
]
];
$guzzle->put($url, $sent_options);

OK, so I've worked it out... for anyone else with the same problem, here's the solution.
$data = file_get_contents($_FILES['foo']['tmp_name']);
$guzzle = new GuzzleHttp\Client();
$sent_options = [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'text/plain'
],
'body' => $data
];
$guzzle->put($url, $sent_options);

Related

Adding PHP variable in JSON

I have this code to send whatsapp API
<?php
require_once('vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$product="shadow";
$response = $client->request('POST', 'https://live-server-10100.wati.io/api/v1/sendTemplateMessage?whatsappNumber=96655642XXXXX',
[
'body' => '{"parameters":
[{"name":"name1","value":"hosam"},
{"name":"discount_code","value":"gh5"},
{"name":"shop_name","value":$product}],
"template_name":"aband_cart4",
"broadcast_name":"test01"}',
'headers' => [
'Authorization' => 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0OTFmOGNkOS1mOWNOTM5Yy04MTEzMzhmMzc1ZjEiLCJ1bmlxdWVfbmFtZSI6ImFkbWluQGdoYW5hdHkuY29tIiwibmFtZWlkIjoiYWRtaW5AZ2hhbmF0eS5jb20iLCJlbWFpbCI6ImFkbWluQGdoYW5hdHkuY29tIiwiYXV0aF90aW1lIjoiMDIvMDUvMjAyMyAwNDo1NzozOCIsImRiX25hbWUiOiIxMDE3MDAiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJBRE1JTklTVFJBVE9SIiwiZXhwIjoyNTM0MDIzMDA4MDAsImlzcyI6IkNsYXJlX0FJIiwiYXVkIjoiQ2xhcmVfQUkifQ.3scVLBYDnzxPWlGQ_UfUgR_ecFQgnahQCnRQkAuzjoY',
'content-type' => 'text/json',
],
]);
echo $response->getBody();
?>
I tried to send post code with user value, and get error:
"{"result":false,"info":"Parameters is incorrect""
So what is the way to add PHP value $product to JSON?

Linkedin Video api upload throwing error 500

I am trying to create Video ad Campaigns using LinkedIn API. I am using Laravel, Guzzle and I have followed steps given in documentation to upload video
Initialize Upload for Video
Upload the Video
Finalize Video Upload
On Initialization I receive success response with multiple upload Urls depending on the file size. Using these uploadUrl I am making request to upload the file chunk using Guzzle but in response it is throwing INternal server error 500. I understand it can be server error but not sure if that raised to any header, param or token.
Please help If anyone has faced similar issue and got resolved. I am sharing the response of the initialize upload and request being made using Guzzle.
Doc Link
Response of Initialize APi
{#1344 // app/Services/LinkedIn/LinkedInCampaignService.php:328
+"value": {#1324
+"uploadUrlsExpireAt": 1669664693370
+"video": "urn:li:video:C4D10AQGwksU16dn3Zw"
+"uploadInstructions": array:2 [
0 => {#1325
+"uploadUrl": "https://www.linkedin.com/dms-uploads/C4D10AQGwksU16dn3Zw/uploadedVideo?sau=aHR0cHM6Ly93d3cubGlua2VkaW4uY29tL2FtYnJ5L2FtYnJ5LXZpZGVvLz94LWxpLWFtYnJ5LWVwPUFRTE9OS2RwQmlCOS1BQUFBWVM2bndCNTd1MTR1Yjh5bVVKQ1BERDhFcVhIN1hxcXl1OHBiM3BuUVVCLV82dng2cjZscGVkWmNJajZFZXR2c2trZ1pKM1Z2MVJwWDRxQnQ4T1Z1SWxHNGlUbk85eF9tX082dE11MHhySnhod0RmbFNzUlBvWV90b1Fjdmd0TlZUTlNOQ2RlQkZKR2Zodk8tSktkcWlGMUFpa3pDZjVveDFMcnBQbkY3TXBaYkVkdlpKQXJnMGQ4R3gxQmFZWGR2SFA4aXdtRWRGdGlrSGNLRXVTa283eDhvWnNOZX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TndTcjJZajNBZU4tcXVmRThtQy1qMzA4eEdic3NVQ0wxTTVSZTJjVmVxOS1pbDVQWmQ2MDRXU2lBSXhhejNDM09aenZmaXYtRkRwWlBIaEdscGVCYTdadFAycGRJMXR4eUpUdzVtcFFMTExiN1o2WGNscWoybWFlWkJwUkxZU0VIZXZ0Q29qMXNSUDRrcHQ0ZFluTUw1U0J6RV9qU2ZacW1pS21SS29RcnNrYWZrcUtUY0tMV1o5ZmZKTWZvaGNHTVE2ZTlRdlBJaGJHZ3ZSSFlWdFBjd1BOOG5uSG5rXzFIcE1SWWtWeGdoTVlhQm5KVGJrWDIxaExzYVBNVHlyM2FTQnlTME54c0c2UENMX202eDN2NlBmUC1nQXo1UDZOUGkxUHRubDE2Nm92Tm5ZNHNTdWxrNDdlaGVfZ1FZcnJDalZIbGVYZW4wU0g4TGUwaDNLczFLckdsekpyY0pqMjhQa29NQUdXN1ZCdktZN0ctdFZ0T0Q1cEswTTNsMUthUUQteGxsWnpVV3JLN2V2ZmtfZnEtZWNENTR5aHpKb1FVTzVmbWhDeDVIWERjT1ZYckhlWXlqVFlpbVQ5R1ZmdU9fbkdSZWtTczZENHZ6eVljejN1S0QxVmEzY3dnTU9heWQ4S3RBaVRjMGU3ZFVPdmJaMklNUnhnUlNKQnBaTmtDaHRybGRKQlJJUjRlakdMUkxJS2FpRElRUDlzMGkwUHZhNHVPOG8%253D&pn=2&m=91877349&app=4647153&sync=0&v=beta&ut=3GSFILXAS0Caw1"
+"lastByte": 5253879
+"firstByte": 4194304
}
]
+"uploadToken": ""
}
}
Calling Upload Urls
public function uploadChunkedVideo($fileName, $uploadInstructions)
{
try {
$fileHandler = fopen(storage_path('app') . '/' . $fileName, 'r');
$client = new Client();
$uploadPartIds = [];
foreach ($uploadInstructions as $instruction) {
$chunkedUpload = $client->put($instruction->uploadUrl, [
'headers' => [
'Content-Type' => 'application/octet-stream',
'Authorization' => 'Bearer ' . $this->accessToken,
'LinkedIn-Version' => config('services.linkedIn.version'),
],
'multipart' => [
[
'name' => $fileName,
'contents' => fread($fileHandler, $instruction->lastByte - $instruction->firstByte),
]
],
]);
//Push etag
$uploadPartIds[] = $chunkedUpload->getHeader('ETag')[0];
}
} catch (\GuzzleHttp\Exception\ServerException $e) {
dd($e->getResponse()->getBody()->getContents());
}
}
This worked for me.
$fileHandler = fopen(storage_path('app') . '/' . $fileName, 'r');
$client = new Client();
$uploadPartIds = [];
foreach ($uploadInstructions as $instruction) {
$chunkedUpload = $client->put($instruction->uploadUrl, [
'headers' => [
'Content-Type' => 'application/octet-stream',
'Authorization' => 'Bearer ' . $this->accessToken,
'LinkedIn-Version' => config('services.linkedIn.version'),
],
'body' => fread($fileHandler, $instruction->lastByte - $instruction->firstByte),
]);
//Push etag
$uploadPartIds[] = $chunkedUpload->getHeader('ETag')[0];
info($uploadPartIds);
}
return $uploadPartIds;

Laravel Gazzel Making multiple requests to same URL without login multiple times

So I have this class setup in laravel. It is using following header to initialize requests.
$this->xml = "<?xml version=\"1.0\"?>
<query xmlns=\"http://www.someurl.com/queryLanguage/v1.0\">
<logon>
<userName>".config('some.username')."</userName>
<password>".config('some.password')."</password>
<deviceName>".config('some.device')."</deviceName>
</logon>";
Then I have like 10 requests to make to the same url with above auth details.
so im doing it like.
$xml1 = $this->xml;
$xml1 .= "some xml";
$options = [
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
],
'body' => $xml1,
];
$client = new Client();
$response = $client->request('POST', config('some.apiurl'), $options);
$xml2 = $this->xml;
$xml2 .= "some xml";
$options = [
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
],
'body' => $xml2,
];
$client = new Client();
$response = $client->request('POST', config('some.apiurl'), $options);
$xml3 = $this->xml;
$xml3 .= "some xml";
$options = [
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
],
'body' => $xml3,
];
$client = new Client();
$response = $client->request('POST', config('some.apiurl'), $options);
as you can see with each requests it makes a new login and eventually ended up getting too many concurrent logons error from remote server. so my question is how we use this api login information and just login once with guzzel and then use it for multiple requests later.
Thanks in advance.
You can use Guzzle CookieJar to save your session and send it to the next request.
http://docs.guzzlephp.org/en/stable/quickstart.html#cookies
#Request-1
$login = $client->request("POST" , $url , [
"headers" => $header,
"body" => $xmlLogin
]);
// Here you should get all cookies from $login request and save it to $tmpCookieJar variable for example.
// For request-2 it will depends on the requirement of the endpoint or api.
#Request-2
$action2 = $client->request("POST" , $url , [
"headers" => $header,
"body" => $xmlLogin, // If necessary
"cookies" => $tmpCookieJar
]);

(Updated) Laravel PUT Method Not Working

updated - the JSON file would return but it will not change the billing date at all.
Reference 1: The official documentation about changing the billing date.
Reference2: their sample code in detail:
<?php
$request = new HttpRequest();
$request->setUrl('https://domain.chargify.com/subscriptions/$subscriptionId.json');
$request->setMethod(HTTP_METH_PUT);
$request->setHeaders(array(
'authorization' => 'Basic YXBpa2V5Og==',
'content-type' => 'application/json'
));
$request->setBody('{"subscription":{"next_billing_at":"2028-12-15"}}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
My code in detail:
public function changeYearlySubscriptionBillingDate(Request $request)
{
$user = $request->user();
$subscriptionId = $user->subscription->subscription_id;
$nextBilling = Carbon::now()->addYear();
$hostname = env('CHARGIFY_HOSTNAME');
$headers = [
'authorization' => 'Basic ANIDIANDIAJIJCQ',
'content-type' => 'application/json'
];
$body = ["subscription" => ["next_billing_at" =>[ $nextBilling ]]];
$config = [
'headers' => $headers,
'form_param' => $body
];
$client = new Client($config);
$res = $client->put("https://$hostname/subscriptions/$subscriptionId.json",
["json" => [
[ "subscription" =>
[ "next_billing_at" => $nextBilling ]
]
]
]);
echo $res->getBody();
}
The url you are building is incorrect. There shouldn't be a / between $subscription and .json
Change
$res = $client->put("https://$hostname/subscriptions/$subscriptionId/.json",
to
$res = $client->put("https://$hostname/subscriptions/$subscriptionId.json",
EDIT
Try changing the logic to make Guzzle call like this.
$headers = [
'authorization' => 'Basic ANIDIANDIAJIJCQ',
'content-type' => 'application/json'
];
$body = ["subscription" => ["next_billing_at" =>[ $nextBilling ]]];
$client = new Client();
$res = $client->put("https://$hostname/subscriptions/$subscriptionId.json",
[
'headers' => $headers,
'body' => json_encode($body)
]
);
echo $res->getBody()->getContents();
thanks everyone so much for helping me out.
I've been working on this problem for 2 days and it was supposed to be right to me. Eventually, it is their API that misled me.
the only thing we need to do, is simply change
'body' => "{\"subscription\":{\"next_billing_at\":\"$nextBilling\"}}"
added a few '\' s inside.
Thanks everyone for helping me out, have a good day!

Can you include raw JSON in Guzzle POST Body?

This should be soo simple but I have spent hours searching for the answer and am truly stuck. I am building a basic Laravel application and am using Guzzle to replace the CURL request I am making at the moment. All the CURL functions utilise raw JSON variables in the body.
I am trying to create a working Guzzle client but the server is respsonding with 'invalid request' and I am just wondering if something fishy is going on with the JSON I am posting. I am starting to wonder if you can not use raw JSON in the Guzzle POST request body? I know the headers are working as I am receiving a valid response from the server and I know the JSON is valid as it is currently working in a CURL request. So I am stuck :-(
Any help would be sooo greatly appreciated.
$headers = array(
'NETOAPI_KEY' => env('NETO_API_KEY'),
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'NETOAPI_ACTION' => 'GetOrder'
);
// JSON Data for API post
$GetOrder = '{
"Filter": {
"OrderID": "N10139",
"OutputSelector": [
"OrderStatus"
]
}
}';
$client = new client();
$res = $client->post(env('NETO_API_URL'), [ 'headers' => $headers ], [ 'body' => $GetOrder ]);
return $res->getBody();
You can send a regular array as JSON via the 'json' request option; this will also automatically set the right headers:
$headers = [
'NETOAPI_KEY' => env('NETO_API_KEY'),
'Accept' => 'application/json',
'NETOAPI_ACTION' => 'GetOrder'
];
$GetOrder = [
'Filter' => [
'OrderID' => 'N10139',
'OutputSelector' => ['OrderStatus'],
],
];
$client = new client();
$res = $client->post(env('NETO_API_URL'), [
'headers' => $headers,
'json' => $GetOrder,
]);
Note that Guzzle applies json_encode() without any options behind the scenes; if you need any customisation, you're advised to do some of the work yourself
$res = $client->post(env('NETO_API_URL'), [
'headers' => $headers + ['Content-Type' => 'application/json'],
'body' => json_encode($getOrders, ...),
]);
Guzzle 7 Here
The below worked for me with raw json input
$data = array(
'customer' => '89090',
'username' => 'app',
'password' => 'pwd'
);
$url = "http://someendpoint/API/Login";
$client = new \GuzzleHttp\Client();
$response = $client->post($url, [
'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($data)
]);
print_r(json_decode($response->getBody(), true));
For some reasons until I used the json_decode on the response, the output wasn't formatted.
You probably need to set the body mime type. This can be done easily using the setBody() method.
$request = $client->post(env('NETO_API_URL'), ['headers' => $headers]);
$request->setBody($GetOrder, 'application/json');

Categories