Magento 2支持REST(具象状态传输)和SOAP(简单对象访问协议),很像我们以前使用的Magento的旧版本。官方文档主要基于raw curl请求,没有特定语言的示例。我们所做的就是PHP,也会有很多人使用它,所以我们试着给你们一些真正的PHP例子,告诉你们如何连接和使用Magento 2 API。
在Magento中有三种可以访问API的用户类型:
1)Guest user
他们可以访问具有匿名权限的资源。
2)Administrator/Integration
他们可以访问由配置授权的资源。
3)Customer
他们可以通过自我或匿名权限访问资源。
我们可以使用三种类型的身份验证:
1)Token-based authentication
这里的想法是在初始连接期间提供用户名和密码,并接收用于后续请求的令牌,直到令牌过期。
以下是通过PHP使用rest API的示例
<?php
$userData = array("username" => "magease", "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);
如果我们运行这段代码,我们会得到这样的响应:
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}"
这是另一个通过PHP使用SOAP API的例子
<?php
$request = new SoapClient("http://magento.m2/index.php/soap/?wsdl&services=integrationAdminTokenServiceV1", array("soap_version" => SOAP_1_2));
$token = $request->integrationAdminTokenServiceV1CreateAdminAccessToken(array("username"=>"magease", "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();
这返回给我们以下响应:
<?php
array(1) {
[0]=>
string(196) "DirectoryCurrencyInformationAcquirerV1GetCurrencyInfoResponse directoryCurrencyInformationAcquirerV1GetCurrencyInfo(DirectoryCurrencyInformationAcquirerV1GetCurrencyInfoRequest $messageParameters)"
}
2)Session-based authentication
基于会话的身份验证似乎是这三者中最简单的。
简而言之,Magento API框架使用您的会话来授权访问所请求的资源。
例如,创建前端用户,登录并将浏览器指向此页面:http://magento.m2/rest/V1/customers/me
你将得到这样的结果:
<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@magease.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>
作为客户,您将被授权以自己的匿名权限访问资源。但是,如果您尝试访问管理员帐户具有权限的资源,它也适用于管理员帐户。
3)OAuth-based authentication
可以通过OAuth 1.0a(https://en.wikipedia.org/wiki/OAuth)访问API 。
这种情况下,是将Magento API视为一种服务,允许通过资源所有者的批准向第三方访问资源。
例如,从第三方应用程序(客户端)获取Magento API(服务)的客户(资源所有者)信息。
您需要做的是转到System > Integrations并添加没有“Identity link URL”和“Callback URL”的新集成。请记住在API选项卡上编辑资源访问。
然后运行此脚本:
<?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);
并期待这样的回应:
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@magease.net","firstname":"Tomas","lastname":"Novoselic","store_id":1,"website_id":1,"addresses":[],"disable_auto_group_change":0}"