So, i'm trying to communicate with a curl for a project using php, and send data from my database with the POST method.
but i'm getting the "Invalid Key Character" error, and i really don't know what else to do to fix this...
The code:
<?php
require_once('autoload.php');
require_once('vendor/autoload.php');
$conexao = new Conexao();
$produtos = $conexao->select('produto', '*', 'LIMIT 1');
foreach ($produtos as $produto) {
try {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "url");
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "X-Api-Key: key";
$headers[] = "X-App-Key: key";
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_HEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
$status = 1;
if ($produto['status'] == 1){
$status = 0;
}
$valores = '
{
"product":{
"name":"'. trim($produto['descricao']) .'",
"sku":"'. trim($produto['cod_est']) .'",
"description":"'. trim($produto['obs']) .'",
"price":'. $produto['valor_vend'] .',
"saleprice":'. $produto['vl_promo'] .',
"categories": [
"'. trim($produto['ender3']) .'"
],
"properties": [],
"related_products": [],
"special_options": [],
"slug":"'. str_replace(' ', '-', trim($produto['descricao'])) .'",
"excerpt":"'. trim($produto['descricao']) .'",
"factory_price":'. $produto['ult_custo'] .',
"installments": 1,
"shippable":0,
"fixed_quantity": 999,
"gtin_code":"'. trim($produto['cod_fabr']) .'",
"ncm_code":"'. trim($produto['cod_ncm']). '",
"track_stock": 0,
"enabled":' . $status . ',
"video": "",
"weight":"' . $produto['peso_brut']. '",
"height": "' . $produto['espessura'] . '",
"width": "' . $produto['largura'] . '",
"depth": "' . $produto['compriment'] . '",
"meta": "",
"seo_title": "",
"seo_description":"'. trim($produto['descricao']) . '",
"seo_keywords":"'. str_replace(' ',',',strtolower(trim($produto['descricao']))) .'"
}
}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $valores);
$response = curl_exec($curl);
curl_close($curl);
print_r($response);
}
catch (Exception $e){
echo 'Ocorreu um Erro: ' . $e;
}
}
The error:
HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8 Content-Length: 263 Connection: keep-alive Cache-Control: max-age=1, public Date: Wed, 27 Dec 2017 19:09:30 GMT Expires: Wed, 27 Dec 2017 19:09:31 GMT Server: Apache Vary: Accept-Encoding X-Cache: Miss from cloudfront Via: 1.1 f2e2a7eca4778c8776461616fad77017.cloudfront.net (CloudFront) X-Amz-Cf-Id: urR4k92zkT2PCfimpCNAf5-uBmUi46nvHM6J-aWVZ8OxDYZUPteEWg== Disallowed Key Characters. "\r\n\t\t{\r\n\t\t\t\"product\":{\r\n\t\t\t\t\"name\":\"PH_CAMISA_GOLA_V_BR_12\",\r\n\t\t\t\t\"sku\":\"2129246\",\r\n\t\t\t\t\"description\":\"\",\r\n\t\t\t\t\"price\":49_000,\r\n\t\t\t\t\"saleprice\":0_000,\r\n\t\t\t\t\"categories\":_"
if i copy the generated json and paste to JSONLint, it shows that the json is valid...
Any Tips on how to solve this?
You just don't build JSON by hand in PHP.
You first build your data structure and THEN you json_encode() the whole thing...
$valores = [
"product" => [
"name" => trim($produto['descricao']),
"sku" => trim($produto['cod_est']),
"description" => trim($produto['obs']),
"price" => $produto['valor_vend'],
"saleprice" => $produto['vl_promo'],
"categories" => [
trim($produto['ender3']) // I'm not so sure here...
],
"properties" => [],
...
...
...
]
];
// $valores is an array containing your data.
$encoded = json_encode($valores);
// $encoded is a string containing encoded JSON.
json_encode() handles everything for you (escaping, etc.). It also has some options - for that see the manual.
Related
I converted the following Python code from the official docs(https://docs.sandbox.gemini.com/rest-api/#private-api-invocation) to PHP but I always get InvalidSignature error:
url = "https://api.gemini.com/v1/mytrades"
gemini_api_key = "mykey"
gemini_api_secret = "1234abcd".encode()
t = datetime.datetime.now()
payload_nonce = time.time()
payload = {"request": "/v1/mytrades", "nonce": payload_nonce}
encoded_payload = json.dumps(payload).encode()
b64 = base64.b64encode(encoded_payload)
signature = hmac.new(gemini_api_secret, b64, hashlib.sha384).hexdigest()
request_headers = {
'Content-Type': "text/plain",
'Content-Length': "0",
'X-GEMINI-APIKEY': gemini_api_key,
'X-GEMINI-PAYLOAD': b64,
'X-GEMINI-SIGNATURE': signature,
'Cache-Control': "no-cache"
}
response = requests.post(url, headers=request_headers)
My PHP code is this and everything looks correct:
$b64 = base64_encode(utf8_encode(json_encode([ "request" => "/v1/balances", "nonce" => time() ])));
$header = [
'Content-Type: text/plain',
'Content-Length: 0',
'X-GEMINI-APIKEY: master-XXXXXXX',
'X-GEMINI-PAYLOAD: ' . $b64,
'X-GEMINI-SIGNATURE: ' . md5(hash_hmac('sha384', utf8_encode('XXXXXXXXXX'), $b64)),
'Cache-Control: no-cache'
];
$ch = curl_init('https://api.sandbox.gemini.com/v1/balances');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
echo curl_exec($ch);
Error:
{"result":"error","reason":"InvalidSignature","message":"InvalidSignature"}
I don't have any access to the API, but could you please try the following chagnes:
Remove the MD5 function from the signature calculation. The hash_hmac function in PHP already does this by default.
'X-GEMINI-SIGNATURE: ' . hash_hmac('sha384', utf8_encode('XXXXXXXXXX'), $b64),
Switch around the payload and the key in the same line:
'X-GEMINI-SIGNATURE: ' . hash_hmac('sha384', $b64, utf8_encode('XXXXXXXXXX')),
we have been working with 3d cart rest response which we have successfully get here is my code.file name example.php which located in my wamp server
<?php
$host = 'https://apirest.3dcart.com';
$version = 1;
$service = 'Orders';
$secureUrl = 'https://xxxxyyyyy.3dcart.net'; // Secure URL is set in Settings->General->StoreSettings
$privateKey = 'xxxxxxxxxxxxxxxx'; // Private key is obtained when registering your app at http://devportal.3dcart.com
$token = 'xxxxxxxxxxxxx'; // The token is generated when a customer authorizes your app
// initialize cURL session
$ch = curl_init($host . '/3dCartWebAPI/v' . $version . '/' . $service);
// set headers
$httpHeader = array(
'Content-Type: application/json;charset=UTF-8',
'Accept: application/json',
'SecureUrl: ' . $secureUrl,
'PrivateKey: ' . $privateKey,
'Token: ' . $token,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
// [ ... addtional cURL options as needed ... ]
$response = curl_exec($ch);
if ($response === false) {
$response = curl_error($ch);
}
curl_close($ch);
we have an access file on a browser using this URL http://localhost/social/example.php get a response in JSON like this without JSON encoded. but I want array this response so we can write CSV file.i have many try to google but no more luck for appropriate solution.thanks in advance.
[{"InvoiceNumberPrefix":"AB-","InvoiceNumber":1000,"OrderID":1,"CustomerID":1,"OrderDate":"2014-01-10T12:44:37","OrderStatusID":1,"LastUpdate":"0001-01-01T00:00:00","UserID":"","SalesPerson":"","ContinueURL":"http://71745179439.3dcart.net/continue_order.asp?orderkey=tl31S22wts7B0hF1","BillingFirstName":"John","BillingLastName":"Doe","BillingCompany":"","BillingAddress":"123 Street","BillingAddress2":"","BillingCity":"Coral Springs","BillingState":"FL","BillingZipCode":"33065","BillingCountry":"US","BillingPhoneNumber":"800-828-6650","BillingEmail":"test#3dcart.com","BillingPaymentMethod":"Online Credit Card","BillingOnLinePayment":true,"BillingPaymentMethodID":"1","ShipmentList":[{"ShipmentID":0,"ShipmentLastUpdate":"0001-01-01T00:00:00","ShipmentBoxes":1,"ShipmentInternalComment":"Sample Order from 3dcart","ShipmentOrderStatus":1,"ShipmentAddress":"123 Street","ShipmentAddress2":"","ShipmentAlias":"","ShipmentCity":"Coral Springs","ShipmentCompany":"","ShipmentCost":0.0,"ShipmentCountry":"US","ShipmentEmail":"","ShipmentFirstName":"Test","ShipmentLastName":"Test","ShipmentMethodID":0,"ShipmentMethodName":"Free Shipping","ShipmentShippedDate":"","ShipmentPhone":"800-828-6650","ShipmentState":"FL","ShipmentZipCode":"33065","ShipmentTax":0.0,"ShipmentWeight":1.0,"ShipmentTrackingCode":"","ShipmentUserID":"","ShipmentNumber":1,"ShipmentAddressTypeID":0}],"OrderItemList":[{"CatalogID":3,"ItemIndexID":1,"ItemID":"1003K","ItemShipmentID":0,"ItemQuantity":1.0,"ItemWarehouseID":0,"ItemDescription":"Tote Bag
Color: Khaki","ItemUnitPrice":1.0,"ItemWeight":3.0,"ItemOptionPrice":0.0,"ItemAdditionalField1":"","ItemAdditionalField2":"","ItemAdditionalField3":"","ItemPageAdded":"Tote-Bag_p_3.html","ItemDateAdded":"2009-06-22T12:05:07","ItemUnitCost":0.0,"ItemUnitStock":5.0,"ItemOptions":",1","ItemCatalogIDOptions":"","ItemSerial":"","ItemImage1":"http://71745179439.3dcart.net/assets/images/default/handbag.jpg","ItemImage2":"http://71745179439.3dcart.net/assets/images/default/handbag.jpg","ItemImage3":"http://71745179439.3dcart.net/assets/images/default/handbag.jpg","ItemImage4":"http://71745179439.3dcart.net/assets/images/default/handbag.jpg","ItemWarehouseLocation":"","ItemWarehouseBin":"","ItemWarehouseAisle":"","ItemWarehouseCustom":""}],"PromotionList":[],"OrderDiscount":0.0,"SalesTax":0.0,"SalesTax2":0.0,"SalesTax3":0.0,"OrderAmount":1.0,"AffiliateCommission":0.0,"TransactionList":[],"CardType":"","CardNumber":"","CardName":"John Doe","CardExpirationMonth":"","CardExpirationYear":"","CardIssueNumber":"","CardStartMonth":"","CardStartYear":"","CardAddress":"","CardVerification":"","RewardPoints":"1","QuestionList":[],"Referer":"http://www.google.com","IP":"","CustomerComments":"Sample Order from 3dcart","InternalComments":"","ExternalComments":""}]
You can use json_decode php function : http://php.net/manual/fr/function.json-decode.php
On your code :
<?php
$host = 'https://apirest.3dcart.com';
$version = 1;
$service = 'Orders';
$secureUrl = 'https://xxxxyyyyy.3dcart.net'; // Secure URL is set in Settings->General->StoreSettings
$privateKey = 'xxxxxxxxxxxxxxxx'; // Private key is obtained when registering your app at http://devportal.3dcart.com
$token = 'xxxxxxxxxxxxx'; // The token is generated when a customer authorizes your app
// initialize cURL session
$ch = curl_init($host . '/3dCartWebAPI/v' . $version . '/' . $service);
// set headers
$httpHeader = array(
'Content-Type: application/json;charset=UTF-8',
'Accept: application/json',
'SecureUrl: ' . $secureUrl,
'PrivateKey: ' . $privateKey,
'Token: ' . $token,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
// [ ... addtional cURL options as needed ... ]
$response = curl_exec($ch);
if ($response === false) {
$response = curl_error($ch);
}
curl_close($ch);
$arrayResponse = json_decode($response, true);
//Do something with your array
Introduction
I don't know what is the structure of the csv file you want to output. You should provide it in your question if you want a better quality answer. Keep in mind though, that you are using 2 different data structures :
JSON is a tree
CSV is a table
So having nested arrays in your json will make this work harder.
Step 1
Check if your json string is valid: json validator
As you will see, the json string response you provided is not.
For the rest of my answer i will consider this part of your response which i made valid :
$string = '
[{
"InvoiceNumberPrefix": "AB-",
"InvoiceNumber": 1000,
"OrderID": 1,
"CustomerID": 1,
"OrderDate": "2014-01-10T12:44:37",
"OrderStatusID": 1,
"LastUpdate": "0001-01-01T00:00:00",
"UserID": "",
"SalesPerson": "",
"ContinueURL": "http://71745179439.3dcart.net/continue_order.asp?orderkey=tl31S22wts7B0hF1",
"BillingFirstName": "John",
"BillingLastName": "Doe",
"BillingCompany": "",
"BillingAddress": "123 Street",
"BillingAddress2": "",
"BillingCity": "Coral Springs",
"BillingState": "FL",
"BillingZipCode": "33065",
"BillingCountry": "US",
"BillingPhoneNumber": "800-828-6650",
"BillingEmail": "test#3dcart.com",
"BillingPaymentMethod": "Online Credit Card",
"BillingOnLinePayment": true,
"BillingPaymentMethodID": "1",
"ShipmentList": [{
"ShipmentID": 0,
"ShipmentLastUpdate": "0001-01-01T00:00:00",
"ShipmentBoxes": 1,
"ShipmentInternalComment": "Sample Order from 3dcart",
"ShipmentOrderStatus": 1,
"ShipmentAddress": "123 Street",
"ShipmentAddress2": "",
"ShipmentAlias": "",
"ShipmentCity": "Coral Springs",
"ShipmentCompany": "",
"ShipmentCost": 0.0,
"ShipmentCountry": "US",
"ShipmentEmail": "",
"ShipmentFirstName": "Test",
"ShipmentLastName": "Test",
"ShipmentMethodID": 0,
"ShipmentMethodName": "Free Shipping",
"ShipmentShippedDate": "",
"ShipmentPhone": "800-828-6650",
"ShipmentState": "FL",
"ShipmentZipCode": "33065",
"ShipmentTax": 0.0,
"ShipmentWeight": 1.0,
"ShipmentTrackingCode": "",
"ShipmentUserID": "",
"ShipmentNumber": 1,
"ShipmentAddressTypeID": 0
}],
"OrderItemList": [{
"CatalogID": 3,
"ItemIndexID": 1,
"ItemID": "1003K",
"ItemShipmentID": 0,
"ItemQuantity": 1.0,
"ItemWarehouseID": 0
}]
}]';
Step 2
Use json_decode() to convert your json to an array this way : The 1st parameter is your json string and the 2nd is a boolean that when set to true will return an associative array. (manual: json_decode)
$array = json_decode($string, true);
Step 3
Create your csv file this way :
$f = fopen('output.csv', 'w');
foreach ($array as $row) {
$result = [];
array_walk_recursive($row, function($item) use (&$result) {
$result[] = $item;
});
fputcsv($f, $result);
}
Of course my answer is based on the json string provided in step 1 !
thanks, all I have to find a solution write curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); then the return value from curl_exec will be the actual result from the successful operation and set false display it only browser
My curl exec response returns this:
string(151937) "HTTP/1.1 200 OK Access-Control-Allow-Headers: Content-Type, Accept-Tenant, Authorization Access-Control-Allow-Methods: POST,GET,PUT,PATCH,OPTIONS Access-Control-Allow-Origin: * Cache-Control: private Content-Type: application/json; charset=utf-8 Date: Mon, 28 Sep 2015 08:35:33 GMT Server: Microsoft-IIS/7.5 Warning: Unsupported Authentication Scheme X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 151475 Connection: keep-alive {"ShortResultText":"SE19","Restaurants":[{"Id":50371,"Name":"Mahjestics Caribbean Cuisine","Address":"247 Gypsy Road","Postcode":"SE27 9QY","City":"London","CuisineTypes":[{"Id":76,"Name":"Caribbean","SeoName":null},{"Id":97,"Name":"African","SeoName":null}],"Url":"http://majestic-caribbean-cuisine-west-norwood.just- ...
But the JSON starts here at "{ ShortResultText"..:
{
"ShortResultText": "SE19",
"Restaurants": [
{
"Id": 50371,
"Name": "Mahjestics Caribbean Cuisine",
"Address": "247 Gypsy Road",
"Postcode": "SE27 9QY",
"City": "London",
"CuisineTypes": [
{
"Id": 76,
"Name": "Caribbean",
"SeoName": null
},
{
"Id": 97,
"Name": "African",
"SeoName": null
}
"Url": "http://majestic-caribbean-cuisine-west-norwood.test.co.uk",
"IsOpenNow": true,
"IsSponsored": false,
"IsNew": false,
"IsTemporarilyOffline": false,
"ReasonWhyTemporarilyOffline": "",
"UniqueName": "majestic-caribbean-cuisine-west-norwood",
"IsCloseBy": false,
"IsHalal": true,
"DefaultDisplayRank": 1,
"IsOpenNowForDelivery": true,
"IsOpenNowForCollection": true,
"RatingStars": 4.71,
"Logo": [
{
"StandardResolutionURL": "http://d30v2pzvrfyzpo.cloudfront.net/uk/images/restaurants/50371.gif"
}
],
"Deals": [],
"NumberOfRatings": 7
I need to get JUST the JSON data from my curl response and I'm not sure the best way to go about it? The curl response header might vary in length depending on the "ShortResultText" value from POST as this is a variable.
Then I'll be able to get the data in an array and loop through it.
Curl code:
$url = "http://api-interview.test.com/restaurants?q=se19";
$ch = curl_init();
$api_headers = array(
'Content-Type: text/plain; charset=utf-8',
'Accept-Tenant: uk',
'Accept-Language: en-GB',
'Authorization: Basic VGVjaFRlc3RBUEk6dXNlcjI=',
'Host: api-interview.test.com'
);
//print_r($api_headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $api_headers);
// echo "<pre>";
// $data = curl_exec($ch);
// echo "</pre>";
echo "<pre>";
$data = curl_exec($ch);
echo "</pre>";
//just testing here
// $json = json_encode($data, true);
// $json1 = json_decode($json, true);
// var_dump($json1);
//print $json1['restaurants'];
//$json = json_encode($data, true);
// foreach($json['restaurants'] as $value) {
// echo $value->postcode;
// }
curl_close($ch);
You only have to set CURLOPT_HEADER to false.
Try this:
$json1 = json_decode($json, true);
foreach($json1['Restaurants'] as $key => $val){
print_r($val); // You will get here the ID, Name ....
echo 'ID: ' $val['Id'] . 'Name: ' . $val['Name']; . 'Rating Stars: ' . $val['RatingStars']..
//If you want to go deeper and get the CuisineTypes just do below
foreach($val['CuisineTypes'] as $key2 => $val2) {
print_r($val2); //This is the cuisine types
}
}
Or you can just manipulate your array:
$newData = [];
foreach($json1['Restaurants'] as $key => $val)
{
$newData[] = ['Name' => $val['Name'], 'CusineTypes' => $val['CuisineTypes'], 'RatingStars' => $val['RatingStars']];
}
print_r($newData);
I am trying to add an excel file (.xlsx) as an attachment to the email I am sending out through the Mandrill API. I am using CURL in a php file to send the email. The excel file is named Report.xlsx.
Here is a link to Mandrill API to use CURL.
Here is a link an other question going over adding file paths.
I receive the following error message:
PHP Parse error: syntax error, unexpected 'path' (T_STRING) in
/var/www/html/newFolder/EmailAlertSystem/mailchimp-mandrill-api-php/UsageReport.php
(****Which is my directory of my code)
This is my php code to send out the email via Mandrill:
$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';
$api_key = 'APIKEY';
$content = 'all the content I want to add';
$content_text = strip_tags($content);
$from = 'FROM';
$fromName = 'FROMNAME';
$to = 'TO';
$toName = 'TONAME';
$subject = 'SUBJECT';
$fullName = "FIRSTNAME LASTNAME";
$attachment = file_get_contents('Report.xlsx');
$attachment_encoded = base64_encode($attachment);
$postString = '{
"key": "' . $api_key . '",
"message": {
"html": "' . $content . '",
"text": "' . $content_text . '",
"subject": "' . $subject . '",
"from_email": "' . $from . '",
"from_name": "' . $fromName . '",
"to": [
{
"email": "' . $to . '",
"name": "' . $fullName . '"
}
],
"track_opens": true,
"track_clicks": true,
"auto_text": true,
"url_strip_qs": true,
"preserve_recipients": true,
"attachments" : array(
array(
'path' => $attachment_encoded,
'type' => "application/xlsx",
'name' => 'Report.xlsx',
)
)
},
"async": false
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
//this is the executable curl statement that will actually send the email
$result = curl_exec($ch);
Any help would be greatly appreciated!!! Please let me know if I was unclear and what I am doing wrong. Thank you in advance!
The error seems to refer to this part
"attachments" : array(
array(
'path' => $attachment_encoded,
'type' => "application/xlsx",
'name' => 'Report.xlsx',
)
)
Right there, the string is terminated before path and then restarted, its a syntax error.
Something like,
"attachments" : array(
array(
\'path\' => $attachment_encoded,
\'type\' => "application/xlsx",
\'name\' => \'Report.xlsx\',
)
)
i.e. having the quotes escaped should fix it, but... the rest of that string looks like JSON. Is the attachments portion supposed to be in PHP-like array format? Might want to double-check.
I'm a little confused on how to set up a cURL request to an API I'm working with. To be specific, it's for a fulfillment center called ShipStation (http://api.shipstation.com). I've done many cURL requests in the past but now I'm trying to figure out how to set up a 'MERGE' cURL request as opposed to a 'GET' cURL request, etc. You can see on here the 'GET' header to pull info from the API:
http://api.shipstation.com/Order-Resource.ashx#Reading_an_Order_5
And then to update/merge data:
http://api.shipstation.com/Order-Resource.ashx#Updating_an_Order_6
Every time I try to send a request though, I get curl_setopt(): supplied argument is not a valid cURL handle resource errors on several lines. I tried initially by copying the data and trying to send it as a header:
$header .= "GET https://data.shipstation.com/1.3/Orders(128714) HTTP/1.1";
$header .= "User-Agent: Microsoft ADO.NET Data Services";
$header .= "Accept-Charset: UTF-8";
$header .= "DataServiceVersion: 1.0;NetFx";
$header .= "MaxDataServiceVersion: 2.0;NetFx";
$header .= "Accept: application/atom+xml,application/xml";
$header .= "Host: data.shipstation.com";
//Send request
$curlConn = curl_init();
curl_setopt($curlConn,CURLOPT_USERPWD,'myusername:mypassword');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
curl_setopt($curlConn,CURLOPT_RETURNTRANSFER,1);
$ret = curl_exec($curlConn);
curl_close($curlConn);
I do update the username and password to my credentials since you need that to log into this API. I basically copied the header as it was and it doesn't work. I also updated 'CURLOPT_CUSTOMREQUEST' to 'CURLOPT_HTTPHEADER' but both gave errors.
I'm not understanding where I'm going wrong and I also don't know how (if it's possible) to return more detailed error messages so I can get to the bottom of the problem with the code since I just get the supplied argument error.
Thanks for your help!
EDIT
Perhaps I'm approaching this wrong? How would I send a 'MERGE' request as evidenced in the documentation in the links above. I don't know how to take that info that they've given (the header info) and translate it into a request to the API.
Try in this way:
$end = "\r\n";
$header .= "GET https://data.shipstation.com/1.3/Orders(128714) HTTP/1.1" . $end;
$header .= "User-Agent: Microsoft ADO.NET Data Services" . $end;
$header .= "Accept-Charset: UTF-8" . $end;
$header .= "DataServiceVersion: 1.0;NetFx" . $end;
$header .= "MaxDataServiceVersion: 2.0;NetFx" . $end;
$header .= "Accept: application/atom+xml,application/xml" . $end;
$header .= "Host: data.shipstation.com" . $end;
//Send request
$curlConn = curl_init();
curl_setopt($curlConn,CURLOPT_USERPWD,'myusername:mypassword');
curl_setopt($curlConn, CURLOPT_CUSTOMREQUEST, $header);
curl_setopt($curlConn,CURLOPT_RETURNTRANSFER,1);
$ret = curl_exec($curlConn);
curl_close($curlConn);
Please try this:
$username = "YOUR API KEY";
$password = "YOUR API SECRET";
$endpoint = "https://ssapi.shipstation.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPHEADER, array ("
Content-Type: application/json"
));
create_order($ch, $endpoint);
function create_order($ch, $endpoint) {
curl_setopt($ch, CURLOPT_URL, $endpoint . "/orders/createorder");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"orderNumber\": \"ABC124\",
\"orderKey\": \"0f6aec18-3e89-4771-83aa-f392d84f4c74\",
\"orderDate\": \"2015-01-31T17:46:27.0000000\",
\"paymentDate\": \"2015-01-31T17:46:27.0000000\",
\"orderStatus\": \"awaiting_shipment\",
\"customerUsername\": \"headhoncho#whitehouse.gov\",
\"customerEmail\": \"headhoncho#whitehouse.gov\",
\"billTo\": {
\"name\": \"The President\",
\"company\": \"US Govt\",
\"street1\": \"1600 Pennsylvania Ave\",
\"street2\": \"Oval Office\",
\"street3\": null,
\"city\": \"Washington\",
\"state\": \"DC\",
\"postalCode\": \"20500\",
\"country\": \"US\",
\"phone\": null,
\"residential\": true
},
\"shipTo\": {
\"name\": \"The President\",
\"company\": \"US Govt\",
\"street1\": \"1600 Pennsylvania Ave\",
\"street2\": \"Oval Office\",
\"street3\": null,
\"city\": \"Washington\",
\"state\": \"DC\",
\"postalCode\": \"20500\",
\"country\": \"US\",
\"phone\": null,
\"residential\": true
},
\"items\": [
{
\"lineItemKey\": null,
\"sku\": \"ABC123\",
\"name\": \"Test item #1\",
\"imageUrl\": null,
\"weight\": {
\"value\": 24,
\"units\": \"ounces\"
},
\"quantity\": 2,
\"unitPrice\": 99.99,
\"warehouseLocation\": \"Aisle 1, Bin 7\",
\"options\": []
},
{
\"lineItemKey\": null,
\"sku\": \"DEF456\",
\"name\": \"Test item #2\",
\"imageUrl\": null,
\"weight\": {
\"value\": 0.01,
\"units\": \"ounces\"
},
\"quantity\": 3,
\"unitPrice\": 1.25,
\"warehouseLocation\": \"Aisle 7, Bin 34\",
\"options\": []
}
],
\"amountPaid\": 218.73,
\"taxAmount\": 5,
\"shippingAmount\": 10,
\"customerNotes\": null,
\"internalNotes\": \"This order was created via the ShipStation API\",
\"gift\": false,
\"giftMessage\": null,
\"requestedShippingService\": \"Priority Mail\",
\"paymentMethod\": null,
\"carrierCode\": \"fedex\",
\"serviceCode\": \"fedex_2day\",
\"packageCode\": \"package\",
\"confirmation\": \"delivery\",
\"shipDate\": \"2014-04-08\",
\"weight\": {
\"value\": 0,
\"units\": \"ounces\"
},
\"dimensions\": {
\"units\": \"inches\",
\"length\": 7,
\"width\": 5,
\"height\": 6
},
\"insuranceOptions\": {
\"provider\": null,
\"insureShipment\": false,
\"insuredValue\": 0
},
\"internationalOptions\": {
\"contents\": null,
\"customsItems\": null
},
\"advancedOptions\": {
\"warehouseId\": 34369,
\"nonMachinable\": false,
\"saturdayDelivery\": false,
\"containsAlcohol\": false,
\"storeId\": 42756,
\"customField1\": \"Some custom data\",
\"customField2\": null,
\"customField3\": null,
\"source\": null
}
}");
$response = curl_exec($ch);
curl_close($ch);
print_r($response);
}