Amazon SP-API 获取产品

问题描述 投票:0回答:1

如何通过亚马逊SP-api获取与我的卖家账户关联的所有产品?

php laravel php-curl
1个回答
0
投票

使用 Amazon 门户生成刷新令牌 (

Atzr|....
)。还要记下您的客户端 ID 和客户端密钥。 将其作为参数传递给以下函数:

define('CLIENT_ID','amzn1.application-oa2-client.....');
define('CLIENT_SECRET','amzn1.oa2-cs.v1.....');

function writeLog($s,$level = 'INFO') {
    print($level . "\t" . $s . "\r\n");
}

function getToken($refresh_token) {
    try {
        $url = sprintf('https://api.amazon.com/auth/o2/token?grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s',$refresh_token,CLIENT_ID,CLIENT_SECRET);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array());
        $result = curl_exec($ch);
        $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($responseCode > 300) {
            throw new Exception($result, $responseCode);
        }
        return json_decode($result)->access_token;
    } catch(Exception $ex) {
        writeLog($ex->getMessage(),'ERROR');
    }
}
$your_auth_token = getToken('Atzr|...');

获得授权令牌后,请使用它从所需的端点检索数据,例如:

function http_request(string $url, string $token, array $params = array()) {
    try {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","User-Agent: YourSuperApp","x-amz-access-token: $token")); // Add the token to the header
        if (!empty($params)) { // this is a POST, add body. 
            //Some endpoints expect POST instead of GET, there you can pass the array of values as the 3rd parameter of this function
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        if ($result === false) {
            throw new Exception(curl_error($ch), curl_errno($ch));
        }
        return json_decode($result);
    } catch(Exception $ex) {
        writeLog($ex->getMessage(),'ERROR');
    }
}

$items = http_request('https://sellingpartnerapi-eu.amazon.com/catalog/2022-04-01/items?marketplaceIds=["A1PA6795UKMFR9"]',$your_auth_token);

然后您可以处理应为 this 格式的 JSON。您可以使用

var_dump($items);
来查看它的样子。

注意事项:

  1. API URL 每个区域都不同,请参阅此处。我用的是欧盟的。
  2. 可以在此处找到市场 ID。我用的是德国的。
© www.soinside.com 2019 - 2024. All rights reserved.