Php 如何在magento中实现自定义RESTAPI?

Php 如何在magento中实现自定义RESTAPI?,php,rest,magento,Php,Rest,Magento,我正在尝试创建我的自定义RESTAPI。 我已经创建了自己的模块Custom/Restapi.Custom[Namespace],Restapi[module name] 在etc文件夹中,我创建了config.xml和api2.xml。以下是代码-: Config.xml <?xml version="1.0"?> <config> <modules> <Custom_Restapi>

我正在尝试创建我的自定义RESTAPI。 我已经创建了自己的模块Custom/Restapi.Custom[Namespace],Restapi[module name]

在etc文件夹中,我创建了config.xml和api2.xml。以下是代码-:

Config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Custom_Restapi>
            <version>0.1.0.0</version>
        </Custom_Restapi>
    </modules>
    <global>
        <models>
            <restapi>
                <class>Custom_Restapi_Model</class>
            </restapi>
        </models>
</config>
<config>
    <api2>
        <resource_groups>
            <restapi translate="title" module="Custom_Restapi">
                <title>Custom Rest API</title>
                <sort_order>10</sort_order>
            </restapi>
        </resource_groups>
        <resources>
            <restapi translate="title" module="Custom_Restapi">
                <group>restapi</group>
                <model>restapi/api2_restapi</model>
                <title>Testing My Rest API</title>
                <sort_order>10</sort_order>
                <privileges>
                    <admin>
                        <create>1</create>
                       <!-- <retrieve>1</retrieve>
                        <delete>1</delete>-->
                    </admin>
                   <!--  <customer>
                        <create>1</create>
                        <retrieve>1</retrieve>
                         <delete>1</delete>
                    </customer>
                     <guest>
                        <create>1</create>
                       <retrieve>1</retrieve>
                        <delete>1</delete>
                    </guest>-->
                </privileges>
                <routes>
                    <route_entity>
                        <route>/custom/createwebsite/:s</route>
                        <action_type>entity</action_type>
                    </route_entity>
                </routes>
                <versions>1</versions>
            </restapi>
        </resources>
    </api2>
app\code\local\Custom\Restapi\Model\Api2\Restapi\Rest\Admin\V1.php下面是文件的代码-:

V1.php

class Custom_Restapi_Model_Api2_Restapi extends Mage_Api2_Model_Resource
{

}
class Custom_Restapi_Model_Api2_Restapi_Rest_Admin_V1 extends Custom_Restapi_Model_Api2_Restapi
{
     protected function _create(){
  
   
   return  json_encode(array("testing","hello"));
}

 protected function _retrieveCollection()
{
      return  json_encode(array("testing","hello"));
 }
}
还设置了Etc/模块配置文件

