系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》
本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。
Magento 2有两种类型的API:公共API和Web API。公共API提供了一组用于开发Magento 2扩展的PHP接口。而Web API则允许外部应用程序与Magento 2进行通信。
公共API
公共API是Magento 2的一组PHP接口,允许开发人员访问Magento 2的内部功能和数据。这些接口使用Magento\Framework\Api接口进行定义。下面是一个简单的示例代码,演示如何使用Magento 2的公共API获取产品数据:
<?php
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Api\ProductRepositoryInterface;
class Product
{
protected $productRepository;
protected $searchCriteriaBuilder;
public function __construct(
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
public function getProductById($productId)
{
$searchCriteria = $this->searchCriteriaBuilder->addFilter('entity_id', $productId)->create();
$product = $this->productRepository->getList($searchCriteria)->getFirstItem();
return $product;
}
}Web API
Web API允许外部应用程序与Magento 2进行通信。这些API使用REST或SOAP协议,通过HTTP请求和响应进行通信。Web API中的所有请求和响应都是XML或JSON格式的。下面是一个简单的示例代码,演示如何使用Magento 2的Web API创建一个产品:
<?php
$token = 'YOUR_API_TOKEN';
$url = 'http://magento2.local/rest/V1/products';
$productData = [
'product' => [
'sku' => 'test-product',
'name' => 'Test Product',
'price' => 10.00,
'status' => 1,
'visibility' => 4,
'type_id' => 'simple',
'attribute_set_id' => 4,
'weight' => 1
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($productData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer '.$token
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$productId = json_decode($response, true)['id'];
}在上面的示例中,我们使用cURL库向Magento 2的Web API发送一个创建产品的请求。请求中包含了产品的名称、价格、SKU等信息。请求中还包含了一个授权令牌,用于验证请求的身份。如果请求成功,我们将能够从响应中获取新创建产品的ID。