API JSON output Format - php

I have this code
<?php
$id = $_POST['id'];
$nume = $_POST['nume'];
$rrp = $_POST['rrp'];
$pret = $_POST['pret'];
$stoc = $_POST['stoc'];
$url = $_POST['url'];
$url1 = $_POST['url1'];
$url2 = $_POST['url2'];
$url3 = $_POST['url3'];
$username = "xx#xx.eu";
$password = "aaa";
$apiUrl = "https://partners.services.aaaa.eu/v1/mkpApi/product/save";
$auth = base64_encode($username . ":" . $password);
$headers = [
"Authorization: Basic " . $auth,
"Content-Type: application/x-www-form-urlencoded",
];
$payload[] = [
"id" => $id,
"locale" => "RO",
"hidden" => 0,
"currency" => "RON",
"brand" => "Decorepublic",
"name" => $nume,
"category_id" => 10008,
"status" => "1",
"vat" => "0",
"stock" => [[
"warehouse_id" => 1,
"value" => $stoc,
]],
"sale_price" => $pret,
"rrp" => $rrp,
"description" => $nume,
"images" => [
["url" => $url],
["url" => $url1],
["url" => $url2],
["url" => $url3],
],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(["data" => json_encode($payload)]));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$response = json_decode($result, true);
print_r($response);
//echo '<br><br>';
echo json_encode($payload);
print $stoc;
?>
At output i have
status":"1","vat":"0","stock":[{"warehouse_id":1,"value":"200"}]
I need to have value without "" like this:
status":"1","vat":"0","stock":[{"warehouse_id":1,"value":200}],"
I trie to use print $stoc, but it returns value 1.
I tried get function but it doesn't work. Any idea?

If you've got a string in $stoc and you need to convert it to an integer before you encode it as JSON, then you can use intval.
"value" => intval($stoc)
Demo: http://sandbox.onlinephpfunctions.com/code/8b1ed16c28bfbc47f501981f2bf03f7b1bb9ce45

Related

add new product in shopify via php curl

