magento2中如何使用API

M2目前支持三种类型的API

  1. SOAP (很古老了,逐渐被淘汰)
  2. REST (最近这几年非常流行,目前的主流)
  3. GraphQL (很新,刚出来没几年,目前正当红)

关于SOAP和REST是什么意思,有什么区别,请自行百度,在这就不赘述了。
关于这三者的具体介绍和区别,直接看这篇文章就够了
https://medium.com/postman-engineering/rest-soap-graphql-gesundheit-6544053f65cf
GraphQL简单来说就是拥有SOAP和REST的所有优势,轻量级,更先进可靠。

因为GraphQL只有2.3.x版本才有,2.2.x不支持GraphQL,所以我们不讲如何调用GraphQL,只讲SOAP和REST。
关于GraphQL的介绍见
https://devdocs.magento.com/guides/v2.3/graphql/index.html

因为SOAP是历史遗留原因,M2才兼容SOAP,
M2里主要是用的REST,我们开发中只需要用REST方式调用API就行了。

我们主要讲下怎么调用M2的API

哪些用户类型能访问M2的API

我们通常理解的调用api,是指远程调用M2的api,比如其他erp或者手机端调用api。这个没问题。
除此之外,M2自己页面,比如你在M2里下单购买产品,里面的交互也是用的rest api方式来调用数据的。

有哪些验证方式

  1. Token-based authentication (基于令牌的认证)
  2. Session-based authentication (基于会话的认证)
  3. OAuth-based authentication (基于OAuth的身份验证)

1, Token-based authentication

移动应用程序使用令牌进行身份验证。
也就是远程调用M2的api时,传递用户名和密码进行验证。
我们需要在M2后台创建用户
System -> Permissions -> All Users 里创建一个用户
比如我创建了一个zou用户,User Role 为Administrators,等于说给了所有权限 能访问所有资源,当然你可以限制权限。

以SOAP方式调用

我们在其他服务器写个php脚本,比如testsoap.php:

//通过integrationAdminTokenServiceV1登录后台生成token
$request = new SoapClient("http://magento2demo.texiaoyao.cn/soap/?wsdl&services=integrationAdminTokenServiceV1", array("soap_version" => SOAP_1_2));
$token = $request->integrationAdminTokenServiceV1CreateAdminAccessToken(array("username"=>"zou", "password"=>"zou用户的密码"));
 
$opts = array(
            'http'=>array(
                'header' => 'Authorization: Bearer '.json_decode($token->result)
            )
        );
 
/*
$wsdlUrl = 'http://magento2demo.texiaoyao.cn/soap/default?wsdl&services=customerCustomerRepositoryV1';
$requestData = ['customerId' => 1];
$result = $soapClient->customerCustomerRepositoryV1getById($requestData);
*/
$wsdlUrl = 'http://magento2demo.texiaoyao.cn/soap/default?wsdl&services=directoryCurrencyInformationAcquirerV1';
 
$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, ['version' => SOAP_1_2, 'context' => $context]);
 
$soapResponse = $soapClient->__getFunctions();

var_dump($soapResponse);

执行php testsoap.php,返回的结果为:

array(1) {
  [0]=>
  string(196) "DirectoryCurrencyInformationAcquirerV1GetCurrencyInfoResponse directoryCurrencyInformationAcquirerV1GetCurrencyInfo(DirectoryCurrencyInformationAcquirerV1GetCurrencyInfoRequest $messageParameters)"
}

以REST方式调用

我们在其他服务器写个php脚本,比如testrest.php:
读取id为1的customer信息

