简体   繁体   English

如何在magento中实现自定义REST API?

[英]How to implement custom REST API in magento?

I am trying to create my custom REST api. 我正在尝试创建自定义REST API。 I have create my own module Custom/Restapi.Custom [Namespace], Restapi[Module name]. 我创建了自己的模块Custom / Restapi.Custom [Namespace],Restapi [Module name]。

In etc folder i have created config.xml and api2.xml. 在etc文件夹中,我创建了config.xml和api2.xml。 Below is the code-: 以下是代码 - :

Config.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>

api2.xml api2.xml

<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>

Model Directory Structure 模型目录结构

app\\code\\local\\Custom\\Restapi\\Model\\Api2\\Restapi.php. 应用程序\\代码\\本地\\自定义\\ RESTAPI \\型号\\ API2 \\ Restapi.php。 Below is code of file-: 以下是文件代码 - :

Restapi.php Restapi.php

class Custom_Restapi_Model_Api2_Restapi extends Mage_Api2_Model_Resource
{

}

app\\code\\local\\Custom\\Restapi\\Model\\Api2\\Restapi\\Rest\\Admin\\V1.php Below is code of file-: app \\ code \\ local \\ Custom \\ Restapi \\ Model \\ Api2 \\ Restapi \\ Rest \\ Admin \\ V1.php下面是file-代码:

V1.php V1.php

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/module configuration file is also setup. 还设置了Etc /模块配置文件。

Admin setting 管理员设置

  1. I have create OAuth role admin. 我创建了OAuth角色admin。 Under left side tab "Role Api Resource" module settings are visible and selected. 在左侧选项卡“角色Api资源”模块设置可见并选中。

  2. Rest Consumer setting is also configured. 还配置了休眠消费者设置。

Below is REST API calling script code-: 下面是REST API调用脚本代码 - :

Api Calling Script Code 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);
}

When i am trying to access the API then it ask for Authorize 当我尝试访问API时,它会要求授权

Authorize application admin requests access to your account 授权应用程序管理员请求访问您的帐户

After authorization application will have access to you account. 授权申请后,您将有权访问您的帐户。

authorize button and reject button 授权按钮和拒绝按钮

After click on Authorize button Error-: 点击授权按钮错误后:

Invalid auth/bad request (got a 404, expected HTTP/1.1 20X or a redirect) {"messages":{"error":[{"code":404,"message":"Request does not match any route."}]}} 无效的身份验证/错误请求(获得404,预期的HTTP / 1.1 20X或重定向){“messages”:{“error”:[{“code”:404,“message”:“请求与任何路由都不匹配”。 }]}}

PHP OAuth extension does not support RSA-SHA1 support in my OAuth settings PHP OAuth扩展在我的OAuth设置中不支持RSA-SHA1支持

Reference Link http://www.magentocommerce.com/knowledge-base/entry/how-to-use-extend-the-magento-rest-api-to-use-coupon-auto-generation 参考链接http://www.magentocommerce.com/knowledge-base/entry/how-to-use-extend-the-magento-rest-api-to-use-coupon-auto-generation

http://ctodilemma.com/2013/04/customising-and-extending-the-magento-rest-api/ http://ctodilemma.com/2013/04/customising-and-extending-the-magento-rest-api/

We only use the function provided by magento for accessing the code in rest, below are the function list-: 我们只使用magento提供的函数来访问其余的代码,下面是函数列表 - :

  1. _create() _创造()
  2. _retrieve() _retrieve()
  3. _delete() _删除()
  4. _retrieveCollection() _retrieveCollection()
  5. _update() _Update()
  6. _multiUpdate() _multiUpdate()
  7. _multiDelete _multiDelete

Error Invalid auth/bad request (got a 404, expected HTTP/1.1 20X or a redirect) {"messages":{"error":[{"code":404,"message":"Request does not match any route."}]}} 错误无效的身份验证/错误请求(获得404,预期的HTTP / 1.1 20X或重定向){“messages”:{“error”:[{“code”:404,“message”:“请求与任何路由都不匹配。 “}]}}

I have shared above my all analysis but i am not able to access the data.Please share your feedback. 我已经分享了我的所有分析,但我无法访问数据。请分享您的反馈。

The Core API allows you to manage a set of common resources used in Magento. Core API允许您管理Magento中使用的一组公共资源。 However, you may choose to have your own set of resources to manage, or you may wish to extend the Core API to handle additional resources. 但是,您可以选择使用自己的一组资源进行管理,或者您可能希望扩展Core API以处理其他资源。

This would be help full to create custom API. 这将有助于创建自定义API。

http://devdocs.magento.com/guides/m1x/api/soap/create_your_own_api.html http://devdocs.magento.com/guides/m1x/api/soap/create_your_own_api.html

Your ressource url should correspond to the one in your api2.xml 您的资源URL应该与api2.xml中的URL相对应

$resourceUrl = "$apiUrl/custom";

should be : 应该 :

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

What does the :s at the end of $apiUrl/custom/createwebsite/ :s stands for ? 什么:s $ apiUrl / custom / createwebsite / :s代表的结尾?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM