Magento 2 API usage with examples
Magento 2 supports REST (Representational State Transfer) and SOAP (Simple Object Access Protocol), much like the old version of Magento we were used to. Official documentation is mostly based on raw curl request without examples in some specific language. PHP is what we do and there will be many people using it as well, so we tried to give you real PHP examples of how to connect and use Magento 2 API.
There are three user types that have access to API in Magento and those are:
1) Guest user
They have access to resources with anonymous permission.
2) Administrator/Integration
They have access to resources for which are authorized by configuration.
3) Customer
They have access to resources with self or anonymus permission.
There are three types of authentication that we can use:
1) Token-based authentication
Idea here is to provide username and password during initial connection and receive the token to be used for requests that follow, until token expires.
Here is example using rest API via PHP
<?php
$userData = array(“username” => “inchoo”, “password” => “mypassword”);
$ch = curl_init(“http://magento.m2/index.php/rest/V1/integration/admin/token”);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, “POST”);
curl_setopt($ch, CUsRLOPT_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://magento.m2/index.php/rest/V1/customers/1”);
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);
var_dump($result);
If we run this code, we will get a response that looks like something like this:
string(338) “{“id”:1,”group_id”:1,”default_billing”:”0″,”default_shipping”:”0″,”created_at”:”2016-08-16 08:37:59″,”updated_at”:”2016-08-16 08:38:00″,”created_in”:”Default Store View”,”email”:”tomas.novoselic@gmail.com”,”firstname”:”Tomas”,”lastname”:”Novoseli\u0107″,”gender”:1,”store_id”:1,”website_id”:1,”addresses”:[],”disable_auto_group_change”:0}”
There is another example using SOAP API via PHP
<?php
$request = new SoapClient(“http://magento.m2/index.php/soap/?wsdl&services=integrationAdminTokenServiceV1”, array(“soap_version” => SOAP_1_2));
$token = $request->integrationAdminTokenServiceV1CreateAdminAccessToken(array(“username”=>“inchoo”, “password”=>“GN2vKgfsszz43u”));
$opts = array(
‘http’=>array(
‘header’ => ‘Authorization: Bearer ‘.json_decode($token->result)
)
);
$wsdlUrl = ‘http://magento.m2/soap/default?wsdl&services=directoryCurrencyInformationAcquirerV1’;
$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, [‘version’ => SOAP_1_2, ‘context’ => $context]);
$soapResponse = $soapClient->__getFunctions();
which gives us the following response:
<?php
array(1) {
[0]=>
string(196) “DirectoryCurrencyInformationAcquirerV1GetCurrencyInfoResponse directoryCurrencyInformationAcquirerV1GetCurrencyInfo(DirectoryCurrencyInformationAcquirerV1GetCurrencyInfoRequest $messageParameters)”
}
2) Session-based authentication
Session based authentication seems to be most simple of all three.
In short, Magento API framework uses your session in order to authorize access to the requested resource.
For example, create frontend user, log in and point your browser to this page: http://magento.m2/rest/V1/customers/me
You will get something like this as result:
<response>
<id>2</id>
<group_id>1</group_id>
<created_at>2016-08-17 08:48:00</created_at>
<updated_at>2016-08-17 09:32:42</updated_at>
<created_in>Default Store View</created_in>
<email>tomas@inchoo.net</email>
<firstname>Tomas</firstname>
<lastname>Novoselic</lastname>
<store_id>1</store_id>
<website_id>1</website_id>
<addresses/>
<disable_auto_group_change>0</disable_auto_group_change>
</response>
As a customer, you will be authorized to access resources with self and anonymous permission. However, it also works for admin accounts if you try to access resource for which your admin account has permission .
3) OAuth-based authentication
Access to API is allowed via OAuth 1.0a (https://en.wikipedia.org/wiki/OAuth).
In this case, think of Magento API as a service that allows access to resources to third party via approval gotten from resource owners.
For example, getting customer (resource owner) info from Magento API (service) from third party application (client).
This is little bit out of the scope for this article and separate article is in preparation, however there is simple example of using integration without “Identity link URL” and “Callback URL”.
What you need to do is to go to System > Integrations and add new integration without “Identity link URL” and “Callback URL”. Remember to edit resource access on API tab.
Then run this script:
<?php
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);
$data = urlEncodeAsZend(http_build_query($data, ”, ‘&’));
$data = implode(‘&’, [$method, $url, $data]);
$secret = implode(‘&’, [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac(‘sha1’, $data, $secret, true));
}
function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace(‘%7E’, ‘~’, $encoded);
return $encoded;
}
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = ‘1fuj3asjsk4w3qb3cx44ik5ue188s30s’;
$consumerSecret = ‘lcey0h5uyt26slvtws5okaiqh8ojju5d’;
$accessToken = ‘b41sqrw1cfqh598yfoygd836c4ll3cr8’;
$accessTokenSecret = ‘lywj45gighqo3knl6bv6i61n2jf6iv0a’;
$method = ‘GET’;
$url = ‘http://magento.m2/index.php/rest/V1/customers/2’;
//
$data = [
‘oauth_consumer_key’ => $consumerKey,
‘oauth_nonce’ => md5(uniqid(rand(), true)),
‘oauth_signature_method’ => ‘HMAC-SHA1’,
‘oauth_timestamp’ => time(),
‘oauth_token’ => $accessToken,
‘oauth_version’ => ‘1.0’,
];
$data[‘oauth_signature’] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => [
‘Authorization: OAuth ‘ . http_build_query($data, ”, ‘,’)
]
]);
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);
and expect something like this for response:
string(268) “{“id”:2,”group_id”:1,”created_at”:”2016-08-17 08:48:00″,”updated_at”:”2016-08-17 09:32:42″,”created_in”:”Default Store View”,”email”:”tomas@inchoo.net”,”firstname”:”Tomas”,”lastname”:”Novoselic”,”store_id”:1,”website_id”:1,”addresses”:[],”disable_auto_group_change”:0}”