今天我开发一个Magento2的Webapi来分享一下php
假设咱们已经学习过建设模块的前提
第一部建设module.xml设定模块web
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Inchoo_Hello" setup_version="1.0.0" /> </config>
而后新建Registrationapi
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Inchoo_Hello', __DIR__ );
这里须要创建两个xml文件di.xml和webapi.xml,其中di用于依赖注入,而webapi用于设定路由和指定方法名称,同时设定访问权限浏览器
<?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/hello/name/:name" method="GET"> <service class="Inchoo\Hello\Api\HelloInterface" method="name"/> <resources> <resource ref="anonymous"/> </resources> </route> </routes>
咱们使用anonymous设置,让其能够直接访问dom
<?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="Inchoo\Hello\Api\HelloInterface" type="Inchoo\Hello\Model\Hello" /> </config>
<?php namespace Inchoo\Hello\Api; interface HelloInterface { /** * Returns greeting message to user * * @api * @param string $name Users name. * @return string Greeting message with users name. */ public function name($name); }
<?php namespace Inchoo\Hello\Model; use Inchoo\Hello\Api\HelloInterface; class Hello implements HelloInterface { /** * Returns greeting message to user * * @api * @param string $name Users name. * @return string Greeting message with users name. */ public function name($name) { return "Hello, " . $name; } }
此处必须在声名方法前加上备注,注明参数类型,否则会报Class does not exist
我就赶上这个坑了后来网上找到:http://magento.stackexchange....
在接口文件加注释声名参数类型后能够正常运行,这我猜想是由于它是基于soap的接口,但php是弱类型命名的,因此在相似WSDL中其余强类型命名的想调用,出于考虑Magento把类型定义放到注释上,但这是一个大坑,咱们这些不清楚的人会不知道这个问题学习
目录结构以下图:测试
Rest Api格式以下:
http://{domain_name}/rest/V1/{method}/{attribute}/{value}.
浏览器直接打开地址以下:
如: http://magento2.loc/rest/V1/h... url
浏览器会显示如下结果:spa
<response>Hello, Jim</response>
<?php $proxy = new SoapClient('http://magento2.vm/index.php/soap/default?wsdl&services=inchooHelloV1'); $result = $proxy->inchooHelloV1Name(array("name"=>"Jim")); var_dump($result);
object(stdClass)#2 (1) { ["result"]=> string(10) "Hello, Jim" }
若不在WebApi使用anonymous权限,咱们须要在etc文件夹新建一个acl.xml文件.net
如: – etc/acl.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> <acl> <resources> <resource id="Magento_Backend::admin"> <resource id="Inchoo_Hello::hello" title="Hello" translate="title" sortOrder="110" /> </resource> </resources> </acl> </config>
在这种状况下,咱们须要在webapi.xml的resource节点中添加“Inchoo_Hello ::hello”,这种操做后就能够不使用anonymous了。
参考:http://inchoo.net/magento/api...
http://magento.stackexchange....