Magento2; update stock by REST API - rest

I've set up a local Magento 2.1.2 environment with sample data. I'm trying to find the correct code for updating stocks through the REST api (catalogInventoryStockRegistryV1 - Put).
This is what i've got so far:
<?php
$adminUrl = 'http://www.localurl.pro/rest/V1/integration/admin/token/';
$ch = curl_init();
$data = array("username" => "admin", "password" => "66sRz97CZt7N[GdqFU");
$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token= json_decode($token);
$headers = array("Authorization: Bearer $token");
$requestUrl='http://www.localurl.pro/rest/V1/products/24-MB01/stockItems/1';
// Sample SKU
$sampleProductData = array(
"qty" => 100
);
$productData = json_encode(array('stockItem' => $sampleProductData));
// Prints: {"stockItem":{"qty":100}}
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $requestUrl);
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
This script gives the following error:
string(122) "{"message":"Server cannot understand Content-Type HTTP header media type application\/x-www-form-urlencoded","trace":null}"
I'm not sure what the message exactly means. Some help would be greatly appreciated.
Solution
Solution given by Mohan Gopal. 'Content-Type: application/json' was missing in the curl header.
<?php
$adminUrl = 'http://www.localhost.pro/rest/V1/integration/admin/token/';
$ch = curl_init();
$data = array("username" => "admin", "password" => "66sRz97CZt7N[GdqFU");
$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token= json_decode($token);
//Use above token into header
$headers = array("Authorization: Bearer $token","Content-Type: application/json");
$skus = array(
'24-MB04' => 10,
'24-MB03' => 5
);
foreach ($skus as $sku => $stock) {
$requestUrl='http://www.localurl.pro/rest/V1/products/' . $sku . '/stockItems/1';
$sampleProductData = array(
"qty" => $stock
);
$productData = json_encode(array('stockItem' => $sampleProductData));
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $requestUrl);
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
unset($productData);
unset($sampleProductData);
}

