$body->append(); from POSTMAN API, how to replace it with variables? - php

Given this generated code from postman, $body->append(); from POSTMAN API, how to replace it with variables?
how to replace the CURLOPT_POSTFIELDS with php variables? so it can be filled with dynamic variable
what is the best practices to do it?
thank you
<?php
$json = '{
"RateRequest": {
"ClientDetails" : null,
"RequestedShipment": {
"DropOffType": "REQUEST_COURIER",
"ShipTimestamp": "2020-08-25T11:00:00GMT+02:00",
"UnitOfMeasurement": "SI",
"Content": "NON_DOCUMENTS",
"PaymentInfo": "DAP",
"NextBusinessDay": "Y",
"Account": "54xxxxxx",
"Ship": {
"Shipper": {
"City": "city",
"PostalCode": 123456,
"CountryCode": "ID"
},
"Recipient" : {
"City" : "canberra",
"PostalCode" : 2601,
"CountryCode" : "AU"
}
},
"Packages": {
"RequestedPackages": {
"#number": "1",
"Weight": {
"Value": 8.82
},
"Dimensions": {
"Length": 4.33,
"Width": 4.33,
"Height": 4.33
}
}
}
}
}
}';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://wsbexpress.dhl.com/rest/sndpt/RateRequest",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => array(
"Authorization: Basic YmF0dWxheWFuZ3NJRDpKXjBlUEA2dkQhM2Y=",
"Content-Type: application/json",
"Cookie: BIGipServer~WSB~pl_wsb-express-cbj.dhl.com_443=293349575.64288.0000"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

json_decode the string into an array
modify the values as needed
set that data for CURLOPT_POSTFIELDS
Something like this
$json = '{
"RateRequest": {
"ClientDetails" : null,
"RequestedShipment": {
"DropOffType": "REQUEST_COURIER",
"ShipTimestamp": "2020-08-25T11:00:00GMT+02:00",
"UnitOfMeasurement": "SI",
"Content": "NON_DOCUMENTS",
"PaymentInfo": "DAP",
"NextBusinessDay": "Y",
"Account": "54xxxxxx",
"Ship": {
"Shipper": {
"City": "city",
"PostalCode": 123456,
"CountryCode": "ID"
},
"Recipient" : {
"City" : "canberra",
"PostalCode" : 2601,
"CountryCode" : "AU"
}
},
"Packages": {
"RequestedPackages": {
"#number": "1",
"Weight": {
"Value": 8.82
},
"Dimensions": {
"Length": 4.33,
"Width": 4.33,
"Height": 4.33
}
}
}
}
}
}';
$data = json_decode($json, true);
if (isset($data['RateRequest']['RequestedShipment']['DropOffType'])) {
$data['RateRequest']['RequestedShipment']['DropOffType'] = 'some new value';
}
//... later in your curl call...
CURLOPT_POSTFIELDS => $data,

Related

Getting 401 unauthorzed error while creating order with Shipstation REST API and PHP

I am trying to connect Shipstation with my website using REST API and creating order which can be added to manual store inside Shipstation by default. However, I am getting error 401 unauthorised continuously, even I copied API key and API secret from Shipstation account and passed its base64 form to Authorization header.
Here is my Simple Post Request :
$api_key = 'SS_KEY';
$api_secret = 'SS_SECRET';
$token = base64_encode($api_key.':'.$api_secret);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://ssapi.shipstation.com/orders/createorder/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"orderNumber": "TEST-ORDER-API-DOCS",
"orderStatus": "awaiting_shipment",
"customerUsername": "abc",
"customerEmail": "headhoncho#whitehouse.gov",
"billTo": {
"name": "Inam Ali",
"company": "abc",
"street1": "1",
"street2": null,
"street3": null,
"city": "Pesh",
"state": "KPK",
"postalCode": 25000,
"country": "Pakistan",
"phone": "0315333333",
"residential": true
},
"shipTo": {
"name": "Inam Ali",
"company": "US Govt",
"street1": "1600 Pennsylvania Ave",
"street2": "Oval Office",
"street3": null,
"city": "Washington",
"state": "DC",
"postalCode": "20500",
"country": "US",
"phone": "555-555-5555",
"residential": true
},
"items": [
{
"lineItemKey": "vd08-MSLbtx",
"name": "Test item #1",
"imageUrl": null,
"quantity": 2,
"unitPrice": 99.99,
"taxAmount": 2.5,
}
],
"amountPaid": 218.73,
"taxAmount": 5,
"tagIds": [
53974
]
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'host: ssapi.shipstation.com',
'Authorization: Basic '.$token
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Random Characters PHP Decode Nested JSON

