<?
//Authentication rest API magento2.Please change url accordingly your url
$adminUrl='http://localhost/magento/index.php/rest/V1/integration/admin/token';
$ch = curl_init();
$data = array("username" => "", "password" => "");
$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');
$requestUrl='http://127.0.0.1/magento/index.php/rest/V1/products';
//Please note 24-MB01 is sku
$ch = curl_init();
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$post ='{
"product": {
"sku": "MY_SKU",
"name": "My Product",
"attributeSetId": "4",
"price": 20,
"status": 1,
"visibility": 4,
"typeId": "virtual",
"weight": 0,
"extensionAttributes": {
"stockItem": {
"stockId": 1,
"qty": 20,
"isInStock": true,
"isQtyDecimal": false,
"useConfigMinQty": true,
"minQty": 0,
"useConfigMinSaleQty": 0,
"minSaleQty": 0,
"useConfigMaxSaleQty": true,
"maxSaleQty": 0,
"useConfigBackorders": false,
"backorders": 0,
"useConfigNotifyStockQty": true,
"notifyStockQty": 20,
"useConfigQtyIncrements": false,
"qtyIncrements": 0,
"useConfigEnableQtyInc": false,
"enableQtyIncrements": false,
"useConfigManageStock": true,
"manageStock": true,
"lowStockDate": "string",
"isDecimalDivided": true,
"stockStatusChangedAuto": 0,
"extensionAttributes": {}
}
},
"options": [],
"tierPrices": [],
"customAttributes": [
]
},
"saveOptions": true
}';
$options = array(
CURLOPT_URL=>$toURL,
CURLOPT_HTTPHEADER=>array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post)),
CURLOPT_VERBOSE=>0,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_USERAGENT=>"Mozilla/4.0 (compatible;)",
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>$post,
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$result= json_decode($result);
print_r($result);
?>
the above code can not add product,i have try many method,still can not add product by rest api , anyone know how to add product by rest api?please help,Thanks.
the above code can not add product,i have try many method,still can not add product by rest api , anyone know how to add product by rest api?please help,Thanks.
<?
$url = domainname;
$token_url=$url."rest/V1/integration/admin/token";
$product_url=$url. "rest/V1/products";
$ch = curl_init();
$data = array("username" => username, "password" => password);
$data_string = json_encode($data);
$ch = curl_init($token_url);
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);
$adminToken= json_decode($token);
$sampleProductData = array(
'sku' => $isbn13,
'name' => $name,
'visibility' => 4,
'type_id' => 'simple',
'price' => $price,
'status' => 1,
'attribute_set_id' => 4,
'weight' => $product_weight,
'extension_attributes' => array(
"stock_item"=>array(
'qty' => $inventory_stock,'is_in_stock' => 1,'manage_stock' => 1,'use_config_manage_stock' => 1,'min_qty' => 0,'use_config_min_qty' => 1,'min_sale_qty' => 1,'use_config_min_sale_qty' => 1,'max_sale_qty ' => 10,'use_config_max_sale_qty' => 1,'is_qty_decimal' => 0,'backorders' => 0,'use_config_backorders' => 1,'notify_stock_qty' => 1,'use_config_notify_stock_qty' => 1
),
),
'custom_attributes' => array(
array( 'attribute_code' => 'category_ids', 'value' => ["43"] ),
array( 'attribute_code' => 'description', 'value' => $description ),
array( 'attribute_code' => 'short_description', 'value' => $short_description ),
array( 'attribute_code' => 'meta_title', 'value' => $meta_title),
array( 'attribute_code' => 'meta_keyword', 'value' => $meta_keyword),
array( 'attribute_code' => 'meta_description', 'value' => $meta_description),
),
);
$productData = json_encode(array('product' => $sampleProductData));
$setHaders = array('Content-Type:application/json','Authorization:Bearer '.$adminToken);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $product_url);
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $setHaders);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
This is for product upload on magento 2 thorugh rest api Description = only copy code and put code in one php file and chagne domainname to (https://--------.com/) and after you create user and roles in magento 2(https://www.youtube.com/watch?v=hMN-ZoeODlQ) and put that username in username field in this code and password also and run this code replace with all dynamic variable.(like $isbn13,$name...etc with your product detail ) see product is create or update in magento 2
$adminUrl = 'http://localhost/magento2.1.2/index.php/rest/V1/integration/admin/token/';
$ch = curl_init();
$data = array("username" => "", "password" => "");
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type=> application/json'));
$token = curl_exec($ch);
$token = json_decode($token);
use your magento admin username and password and get the token id.
Pass the $post json variable to this cURL call.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost/magento2.1.2/index.php/rest/V1/products",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer $token",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
In request URL $requestUrl='http://127.0.0.1/magento/index.php/rest/V1/products' change "products" to product and try.
Related
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);
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,
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.
$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;
}
I am trying to upload video to facebook page as page admin with the call to action:
// Post Data
$action_call_array = array('type' => 'LEARN_MORE', 'value' => array('link' => 'http://www.google.com'));
$data = [
'title' => 'Demo Title',
'description' => 'Demo Description
http://www.google.com
http://hk.yahoo.com',
'source' => new CURLFile('video/video_1mb.mp4', 'video/mp4'),
'call_to_action' => $action_call_array,
'access_token' => FACEBOOK_PAGE_TOKEN, // MUST BE INCLUDED !!!
];
// Post Url
$post_url = 'https://graph-video.facebook.com/'.FACEBOOK_PAGE_ID.'/videos';
// CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
// result
$j = json_decode($return);
$page_post_id = $j->id;
var_dump($return);
Without the call to action, it works. But after adding the call to action, it returns me the following error:
string(196) "{"error":{"type":"Exception","message":"No Call To Action Type was parseable. Please refer to the call to action api documentation","code":1373054,"is_transient":false,"fbtrace_id":"H9GksxYBdQx"}}"
Looks like the way I add the call to action is not correct. But I don't really know how to fix it.
I put the call to action into url parameter and it is working now!
// Post Data
$fb_action = 'LEARN_MORE';
$fb_action_link = 'http://www.google.com';
$action_call_array = array('type' => $fb_action, 'value' => array('link' => $fb_action_link));
$params = http_build_query(array('call_to_action' => $action_call_array));
$data = [
'title' => 'Demo Title',
'description' => 'Demo Description
http://www.google.com
http://hk.yahoo.com',
'source' => new CURLFile('video/video_1mb.mp4', 'video/mp4'),
'access_token' => FACEBOOK_PAGE_TOKEN, // MUST BE INCLUDED !!!
];
// Post Url
$post_url = 'https://graph-video.facebook.com/'.FACEBOOK_PAGE_ID.'/videos?'.urldecode($params);
// CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
// result
$j = json_decode($return);
$page_post_id = $j->id;