管理设置

  • 我已经创建了OAuth角色管理员。在左侧选项卡“角色Api资源”下,显示并选择模块设置

  • 还配置了Rest使用者设置

  • 下面是REST API调用脚本代码-:

    Api调用脚本代码

    $consumerKey    = 'ozr74egldg07dpxtkk9uq1o8bj6wwd65'; // from Admin Panel's &quot;REST - OAuth Consumers page&quot;
    $consumerSecret = 'ozr74egldg07dpxtkk9uq1o8bj6wwd65'; // from Admin Panel's &quot;REST - OAuth Consumers page&quot;
    
    // Set the OAuth callback URL to this script since it contains the logic
    // to execute *after* the user authorizes this script to use the Coupon AutoGen API
    $callbackUrl = "http://127.0.0.1/magento/testscript.php";
    
    // Set the URLs below to match your Magento installation
    $temporaryCredentialsRequestUrl = "http://127.0.0.1/mage_restapi/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
    $adminAuthorizationUrl = 'http://127.0.0.1/mage_restapi/admin/oauth_authorize';
    $accessTokenRequestUrl = 'http://127.0.0.1/mage_restapi/oauth/token';
    $apiUrl = 'http://127.0.0.1/mage_restapi/api/rest';
    
    session_start();
    
    if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
        $_SESSION['state'] = 0;
        echo "try";
    }
    
    try {
       
        $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
        $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
    
        $oauthClient->enableDebug();
    
        if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
           
            $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
            $_SESSION['secret'] = $requestToken['oauth_token_secret'];
            $_SESSION['state'] = 1;
            header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
            exit;
        } else if ($_SESSION['state'] == 1) {
            $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
            $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
            $_SESSION['state']  = 2;
            $_SESSION['token']  = $accessToken['oauth_token'];
            $_SESSION['secret'] = $accessToken['oauth_token_secret'];
            header('Location: ' . $callbackUrl);
            exit;
        } else {  
           
            // We have the OAuth client and token. Now, let's make the API call.
            $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
    
            
    
            // Generate coupon codes via POST
            $resourceUrl = "$apiUrl/custom";
            
            $oauthClient->fetch($resourceUrl, OAUTH_HTTP_METHOD_POST, array(
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ));
    
    
             $data= json_decode($oauthClient->getLastResponse(), true);
            
    
            echo "Data is:<br/>".$data;
          
        }
    } catch (OAuthException $e) {
        
        print_r($e->getMessage());
        //echo "<br/>";
        //print_r($e->lastResponse);
    }
    
    $consumerKey='ozr74egldg07dpxtkk9uq1o8bj6wwd65';//从管理面板的“REST-OAuth用户页面”
    $ConsumerCret='ozr74egldg07dpxtkk9uq1o8bj6wwd65';//从管理面板的“REST-OAuth用户页面”
    //将OAuth回调URL设置为此脚本,因为它包含逻辑
    //要在*之后执行,用户授权此脚本使用优惠券AutoGen API
    $callbackUrl=”http://127.0.0.1/magento/testscript.php";
    //设置下面的URL以匹配您的Magento安装
    $temporaryCredentialsRequestUrl=”http://127.0.0.1/mage_restapi/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
    $adminAuthorizationUrl=http://127.0.0.1/mage_restapi/admin/oauth_authorize';
    $accessTokenRequestUrl='0http://127.0.0.1/mage_restapi/oauth/token';
    $apiUrl='1http://127.0.0.1/mage_restapi/api/rest';
    会话_start();
    if(!isset($\u GET['oauth\u token'])和&isset($\u SESSION['state'])和&$\u SESSION['state']==1){
    $\u会话['state']=0;
    呼应“尝试”;
    }
    试一试{
    $authType=($_SESSION['state']==2)?OAUTH\u AUTH\u TYPE\u授权:OAUTH\u AUTH\u TYPE\u URI;
    $oauthClient=new OAuth($consumerKey、$ConsumerCret、OAuth_SIG_METHOD_HMACSHA1、$authType);
    $oauthClient->enableDebug();
    如果(!isset($\u GET['oauth\u token'])和&&&!$\u会话['state']){
    $requestToken=$oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
    $\u会话['secret']=$requestToken['oauth\u token\u secret'];
    $_会话['state']=1;
    标头('Location:'.$adminAuthorizationUrl'.?oauth_令牌='.$requestToken['oauth_令牌']);
    出口
    }else if($_会话['state']==1){
    $oauthClient->setToken($\u GET['oauth\u token',$\u SESSION['secret']);
    $accessToken=$oauthClient->getAccessToken($accessTokenRequestUrl);
    $\会话['state']=2;
    $_会话['token']=$accessToken['oauth_token'];
    $\u会话['secret']=$accessToken['oauth\u token\u secret'];
    标题('Location:'。$callbackUrl);
    出口
    }否则{
    //我们有OAuth客户端和令牌。现在,让我们进行API调用。
    $oauthClient->setToken($_会话['token',$_会话['secret']);
    //通过POST生成优惠券代码
    $resourceUrl=“$apiUrl/custom”;
    $oauthClient->fetch($resourceUrl,OAUTH\u HTTP\u方法\u POST,数组(
    '接受'=>'应用程序/json',
    '内容类型'=>'应用程序/json',
    ));
    $data=json_decode($oauthClient->getLastResponse(),true);
    echo“数据为:
    ”。$Data; } }捕获(OAutheException$e){ 打印($e->getMessage()); //回声“
    ”; //打印($e->lastResponse); }
    当我试图访问API时,它会请求授权

    授权应用程序管理员请求访问您的帐户

    授权后,应用程序将有权访问您的帐户

    “授权”按钮和“拒绝”按钮

    单击“授权”按钮后出错-:

    无效的身份验证/错误请求(获得404,预期为HTTP/1.1 20X或重定向) {“消息”:{“错误”:[{“代码”:404,“消息”:“请求与任何路由都不匹配。”}]}

    PHP OAuth扩展在我的OAuth设置中不支持RSA-SHA1支持

    参考链接

    我们仅使用magento提供的函数访问rest中的代码,下面是函数列表-:

  • _创建()
  • _检索()
  • _删除()
  • _retrieveCollection()
  • _更新()
  • _多重更新()
  • _多重删除
  • 错误 无效的身份验证/错误请求(获得404,预期为HTTP/1.1 20X或重定向) {“消息”:{“错误”:[{“代码”:404,“消息”:“请求与任何路由都不匹配。”}]}


    我已分享了以上所有分析,但无法访问数据。请分享您的反馈。

    您的ressource url应与您的api2.xml中的url相对应

    $resourceUrl = "$apiUrl/custom";
    
    应该是:

    $resourceUrl = "$apiUrl/custom/createwebsite/"
    

    $APIRL/custom/createwebsite/末尾的
    :s
    代表什么?

    核心API允许您管理Magento中使用的一组公共资源。但是,您可以选择拥有自己的一组资源来管理,或者您可能希望扩展核心API来处理其他资源

    这将有助于创建自定义API