Really struggling with this one. I have connected to the API fine and can get the raw JSON Data.
But when I am trying to decode it I just get a load of random characters.
The JSON path should be response->data->fieldData->Case_ID
There are other fields there also but I have hidden them to make it easier to read.
This is my JSON
{
"response": {
"dataInfo": {
"database": "MicroLog",
"layout": "External_API_Cases",
"table": "Cases",
"totalRecordCount": 143691,
"foundCount": 23,
"returnedCount": 2
},
"data": [
{
"fieldData": {
"Case_ID": 139220,
},
"portalData": {},
"recordId": "139261",
"modId": "138"
},
{
"fieldData": {
"Case_ID": 143421,
},
"portalData": {},
"recordId": "143462",
"modId": "25"
}
]
},
"messages": [
{
"code": "0",
"message": "OK"
}
]
}
The code I have been using.
<?php
include('login.php');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'URL_HERE',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"query": [
{
"Closed": "1",
"Closed_TimeStamp": "06/24/2021"
}
],
"limit": 2
}',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '.$token.'',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$decode = json_decode($response,true);
foreach ($decode['response']['data'] as $dec) {
foreach ($dec['fieldData'] as $cd) {
echo $cd['Case_ID'];
}
echo "<br/>";
}
?>
This is what it returns
188B7162M111662J>41ISS1AM1200000000000J5D
118A7162I11162J�62ISS1AM120000000000J5D

PHP array foreach item

I'm Having issues grabbing values in a multi level array.
This is my JSON I am grabbing with CURL and putting into a variable.
{
"id": 454626,
"results": [
{
"iso_3166_1": "SK",
"release_dates": [
{
"certification": "U",
"iso_639_1": "sk",
"note": "",
"release_date": "2020-02-20T00:00:00.000Z",
"type": 3
}
]
},
{
"iso_3166_1": "DE",
"release_dates": [
{
"certification": "6",
"iso_639_1": "",
"note": "",
"release_date": "2020-02-13T00:00:00.000Z",
"type": 3
}
]
},
{
"iso_3166_1": "TW",
"release_dates": [
{
"certification": "G",
"iso_639_1": "",
"note": "",
"release_date": "2020-02-21T00:00:00.000Z",
"type": 3
}
]
}
]
}
This is my PHP code that I'm having issues with.
$id_tmdb = $row[id_tmdb];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.themoviedb.org/3/movie/$id_tmdb/release_dates?api_key=API-KEY",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$result = json_decode($response, true);
foreach($result[results][release_dates] as $key=>$val){
echo "$val[release_date]";
}
I'm trying to get the release_date but it just shows blank.
I have another page that is formatted the same way so I am unsure why it isn't working.... Thank you for all your help.
Your $result['results'] value is also an array and you need to iterate over that as well as the release_dates array:
foreach($result['results'] as $results) {
foreach ($results['release_dates'] as $val){
echo "$val[release_date]\n";
}
}
Output (for the sample JSON provided):
2020-02-20T00:00:00.000Z
2020-02-13T00:00:00.000Z
2020-02-21T00:00:00.000Z
Demo on 3v4l.org
This should get you there:
foreach($result['results'] as $res){
echo $res['release_dates'][0]['release_date']."\n";
}
3v4l link
On a side-note, I put the array keys in quotes to prevent php warnings.

JSON and CURL encoding

I have a curl page that output in json format but I can't get json reading from android correctly. I want Json format with just an array only not object and array together. Check the output at the bottom for example. I want to write a php code that encode json that matches below. How would i do that? Thanks.
PHP FILE:
<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/vendor/mashape/unirest-php/src/Unirest.php';
//$response = Unirest\Request::get("",
// array(
// "host" => "",
// "key" => "
// )
//);
//
//
//echo stripslashes(json_encode($response));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "json",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_HTTPHEADER, array('Accept: application/json'),
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"host: ",
"KEY: "
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
$json = json_encode($response, JSON_UNESCAPED_SLASHES);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo stripslashes($response);
}
$fp = fopen('results.json', 'w');
fwrite($fp, stripslashes($response));
fclose($fp);
ORIGINAL OUTPUT FROM CURL:
{
"quoteResponse":
{
"result": [{
"language": "en-US",
"region": "US",
"quoteType": "EQUITY",
"quoteSourceName": "Nasdaq Real Time Price",
"exchangeDataDelayedBy": 0,
"regularMarketPrice": 30.69,
"regularMarketTime": 1568404801,
"regularMarketChange": 0.48000145,
"regularMarketVolume": 45547913,
"shortName": "Advanced Micro Devices, Inc.",
"priceHint": 2,
"postMarketChangePercent": 0.0325846,
"postMarketTime": 1568419190,
"postMarketPrice": 30.7,
"postMarketChange": 0.0100002,
"regularMarketChangePercent": 1.5888827,
"regularMarketPreviousClose": 30.21,
"fullExchangeName": "NasdaqGS",
"longName": "Advanced Micro Devices, Inc.",
"market": "us_market",
"pageViews": {
"shortTermTrend": "UP",
"midTermTrend": "UP",
"longTermTrend": "UP"
},
"marketState": "CLOSED",
"exchange": "NMS",
"sourceInterval": 15,
"exchangeTimezoneName": "America/New_York",
"exchangeTimezoneShortName": "EDT",
"gmtOffSetMilliseconds": -14400000,
"esgPopulated": false,
"tradeable": true,
"triggerable": true,
"symbol": "AMD"
}],
"error": null
}
}
THE OUTPUT I WANT IS THIS WITHOUT quoteResponse LIKE ABOVE OUTPUT. CHECK BELOW :
{
"result": [{
"language": "en-US",
"region": "US",
"quoteType": "EQUITY",
"quoteSourceName": "Nasdaq Real Time Price",
"regularMarketPrice": 30.69,
"regularMarketTime": 1568404801,
"regularMarketChange": 0.48000145,
"regularMarketVolume": 45547913,
"sourceInterval": 15,
"exchangeTimezoneName": "America/New_York",
"exchangeTimezoneShortName": "EDT",
"pageViews": {
"shortTermTrend": "UP",
"midTermTrend": "UP",
"longTermTrend": "UP"
},
"gmtOffSetMilliseconds": -14400000,
"market": "us_market",
"postMarketChangePercent": 0.0325846,
"postMarketTime": 1568419190,
"postMarketPrice": 30.7,
"postMarketChange": 0.0100002,
"regularMarketChangePercent": 1.5888827,
"priceHint": 2,
"shortName": "Advanced Micro Devices, Inc.",
"regularMarketPreviousClose": 30.21,
"fullExchangeName": "NasdaqGS",
"longName": "Advanced Micro Devices, Inc.",
"exchange": "NMS",
"exchangeDataDelayedBy": 0,
"esgPopulated": false,
"tradeable": true,
"triggerable": true,
"marketState": "CLOSED",
"symbol": "AMD"
}],
"error": null
}
Decode your JSON, get quoteResponse from it and encode it again.
$json = json_encode(json_decode($json)->quoteResponse);