//通过rest/V1/integration/admin/token登录后台生成token
$userData = array("username" => "zou", "password" => "zou用户的密码");
$ch = curl_init("http://magento2demo.texiaoyao.cn/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://magento2demo.texiaoyao.cn/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);

执行php testrest.php,返回的结果为:

string(641) "{"id":1,"group_id":1,"default_shipping":"1","created_at":"2018-06-11 01:09:31","updated_at":"2018-11-30 05:01:44","created_in":"Default Store View","email":"zouhongzhao@126.com","firstname":"zou","lastname":"hongzhao","store_id":1,"website_id":1,"addresses":[{"id":1,"customer_id":1,"region":{"region_code":"\u6e56\u5317","region":"\u6e56\u5317","region_id":0},"region_id":0,"country_id":"CN","street":["\u9ad8\u65b0\u5927\u9053"],"telephone":"1510232345","postcode":"430000","city":"\u6b66\u6c49","firstname":"zou","lastname":"hongzhao","default_shipping":true}],"disable_auto_group_change":0,"extension_attributes":{"is_subscribed":false}}"

2, Session-based authentication

管理员和客户使用登录凭据进行身份验证。
这个简单的说 就是用浏览器访问api。也就是前面说的

除此之外,M2自己页面,比如你在M2里下单购买产品,里面的交互也是用的rest api方式来调用数据的。

这个跟我们传统的调用api没啥关系,就不说了。

3, OAuth-based authentication

第三方应用程序使用OAuth 1.0a进行身份验证
https://en.wikipedia.org/wiki/OAuth
这个不是通过用户名和密码来访问,而是通过accessToken来访问。
他是将Magento API视为一种服务,向第三方应用程序(客户端)开放。
好比:
通过用户名和密码来访问 是个人用户,
通过accessToken来访问来访问 是企业用户。

所以 做法也不一样,需要在后台
SYSTEM -> Extensions -> Integrations 创建一个新集成

我创建了一个名为mabang的集成

API 的 Resource Access 为All,也就是说能访问所有API.
当然你可以设为Custom,限制访问某些API。
保存后记得Active。

那如何调用呢?
还是通过rest 方式来调用
我们在其他服务器写个php脚本,比如testrest.php:
调用id为2的customer信息

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;
}
 
// 填写集成生成的key和token
$consumerKey = '你的consumerKey';
$consumerSecret = '你的consumerSecret';
$accessToken = '你的accessToken';
$accessTokenSecret = '你的accessTokenSecret';
 
$method = 'GET';
$url = 'http://magento2demo.texiaoyao.cn/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);

执行php testrest.php,返回的结果为:

string(592) "{"id":2,"group_id":1,"default_shipping":"2","created_at":"2018-06-12 02:03:17","updated_at":"2018-11-30 05:02:09","created_in":"Default Store View","email":"529894459@qq.com","firstname":"529894459","lastname":"qq","store_id":1,"website_id":1,"addresses":[{"id":2,"customer_id":2,"region":{"region_code":null,"region":null,"region_id":0},"region_id":0,"country_id":"CN","street":["luoyu"],"telephone":"1513141414","postcode":"430000","city":"wuhan","firstname":"529894459","lastname":"qq","default_shipping":true}],"disable_auto_group_change":0,"extension_attributes":{"is_subscribed":false}}"

返回的都是json格式的数据。

参考

soap

soap能调用的服务名称列表 (SOAP Reference)
https://devdocs.magento.com/guides/v2.2/soap/bk-soap.html

soap官方文档
https://devdocs.magento.com/guides/v2.2/get-started/soap/soap-web-api-calls.html

rest (非常重要)

rest能调用的服务名称列表 (REST Reference)
https://devdocs.magento.com/swagger/index_22.html
https://devdocs.magento.com/guides/v2.2/rest/bk-rest.html

rest官方文档
https://devdocs.magento.com/guides/v2.2/get-started/rest_front.html

如何开发自定义的API?

见 https://bbs.mallol.cn/?thread-177.htm

常见问题

一,用soap会出现Parsing WSDL: Couldn't load from的问题
见 https://github.com/magento/magento2/issues/12299
这个官方还未解决,所以最好是用REST方式调用。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值