使用REST API以JSON格式获取产品详细信息

时间:2017-02-17 06:22:03

标签: json rest api oauth magento2

如何使用Magento2中的REST API以JSON格式获取产品详细信息?当我搜索时,我发现了以下代码。

$url = 'magentohost url';
$callbackUrl = $url . "oauth_admin.php";
$temporaryCredentialsRequestUrl = $url . "oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = $url . 'admin/oauth_authorize';
$accessTokenRequestUrl = $url . 'oauth/token';
$apiUrl = $url . 'api/rest';
$consumerKey = 'consumer_key';
$consumerSecret = 'consumer_secret';
$token = 'token';
$secret = 'token_secret';
 try {
    $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauthClient->setToken($token, $secret);
    $resourceUrl = "$apiUrl/products";
    $oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json', 'Accept' => 'application/json'));
    $productsList = json_decode($oauthClient->getLastResponse());
    echo '<pre>';
    print_r($productsList);
}
catch(Exception $e) {
    echo '<pre>';
    print_r($e);
}

但是我需要把这个问题放在哪里......而且我对这个网址感到困惑...... 并且它还返回错误类OAuth未找到

1 个答案:

答案 0 :(得分:1)

首先,我们需要在Magento 2中创建Web服务角色和Web服务用户

Create Web Service Role:
Login Admin Panel> System> User Roles> Add New Role
Add the Role Name and your current password of Admin in Your Password field
Tap Role Resources
Choose what are required for service of your web in Resource Access
Tap Save Role
Create Web Service User in Magento 2

此用户用于您创建的角色

Go to System> All Users> Add New User
Fill in all the necessary information
Tap User Role then choose which you’ve created
Tap Save User

上述用户将使用Magento 2中的REST API Web服务。

接下来,我们将开始使用Magento 2 REST API。创建一个名为my_magento2_rest_apt.php的php文件或任何您想要创建的文件。并将其放置在磁根目录中。

将此代码添加到文件中。

define('BASEURL','http://yourdomin.com/magento2location/');

$apiUser = 'username'; 
$apiPass = 'password';
$apiUrl = BASEURL.'index.php/rest/V1/integration/admin/token';
/*
    Magento 2 REST API Authentication
*/
$data = array("username" => $apiUser, "password" => $apiPass);                                                                    
$data_string = json_encode($data);                       
try{
    $ch = curl_init($apiUrl); 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );       
    $token = curl_exec($ch);
    $token = json_decode($token);
    if(isset($token->message)){
        echo $token->message;
    }else{
        $key = $token;
    }
}catch(Exception $e){
    echo 'Error: '.$e->getMessage();
}


/*
    Get Product By SKU REST API Magento 2
    Use above key into header
*/
$headers = array("Authorization: Bearer $key"); 
//$requestUrl = BASEURL.'index.php/rest/V1/products/24-MB01';//24-MB01 is the sku.
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[page_size]=10';// get total 10 products
//$requestUrl = BASEURL.'index.php/rest/V1/categories/24/products';// 24 category id
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria=';//get all products
$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=24&searchCriteria[filter_groups][0][filters][0][condition_type]=eq';

$ch = curl_init();
try{
    $ch = curl_init($requestUrl); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   

$result = curl_exec($ch);
$result = json_decode($result);

if(isset($result->message)){
    echo $result->message;
}else{
    print_r($result);
}
    }catch(Exception $e){
        echo 'Error: '.$e->getMessage();
    }

现在输入您的API即可。 http://yourdomin.com/magento2location/my_magento2_rest_apt.php