if(isset($_POST['add_shopify']))
{
$title = $_POST['title'];
$body = $_POST['body_html'];
$vendor = $_POST['vendor'];
$type = $_POST['product_type'];
$price = $_POST['price'];
$images = $_POST['images'];
$product = array(
'title'=> $title,
'body_html' => $body,
'vendor'=> $vendor,
'product_type'=> $type,
"variants"=>[[
"price"=> $price
]],
"images" => [
[
"src"=> $images
]
]
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL," https://9e54fc.myshopify.com/admin/api/2022-10/products.json?access_token=*********************" );
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTPHEADER,array(
'Content-Type' => 'application/json',
));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($product));
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
}
curl_close($curl);
if (isset($error_msg)) {
echo $error_msg;
}
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
print_r(json_decode($resp));
when i run this code it's return true. but when i am checking admin panel there are no product showing of that name. this code is working properly in postman api. please tell me about it what's wrong with it?
You are missing the "product" key in the $product array, please check the below code that there is a "product" key, and inside that, all the product details are there. You have to pass the data in JSON format, but you are using http_build_query, which Shopify doesn't accept with application/json header, so please use the below code to create a product via PHP curl.
<?php
$productData = [
"product" => [
"title" => "Burton Custom Freestyle 151",
"body_html" => "<strong>Good snowboard!</strong>",
"vendor" => "Burton",
"product_type" => "Snowboard",
"variants" => [
[
"option1" => "Blue",
"option2" => "155"
],
[
"option1" => "Black",
"option2" => "159"
]
],
"options" => [
[
"name" => "Color",
"values" => [
"Blue",
"Black"
]
],
[
"name" => "Size",
"values" => [
"155",
"159"
]
]
]
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://your-development-store.myshopify.com/admin/api/2022-10/products.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Shopify-Access-Token' => '{access_token}',
'Content-Type' => 'application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($productData));
$response = curl_exec($ch);
curl_close($ch);

Convert data to json format with multiple arrays

Long story short, i have the following code which is gettin info about an order from api in json, and should send this order to another system through api. All steps works good, but my problem it's if i have more products on order, my script it's creating a new order for each one.
SCRIPT:
foreach($data['orders'] as $key => $val)
{
$phone = $val['phone'];
$email = $val['email'];
$fullname = $val['invoice_fullname'];
$invoicecompany = $val['invoice_company'];
$invoicenip = $val['invoice_nip'];
$invoiceaddress = $val['invoice_address'];
$invoicecity = $val['invoice_city'];
$deliveryprice = $val['delivery_price'];
$deliverymethod = $val['delivery_method'];
}
foreach($data['orders'][0]['products'] as $key => $val){
$pidBl = $val['product_id'];
$ean = $val['ean'];
$grossprice = $val['price_brutto'];
$vatrate = $val['tax_rate'];
$quantity = $val['quantity'];
//open db
$dbc = mysqli_connect ($dbhost, $dbuser, $dbpassword);
$dbSelected = mysqli_select_db($dbc , $database);
$q = $dbc->query("SELECT pId FROM offers WHERE pBarcode = '$ean';");
while ($rs = $q->fetch_assoc()) {
$pId = $rs['pId'];
}
$arr = [
"objects" => [],
"returnColumns" => []
];
$arr['objects'][] = [
"name" => $fullname,
"uniqueCode" => $invoicenip,
"active" => "true"
];
$arr['returnColumns'][] = ["name" => "id"];
$preparesedona = json_encode($arr);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'BLABLABLA',
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 => $preparesedona,
CURLOPT_HTTPHEADER => array(
'accept: application/json',
'Authorization: Basic BLABLABLA',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response, true);
foreach($data['result'] as $key => $val){
$customerId = $val['id'];
}
$arr = [
"objects" => [],
"returnColumns" => []
];
$arr['objects'][] = [
"client_id" => $customerId,
"user_id" => 1,
"administration_id" => 1,
"status" => 1,
"deliveryType" => 1,
"details" => []
];
$arr['objects'][0]['details'][] = [
"product_id" => $pId,
"unitPriceWithVat" => $grossprice,
"orderedUnits" => $quantity
];
$arr['returnColumns'][] = ["name" => "id"];
$preparesedona = json_encode($arr);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'BLABLABLA',
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 => $preparesedona,
CURLOPT_HTTPHEADER => array(
'accept: application/json',
'Authorization: Basic BLABLABLA',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
Yas, i know that somewhere it's a small thing which is making difference, but trust me, i tried in any possible way, i tried to look on similar errors and problems but i cannot find anything related cause i have multiple arrays which should be defined and filled...
This is how it looks my postfields
{
"objects":[
{
"client_id":21947,
"user_id":1,
"administration_id":1,
"status":1,
"deliveryType":1,
"details":[
{
"product_id":"11407",
"unitPriceWithVat":159.7,
"orderedUnits":1
}
]
}
],
"returnColumns":[
{
"name":"id"
}
]
}{
"objects":[
{
"client_id":21948,
"user_id":1,
"administration_id":1,
"status":1,
"deliveryType":1,
"details":[
{
"product_id":"14575",
"unitPriceWithVat":45.31,
"orderedUnits":1
}
]
}
],
"returnColumns":[
{
"name":"id"
}
]
}
This is how should look like:
{
"objects":[
{
"client_id":21947,
"user_id":1,
"administration_id":1,
"status":1,
"deliveryType":1,
"details":[
{
"product_id":"11407",
"unitPriceWithVat":159.7,
"orderedUnits":1
},
{
"product_id":"14575",
"unitPriceWithVat":45.31,
"orderedUnits":1
}
]
}
],
"returnColumns":[
{
"name":"id"
}
]
}
I would much appreciate your help and please, be sympathetic, i'm not a pro, i just try to learn and i promise that i do my best :)
this works for me, baiscally, i make one call to API1 to get general info about order and creating customer in API2 // after that i made another call to API1 to get info about products and this is how i structured my script and it's workin very well.
// gettin info about order data
foreach($data['orders'] as $key => $val)
{
$phone = $val['phone'];
$email = $val['email'];
$fullname = $val['invoice_fullname'];
$invoicecompany = $val['invoice_company'];
$invoicenip = $val['invoice_nip'];
$invoiceaddress = $val['invoice_address'];
$invoicecity = $val['invoice_city'];
$deliveryprice = $val['delivery_price'];
$deliverymethod = $val['delivery_method'];
$deliveryaddress = $val ['delivery_address'];
// CREATE CUSTOMER -------------------------
$arr = [
"objects" => [],
"returnColumns" => []
];
$arr['objects'][] = [
"name" => $fullname,
"uniqueCode" => $invoicenip,
"active" => "true"
];
$arr['returnColumns'][] = ["name" => "id"];
$preparesedona = json_encode($arr);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'BLABLABLABLA',
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 => $preparesedona,
CURLOPT_HTTPHEADER => array(
'accept: application/json',
'Authorization: Basic BLABLABLABLA',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response, true);
$customerId = $data['result'][0]['id'];
}
// Call again to get data for products
$methodParams = [
'order_id' => $orderidbl
];
$apiParams = [
'method' => 'getOrders',
'parameters' => json_encode($methodParams),
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'BLABLABLABLABLABLABLABLA');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-BLToken: BLABLABLABLA-BLABLABLABLA-BLABLABLABLA"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$output = curl_exec($ch);
curl_close($ch);
$data = json_decode($output, true);
$arr = [
"objects" => [],
"returnColumns" => []
];
$arr['objects'][] = [
"client_id" => $customerId,
"user_id" => 1,
"administration_id" => 1,
"status" => 1,
"deliveryType" => 1,
"deliveryAddress" => $deliveryaddress,
"details" => []
];
$arr['returnColumns'][] = ["name" => "id"];
// prepare products area "details"
foreach($data['orders'][0]['products'] as $key => $val){
$pidBl = $val['product_id'];
$ean = $val['ean'];
$grossprice = $val['price_brutto'];
$vatrate = $val['tax_rate'];
$quantity = $val['quantity'];
//open db
$dbc = mysqli_connect ($dbhost, $dbuser, $dbpassword);
$dbSelected = mysqli_select_db($dbc , $database);
$q = $dbc->query("SELECT pId FROM offers WHERE pBarcode = '$ean';");
while ($rs = $q->fetch_assoc()) {
$pId = $rs['pId'];
}
$arr['objects'][0]['details'][] = [
"product_id" => $pId,
"unitPriceWithVat" => $grossprice,
"orderedUnits" => $quantity
];
}
$preparesedona = json_encode($arr);
var_dump($preparesedona);

Confused on a SecureNet response code using cURL

I have searched Google and StackOverflow about this error, and I am having trouble finding results. Perhaps there is someone out there that can point me in the right direction, as I have never worked with the SecureNet API before.
I have a working form in PHP, however when submitting it to SecureNet, I get this as a response:
{"success":false,"result":"AUTHENTICATION_ERROR","responseCode":3,"message":"SecureNetId and SecureNetKey should be passed as Basic authentication tokens or in request object.","responseDateTime":"2015-08-27T02:58:12.54Z","rawRequest":null,"rawResponse":null,"jsonRequest":null}bool(true)
Here is my code:
$url = 'https://gwapi.demo.securenet.com/api/Payments/Charge';
$data = array(
"publickey" => $apiPkey,
"amount" => $donationAmount,
"card" => array(
"number" => $cardNumber,
"cvv" => $cvv,
"expirationDate" => $expiryMonth . '/' . $expiryYear,
"address" => array(
"line1" => $address,
"city" => $city,
"state" => $state,
"zip" => $zip
),
"firstName" => "Jack",
"lastName" => "Test"
),
"extendedInformation" => array(
"typeOfGoods" => "DIGITAL"
),
"developerApplication" => array(
"developerId" => $apiID,
"version" => $apiVersion
)
);
$secureNet = http_build_query($data);
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $secureNet);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
var_dump($result);
curl_close($ch);
I figured it out, I wasn't sending the headers.
$headers = array(
"Authorization: Basic " . base64_encode($apidID . ':' . $apiSkey)
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

php how to send this data threw curl

I have to send this data threw curl:
-d '{"payer": {
"default_payment_instrument":"BANK_ACCOUNT",
"allowed_payment_instruments":["BANK_ACCOUNT"],
"default_swift":"FIOBCZPP",
"contact":{"first_name":"First",
"last_name":"Last",
"email":"first.last#example.com"
}
},
}'
How am I supposed to save those data into fields variable?
$fields = {
"payer": {
"default_payment_instrument":"BANK_ACCOUNT",
"allowed_payment_instruments":["BANK_ACCOUNT"],
"default_swift":"FIOBCZPP",
"contact":{"first_name":"First",
"last_name":"Last",
"email":"first.last#example.com"
}
},
};
$field_string = http_build_query($fields);
curl_setopt($process, CURLOPT_POSTFIELDS, $field_string);
This is GoPay right?
Do something like this:
$fields = [
"payer" => [
"default_payment_instrument" => "BANK_ACCOUNT",
"allowed_payment_instruments" => ["BANK_ACCOUNT"],
"default_swift" => "FIOBCZPP",
"contact" => [
"first_name" => "First",
"last_name" => "Last",
"email" => "first.last#example.com"
]
]
];
$json = json_encode($fields);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
Ok, posting stuff with cURL. Here you go...
<?php
$target_url = "http://domain.dev/post-acceptor.php";
$data_to_post = array(
"payer" => array(
"default_payment_instrument" => "BANK_ACCOUNT",
"allowed_payment_instruments" => "BANK_ACCOUNT",
"default_swift" => "FIOBCZPP",
"contact" => array(
"first_name" => "First",
"last_name" => "Last",
"email" => "first.last#example.com"
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target_url);
curl_setopt($curl, CURLOPT_POST, count($data_to_post));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data_to_post));
$result = curl_exec($curl);
curl_close($curl);
Notes:
you might try to turn your JSON into an PHP array by using json_decode()

Tree structure whit post request cURL and Json and http login

i'm sending a post request with PHP and cURL, the request is a json tree comand.
I have this array
$arr = array(
"lookupKey" => "Ejemplo",
"subject" => "Prueba HideBanner",
"body" => "Esto es una prueba",
"issuerName" => "Karla",
"recipient" => array(
"legalName" => "Tania",
"emailAddress" => "taniacomprador#outlook.com",),
"options" => array("certificationlevel" => "Standard") );
The output of
echo json_encode($arr);
is
{"lookupKey":"Ejemplo","subject":"Prueba HideBanner","body":"Esto es una prueba","issuerName":"Karla","recipient":"legalName":"Tania","emailAddress":"taniacomprador#outlook.com"},"options":{"certificationlevel":"Standard"}}
this is the command I need
but when i run the cURL request with the comand, the server returns
{"responseStatus":{"errorCode":"SerializationException","message":"Error deserializing FormData: lookupKey=Ejemplo&subject=Prueba HideBanner&body=Esto es una prueba&issuerName=Karla&recipient=Array&options=Array"}}
recipent= Array
options= Array
This is the function
function sendPostData($url, $post){
$username = "user";
$password = "pass";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$curlResult = curl_exec($ch);
//errors check
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch) . '<br>';
}
else
{
echo 'Operation completed without any errors <br>';
}
curl_close($ch);
return $curlResult;
}
Call to the function
$arr = array(
"lookupKey" => "Ejemplo",
"subject" => "Prueba HideBanner",
"body" => "Esto es una prueba",
"issuerName" => "Karla",
"recipient" => array(
"legalName" => "Tania",
"emailAddress" => "taniacomprador#outlook.com",
)
,"options" => array("certificationlevel" => "Standard") );
$output_assembly->JSON->Data = $arr;
echo json_encode($arr);
$str_data= $arr;
$url_send ="url";
echo " " . sendPostData($url_send, $str_data);
UPDATE
Is working
function sendPostData(){
$username = "user";
$password = "pass";
$post = array(
"lookupKey" => "Ejemplo",
"subject" => "Prueba test EviMail",
"body" => " mensage",
"issuerName" => "demos",
"recipient" => array(
"legalName" => "emailPeticion",
"emailAddress" => "mail",
)
,"options" => array("certificationlevel" => "Standard") );
$url="url";
//init curl sesion --------------------------------------
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_SSL_VERIFYPEER => TRUE,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CAINFO => getcwd() . '/wp-content/plugins/funciones-evicertia/CAcerts/ecertia.crt',
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_USERPWD => $username . ":" . $password,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($post)
));
$curlResult = curl_exec($ch);
curl_close($ch);
//finish curl sesion --------------------------------------
return $curlResult;
}

Categories