Error in sending Raw data with cURL in PHP

I have to send a request to an API. The reques should contain some data along with 4 header parameters. Teh Raw data that I want to send is the $raw_data.
The Error is : Internal Server Error
My Code is as follows :
<?php
function CurlSendPostRequest($url,$request="")
{
$raw_data='{
"job_id": null,
"collectionOnDelivery": false,
"invoice": null,
"collectionDate": "2015-01-30T09:00:00",
"consolidate": false,
"consignment": [{
"consignmentNumber": null,
"consignmentRef": null,
"parcels": [],
"collectionDetails": {
"contactDetails": {
"contactName": "My Contact",
"telephone": "0121 500 2500"
},
"address": {
"organisation": "GeoPostUK Ltd",
"countryCode": "GB",
"postcode": "B66 1BY",
"street": "Roebuck Lane",
"locality": "Smethwick",
"town": "Birmingham",
"county": "West Midlands"
}
},
"deliveryDetails": {
"contactDetails": {
"contactName": "My Contact",
"telephone": "0121 500 2500"
},
"address": {
"organisation": "GeoPostUK Ltd",
"countryCode": "GB",
"postcode": "B66 1BY",
"street": "Roebuck Lane",
"locality": "Smethwick",
"town": "Birmingham",
"county": "West Midlands"
},
"notificationDetails": {
"email": "my.email#geopostuk.com",
"mobile": "07921000001"
}
},
"networkCode": "2^12",
"numberOfParcels": 1,
"totalWeight": 5,
"shippingRef1": "My Ref 1",
"shippingRef2": "My Ref 2",
"shippingRef3": "My Ref 3",
"customsValue": null,
"deliveryInstructions": "Please deliver with neighbour",
"parcelDescription": "",
"liabilityValue": null,
"liability": false
}]
}';
// $authentication = base64_encode("USER:PASS");
$ch = curl_init($url);
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_POSTFIELDS => $raw_data,
// CURLOPT_FOLLOWLOCATION => false, // follow redirects
// CURLOPT_ENCODING => "utf-8", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
// CURLOPT_CONNECTTIMEOUT => 20, // timeout on connect
// CURLOPT_TIMEOUT => 20, // timeout on response
CURLOPT_POST => 1, // i am sending post data
CURLOPT_POSTFIELDS => $request, // this are my post vars
// CURLOPT_SSL_VERIFYHOST => 0, // don't verify ssl
// CURLOPT_SSL_VERIFYPEER => false, //
// CURLOPT_VERBOSE => 1,
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Content-Type: application/json",
"GEOClient: account/XX-ACC_NO-XX",
"GEOSession: XX-SESS_ID-XX"
)
);
curl_setopt_array($ch,$options);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
//echo $curl_errno;
//echo $curl_error;
print_r($data);
curl_close($ch);
return $data;
}
$url = "https://api.URL.com";
CurlSendPostRequest($url);
?>
A very silly mistake was done : I added a line
CURLOPT_POSTFIELDS => $raw_data,
and few lines below I added
CURLOPT_POSTFIELDS => $request,
My values for the raw Data are in $raw_data, thus $request was over-writing that.Just need to comment the line :
CURLOPT_POSTFIELDS => $request,
and it works great!

Categories