Add the content type to header and change the header from
$headers = array("Authorization: Bearer $token");
to
$headers = array("Authorization: Bearer $token","Content-Type:
application/json");
after getting the token id on line 53.

Related

Rest Api Magento 2 customer search by custom Attribute

i have created a custom attribute "customer_number" in the customer.
i want to filter using this custom attribute
$userData = array("username" => "abc", "password" => "123");
$ch = curl_init("http://example.com/api/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
$ch = curl_init("http://example.com/api/index.php/rest/V1/customers/search?searchCriteria[sortOrders][0][field]=email&searchCriteria[sortOrders][0][direction]=asc&searchCriteria[filter_groups][0][filters][0][field]=customer_number&searchCriteria[filter_groups][0][filters][0][value]=1234567890");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
No Result is Coming...
For Updating the Customer_number I used like below
$custom_attribute[] = array('attribute_code'=>'customer_number','value'=>'6666666666');
$customerData = [
'customer' => [
"id" => 2,
"email" => "xxx#gmail.com",
"firstname" => "Umar",
"lastname" => "Rafsan",
"storeId" => 1,
"websiteId" => 1,
"custom_attributes" => $custom_attribute
]
];
//Get customer info
$ch = curl_init("http://example.com/api/rest/V1/customers/me");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // Get method
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customerData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);

REST API POST /V1/salesRules

I'm getting below error while trying to create sales-rule, using Magento REST/salesRules/API.
string(2067) "{"message":"%fieldName is a required field.","parameters":{"fieldName":"rule"}
My code:-
$userData = array("username" => "admin", "password" => "admin123");
$ch = curl_init("http://test.local/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
$data = [
'name' => '40% Off on Large Orders',
'store_labels'=> [],
'description' => 'Test sales rule',
'website_ids' => [1,3],
'customer_group_ids' => [0, 1, 2, 3],
"from_date" => "2018-01-03",
'uses_per_customer' => 0,
'is_active' => true,
......
......
......
];
$ch = curl_init("http://test.local/index.php/rest/V1/salesRules");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
var_dump($result);
Please help.
Thanks,
Finally, able to successfully create a rule via salesrule API....
I was missing one line of code. Need to set the array in array 'rule'.
$ruleData['rule'] = $data; //important step...
$ch = curl_init("http://test.local/index.php/rest/V1/salesRules/");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($ruleData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
var_dump($result);
Thanks,

"Server cannot understand Content-Type HTTP" error when retrieving a token

$adminUrl='http://localhost/magento/index.php/rest/V1/integration/admin/token';
$data = array("username" => "myname", "password" => "mypassword");
$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type=> application/json',
'Content-Length=> ' . strlen($data_string))
);
$token = curl_exec($ch);
print_r($token);
I have tried the above code but cannot get a token, and return an error message instead:
({"message":"Server cannot understand Content-Type HTTP header media type application/x-www-form-urlencoded"},
How can I resolve this error?
//Authentication rest API magento2.Please change url accordingly your url
$adminUrl='http://127.0.0.1/magento2/index.php/rest/V1/integration/admin/token';
$ch = curl_init();
$data = array("username" => "wsuser", "password" => "password123");
$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token= json_decode($token);
From https://blog.i13websolution.com/magento-2-rest-api-example/
You should try this one :
curl -X POST "https://magento.host/index.php/rest/V1/integration/customer/token" \
-H "Content-Type:application/json" \
-d '{"username":"user_example", "password":"123123q"}'
for more detail http://devdocs.magento.com/guides/v2.0/get-started/authentication/gs-authentication-token.html
The following code worked for me.
//Magento admin user data
$userData = array("username" => "adminuser", "password" => "adminpassword");
$ch = curl_init("http://yourdomain.com/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Length: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
Reference: http://inchoo.net/magento-2/magento-2-api/
Please change your $adminUrl
from:
http://localhost/magento/index.php/rest/V1/integration/admin/token
to:
http://localhost/rest/V1/integration/admin/token
That will work fine.
You can use this to get admin token.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://127.0.0.1/www.yourstoreurl.com/rest/V1/integration/admin/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n \"username\": \"admin\",\r\n \"password\": \"pwd#123\"\r\n}",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json",
"postman-token: e3deae08-0436-af2d-0449-450720bb7086"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

PayPal - Invalid caller, requires client_id & secret

I'm trying to make a request to Paypal to get a new access token, but when trying a simple curl call, it's returning with this error -
"Invalid_request - Invalid caller, requires client_id & secret"
Not quite sure what's wrong with this. The client id and secret are correct and are included.
Here is what I've tried -
$clientId = "XXX";
$secret = "XXX";
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";
$method = 'POST';
$postvals = sprintf("client_id=%s&client_secret=%s&grant_type=%s&refresh_token=%s",
$clientId,
$secret,
'refresh_token',
$refreshToken);
$ch = curl_init($url);
if ($method == 'POST'){
$options = array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postvals,
);
curl_setopt_array($ch, $options);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId.":".$secret);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: application/json",
"Accept-Language: en_US",
"Content-Type: application/x-www-form-urlencoded",
'Authorization: Bearer '.$old_accessToken,
"Host: www.paypal.com",
"Connection: close"
)
);
$result = curl_exec($ch);
// Get Request and Response Headers
$requestHeaders = curl_getinfo($ch, CURLINFO_HEADER_OUT);
$responseHeaderSize = strlen($result) - curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
$responseHeaders = substr($result, 0, $responseHeaderSize);
//only use body and not header, otherwise return is NULL
$result = substr($result, $responseHeaderSize);
if(!$result || empty($result)){
echo 'Curl error or response is empty: ' . curl_error($ch);
curl_close($ch);
} else {
curl_close($ch);
$response =json_decode($result);
var_dump($response);
}
This solution worked instead -
$clientId = "XXXX";
$clientSecret = "XXXX";
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";
$method = 'POST';
$postdata = sprintf("client_id=%s&client_secret=%s&grant_type=%s&refresh_token=%s",
$clientId,
$secret,
'refresh_token',
$refreshToken);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $clientId . ":" . $clientSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
# curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
$response = curl_exec( $curl );
if (empty($response)) {
// some kind of an error happened
die(curl_error($curl));
curl_close($curl); // close cURL handler
} else {
$info = curl_getinfo($curl);
echo "Time took: " . $info['total_time']*1000 . "ms\n";
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
echo "Received error: " . $info['http_code']. "\n";
echo "Raw response:".$response."\n";
die();
}
}
// Convert the result from JSON format to a PHP array
$jsonResponse = json_decode( $response );

Facebook : Post in user wall without SDK

I use below code to post in user wall ,without SDK, it posts successfully , but its not returning the post id , please help me
<?php
$token=$_GET['token'];
$id=$_GET['id'];
$msg = "wooow thats soo possible";
$url = "https://graph.facebook.com/".$id."/feed";
$attachment = array(
'access_token' => $token,
'message' => $msg);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
curl_close ($ch);
return $result;
?>
I got solution , below code works
<?php
$token=$_GET['token'];
$id=$_GET['id'];
$url = "https://graph.facebook.com/".$id."/feed";
$ch = curl_init();
$attachment = array( 'access_token' => $token,
'message' => "cool winne"
);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result= curl_exec($ch);
curl_close ($ch);
?>