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!
Related
I have a method for to send the data to API. I test data in postman. It is working ok. But in the project it is not working. But I copied the method another project it is working here. How can I solve the problem?
function send_candidates_f2()
{
$my_json = '
{
"typeObj": "1",
"tin": "305050590",
"pinfl": "asas",
"tinName": "IQTIDOR ZIYOSI НТМ",
"ns1Code": "14",
"ns3Code": "4",
"ns41Code": "33",
"ns42Code": "1",
"ns10Code": "14",
"ns11Code": "9",
"ns10Code_1": "14",
"ns11Code_1": "9",
"f2Num": 1,
"f2Date": "23.01.2023",
"rukName": "ERGASHEV JAVOHIR ALISHEROVICH",
"buhName": "НЕ ПPЕДУСМОТPЕН",
"nprk": "",
"dateprk": "",
"prvdbeg": "23.01.2023",
"prvdend": "23.01.2023",
"otdel": "1",
"fabula": "sdsdf",
"violationCode1": "5",
"tin2": "420540289",
"year": "2023",
"pkey": "F2ECC0F41C123142E053DE3A18ACF835",
"na3Code": "D0515486CD830030E043C0A8502B15AA",
"files": [
"xs_buyruq_ilovasi.pdf"
],
"fileAct": "F2ECC0F41C133142E053DE3A18ACF835",
"confirmedBy": "NARKULOVA MARXAMAT YUSUPOVNA",
"enteredBy": "NARKULOVA MARXAMAT YUSUPOVNA",
"objectId": "1",
"appType": "Сайёр солик текширувда ноконуний тадбиркорлик(рейд)"
}';
// var_dump($my_json); die();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://dev-tax-offenses-api.soliq.local/tax-offence-api/apray/set-apray-candidate",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 86400,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $my_json,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
curl_close($curl);
var_dump($response); die();
}
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;
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,
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);
I wanted to use Personality Insight Service of Watson to analyze the tweets of user. I am using PHP to code. Here is the block of code I am using to get the tweets from Twitter API and input them in PI service of watson.
//Watson PI Parameters
$pi_url = 'https://gateway.watsonplatform.net/personality-
insights/api/v3/profile?version=2016-10-20';
$pi_username = 'XXXX';
$pi_password = 'YYYY';
// auth parameters
$api_key = urlencode('API KEY'); // Consumer Key
$api_secret = urlencode('API Secret'); // Consumer Secret
$auth_url = 'https://api.twitter.com/oauth2/token';
// Twitter Data Parameters
$data_username = 'Screen Name'; // username
$data_count = 10; // number of tweets
$data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?
tweet_mode=extended';
// get api access token
$api_credentials = base64_encode($api_key.':'.$api_secret);
$auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
'Content-Type: application/x-www-form-urlencoded;charset=UTF-
8'."\r\n";
$auth_context = stream_context_create(
array(
'http' => array(
'header' => $auth_headers,
'method' => 'POST',
'content'=> http_build_query(array('grant_type' =>
'client_credentials', )),
)
)
);
$auth_response = json_decode(file_get_contents($auth_url, 0,
$auth_context), true);
$auth_token = $auth_response['access_token'];
// get tweets
$data_context = stream_context_create( array( 'http' => array( 'header' =>
'Authorization: Bearer '.$auth_token."\r\n", ) ) );
$data = file_get_contents($data_url.'&count='.$data_count.
'&screen_name='.urlencode($data_username), 0, $data_context);
print_r($data);
// Pass $data as input to PI
$ch = curl_init();
// Sets the URL cURL will open
curl_setopt($ch, CURLOPT_URL, $pi_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
)
);
// Here's the HTTP auth
curl_setopt($ch, CURLOPT_USERPWD, $pi_username." : ".$pi_password);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "\CertificateLocation");
// Makes curl_exec() return server response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// And here's the result JSON
$response = curl_exec($ch);
print curl_error($ch);
curl_close($ch);
print_r($response);
I am receiving {
"code": 400,
"sub_code": "S00005",
"error": "Invalid JSON input at line 4, column 28"
} error though.
Can someone please help on how should I pre- format my twitter response so PI can identify it as Json input and analyze it.
EDIT:
Adding the twitter result as answer, as it is too long for comment. Here is the result I am getting with Amazon twitter handle ( tried this just for test)
[{
"created_at": "Thu Apr 20 14:49:27 +0000 2017",
"id": 855070913997492225,
"id_str": "855070913997492225",
"full_text": "#realivanspeaks Aww! We love our customers like Buddy loves a his sugar. \ud83d\ude0d \ud83c\udf6c",
"truncated": false,
"display_text_range": [
16,
76
],
"entities": {
"hashtags": [
],
"symbols": [
],
"user_mentions": [
{
"screen_name": "realivanspeaks",
"name": "Ivan Speaks",
"id": 2484007045,
"id_str": "2484007045",
"indices": [
0,
15
]
}
],
"urls": [
]
},
"source": "\u003ca href=\"https:\/\/www.sprinklr.com\" rel=\"nofollow\"\u003eSprinklr\u003c\/a\u003e",
"in_reply_to_status_id": 855068504642514944,
"in_reply_to_status_id_str": "855068504642514944",
"in_reply_to_user_id": 2484007045,
"in_reply_to_user_id_str": "2484007045",
"in_reply_to_screen_name": "realivanspeaks",
"user": {
"id": 20793816,
"id_str": "20793816",
"name": "Amazon",
"screen_name": "amazon",
"location": "Seattle, Washington",
"description": "Official Twitter of http:\/\/t.co\/4rwjfdidk3. Contact #AmazonHelp for customer support.",
"url": "http:\/\/t.co\/Z2A4m7UeSv",
"entities": {
"url": {
"urls": [
{
"url": "http:\/\/t.co\/Z2A4m7UeSv",
"expanded_url": "http:\/\/www.amazon.com",
"display_url": "amazon.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": [
{
"url": "http:\/\/t.co\/4rwjfdidk3",
"expanded_url": "http:\/\/Amazon.com",
"display_url": "Amazon.com",
"indices": [
20,
42
]
}
]
}
},
"protected": false,
"followers_count": 2567418,
"friends_count": 157,
"listed_count": 13988,
"created_at": "Fri Feb 13 18:39:54 +0000 2009",
"favourites_count": 3092,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 23791,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "9ACAF8",
"profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/448506280982753280\/GZ6eb7ux.png",
"profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/448506280982753280\/GZ6eb7ux.png",
"profile_background_tile": false,
"profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/786252488223580160\/9-Lwv1sI_normal.jpg",
"profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/786252488223580160\/9-Lwv1sI_normal.jpg",
"profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/20793816\/1492450739",
"profile_link_color": "FF9900",
"profile_sidebar_border_color": "FFFFFF",
"profile_sidebar_fill_color": "FFFFFF",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": null,
"follow_request_sent": null,
"notifications": null,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"lang": "en"
}]