Skip to content

Instantly share code, notes, and snippets.

@jrosell
Last active July 2, 2020 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrosell/644256f7b1e6b48d3d0ead799cec5ddb to your computer and use it in GitHub Desktop.
Save jrosell/644256f7b1e6b48d3d0ead799cec5ddb to your computer and use it in GitHub Desktop.
From Magento 2 admin panel, create a new user with a new role with sales, customers and catalog permisions. Change baseURL, username and password lines 9-11. Change example order id, customer id and product sku if needed (lines 31, 38, 45). Run from cli: php magento_api.php
<?php
class Runner {
public $baseURL;
public $username;
public $password;
public $token_string;
function __construct() {
$this->baseURL = "https://domain.com/index.php";
$this->username = "magento_api";
$this->password = "whatever";
$this->token_string = null;
}
function run(){
$this->auth();
$this->print_example_order();
$this->print_example_customer();
$this->print_example_product();
}
function auth(){
$data = array("username" => $this->username, "password" => $this->password);
$response = $this->request("/rest/V1/integration/admin/token", $data);
$this->token_string = json_decode($response);
echo "\nauth()\n";
echo "token:".$this->token_string;
echo "\n";
}
function print_example_order(){
echo "\nprint_example_order()\n";
$response = $this->request("/rest/V1/orders/29229");
$order = json_decode($response);
print_r($order);
echo "\n";
}
function print_example_customer(){
echo "\nprint_example_customer()\n";
$response = $this->request("/rest/V1/customers/5389");
$customer = json_decode($response);
print_r($customer);
echo "\n";
}
function print_example_product(){
echo "\nprint_example_product()\n";
$response = $this->request("/rest/V1/products/PEZ0140");
$category = json_decode($response);
print_r($category);
echo "\n";
}
function request($requestUrl, $data = null){
$ch = curl_init($this->baseURL.$requestUrl);
if(!$this->token_string && $data != null){
$data_string = json_encode($data);
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)));
}
if($this->token_string && $data == null){
$headers = array("Authorization: Bearer ".$this->token_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
return curl_exec($ch);
}
}
$magento_api = new Runner();
$magento_api->run();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment