magento2使用wepapi,配置api示例
7天成为Magento系统架构师,现在开始学习Magento全栈开发!
《Magento2.X企业级开发实战》
本节我们以一个第三方登录模块为例,添加一个webapi
第一步:添加webapi.xml
File app\code\Weblogin\Thirdlogin\etc\webapi.xml
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/customers/weblogin/customer_info" method="POST">
<service class="Weblogin\Thirdlogin\Api\ThirdLoginInterface" method="getCustomerInfo"/>
<resources>
<resource ref="self"/>
</resources>
</route>
</routes>
说明:
该文件定义了一个获取用户信息的web api
第二步:Interface文件
File:app\code\Weblogin\Thirdlogin\Api\ThirdLoginInterface.php
在模块目录下创建Api目录,并添加webapi.xml中指定的service接口文件
<?php
namespace Weblogin\Thirdlogin\Api;
interface ThirdLoginInterface {
/**
* get customer info
* @param string $email
* @return string
*/
public function getCustomerInfo($email);
}
第三步:在di.xml文件添加依赖注入:
File: app\code\Weblogin\Thirdlogin\etc\di.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Weblogin\Thirdlogin\Api\ThirdLoginInterface" type="Weblogin\Thirdlogin\Model\ThirdLogin"/>
</config>
第四步:添加实体类,编写业务逻辑:
File:app\code\Weblogin\Thirdlogin\Model\ThirdLogin.php
<?php
namespace Weblogin\Thirdlogin\Model;
class ThirdLogin
{
/**
* {@inheritdoc}
*/
public function getCustomerInfo($email)
{
$res = [
'code' => 200,
'message' => '',
'data' => []
];
$om = \Magento\Framework\App\ObjectManager::getInstance();
$conn = $om->get('Magento\Framework\App\ResourceConnection')->getConnection();
$table = $conn->getTableName('customer_entity');
$fields = ["entity_id","email"];
$select = $conn->select()
->from($table,$fields)
->where('email = ?', $email);
$customerInfo = $conn->fetchAll($select);
if(empty($customerInfo)){
$res['code'] = 10001;
$res['message'] = 'customer not exists.';
exit(json_encode($res));
}
$customer = $customerInfo[0];
$res['data'] = $customer;
exit(json_encode($res));
}
}
第五步,更新module
执行命令
php bin/magento s:up
chmod -R 777 /var/www/html/magento
最后,通过postman发送请求到
http://192.168.31.58/rest/V1/customers/weblogin/customer_info
并在请求body中传入用户email
查看返回信息。
如无特殊说明或标注,任何个人或组织,复制、转载、采集本站内容请注明:
本文来源于:【Magento中文网】,并添加本文地址链接。
如未按上述操作复制或转载,本站有权追究法律责任。
若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
本文来源于:【Magento中文网】,并添加本文地址链接。
如未按上述操作复制或转载,本站有权追究法律责任。
若本站内容侵犯了原著者的合法权益,可联系我们进行处理。