代码改变世界

Amazon SP API批量更新价格 JSON_LISTINGS_FEED

2025-07-04 14:55  天心PHP  阅读(57)  评论(0)    收藏  举报

以下 Feed 类型值已于 2024 年 3 月 18 日弃用。这些类型的移除日期已从 2025 年 3 月 31 日更改为 2025 年 7 月 31 日:

  • POST_PRODUCT_DATA
  • POST_INVENTORY_AVAILABILITY_DATA
  • POST_PRODUCT_OVERRIDES_DATA
  • POST_PRODUCT_PRICING_DATA
  • POST_PRODUCT_IMAGE_DATA
  • POST_PRODUCT_RELATIONSHIP_DATA
  • POST_FLAT_FILE_INVLOADER_DATA
  • POST_FLAT_FILE_BOOKLOADER_DATA
  • POST_FLAT_FILE_CONVERGENCE_LISTINGS_DATA
  • POST_FLAT_FILE_LISTINGS_DATA
  • POST_FLAT_FILE_PRICEANDQUANTITYONLY_UPDATE_DATA
  • POST_UIEE_BOOKLOADER_DATA

因为我这里只用到了 POST_PRODUCT_PRICING_DATA 批量更新价格

文档 Listing workflow migration tutorial   New JSON_LISTINGS_FEED submission when updating pricing only

以前的上传xml   这里因为是批量 都是用的 Feeds API

<!--?xml version="1.0" encoding="UTF-8"?-->
<amazonenvelope xsi:nonamespaceschemalocation="amzn-envelope.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <header>
        <documentversion>1.01</documentversion>
        <merchantidentifier>A11JVGTAKCKZET</merchantidentifier>
    </header>
    <messagetype>Price</messagetype>
    <message>
        <messageid>1</messageid>
        <price>
            <sku>TIAYKL-FBM-ORANGE</sku>
            <standardprice currency="USD">26.99</standardprice>
            <businessprice>26.99</businessprice>
        </price>
    </message>
    <message>
        <messageid>2</messageid>
        <price>
            <sku>TIAYKL-FBM-RED</sku>
            <standardprice currency="USD">26.99</standardprice>
            <businessprice>26.99</businessprice>
        </price>
    </message>
    <message>
        <messageid>3</messageid>
        <price>
            <sku>TIAYKL-FBM-YELLOW</sku>
            <standardprice currency="USD">26.99</standardprice>
            <businessprice>26.99</businessprice>
        </price>
    </message>
</amazonenvelope>
View Code

改成现在json

{
    "header": {
        "sellerId": "A11JVGTAKCKZET",
        "version": "2.0",
        "issueLocale": "en_US"
    },
    "messages": [
        {
            "messageId": 1,
            "sku": "TIAYKL-FBM-ORANGE",
            "operationType": "PATCH",
            "productType": "PRODUCT",
            "patches": [
                {
                    "op": "replace",
                    "path": "\/attributes\/purchasable_offer",
                    "value": [
                        {
                            "audience": "ALL",
                            "currency": "USD",
                            "our_price": [
                                {
                                    "schedule": [
                                        {
                                            "value_with_tax": "26.99"
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "audience": "B2B",
                            "currency": "USD",
                            "our_price": [
                                {
                                    "schedule": [
                                        {
                                            "value_with_tax": 26.99
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "messageId": 2,
            "sku": "TIAYKL-FBM-RED",
            "operationType": "PATCH",
            "productType": "PRODUCT",
            "patches": [
                {
                    "op": "replace",
                    "path": "\/attributes\/purchasable_offer",
                    "value": [
                        {
                            "audience": "ALL",
                            "currency": "USD",
                            "our_price": [
                                {
                                    "schedule": [
                                        {
                                            "value_with_tax": "26.99"
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "audience": "B2B",
                            "currency": "USD",
                            "our_price": [
                                {
                                    "schedule": [
                                        {
                                            "value_with_tax": 26.99
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "messageId": 3,
            "sku": "TIAYKL-FBM-YELLOW",
            "operationType": "PATCH",
            "productType": "PRODUCT",
            "patches": [
                {
                    "op": "replace",
                    "path": "\/attributes\/purchasable_offer",
                    "value": [
                        {
                            "audience": "ALL",
                            "currency": "USD",
                            "our_price": [
                                {
                                    "schedule": [
                                        {
                                            "value_with_tax": "26.99"
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "audience": "B2B",
                            "currency": "USD",
                            "our_price": [
                                {
                                    "schedule": [
                                        {
                                            "value_with_tax": 26.99
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}
View Code

1.获取要上传的url   api路径:/feeds/2021-06-30/documents   得到url

以前的和现在的一样

Array
(
    [feedDocumentId] => amzn1.tortuga.4.na.9611d8b0-c58b-43b4-a366-66b0018d299c.T1TVKGJCR9JD2O
    [url] => https://tortuga-prod-na.s3-external-1.amazonaws.com/9611d8b0-c58b-43b4-a366-66b0018d299c.amzn1.tortuga.4.na.T1TVKGJCR9JD2O?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20250704T062446Z&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Expires=300&X-Amz-Credential=AKIA5U6MO6RADQRQYCSG%2F20250704%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=34355df203f14e7a950754ebeb7f608573df734215e27a2e181d97a9fc1e5108
)

 

2.上传上述的xml     新的就上传json

以前的和现在的一样

Array
(
    [0] => 200
    [1] => 
)

 

3.根据第1部  feedDocumentId 和 Feed 类型 (POST_PRODUCT_PRICING_DATA) api路径:/feeds/2021-06-30/feeds  得到 feedId

以前的和现在的一样

Array
(
    [feedId] => 85315020273
)

这里xml 用的 feedType=POST_PRODUCT_PRICING_DATA    新的json改成 feedType=JSON_LISTINGS_FEED

代码

 

private function postFeed(array $feeddata)
{
    $data = [];
    $requestReport = new AmazonAllListingNew();
    //$xml = $requestReport->getxml($this->accountInfo['merchant_id'],$feeddata); //以前组建xml数据
    $xml = $requestReport->getjson($this->accountInfo['merchant_id'],$feeddata);  //新的组建json数据

    //$payload =["contentType"=>"text/xml; charset=UTF-8"];  //xml
    $payload =["contentType"=>"application/json; charset=UTF-8"]; //json
    //第一步获取上传的url
    $res = $requestReport->applicationreport($this->accountInfo['merchant_id'],$this->accountInfo['site'],'/feeds/2021-06-30/documents','',$payload,'POST');
    if(isset($res['url'])){
        //第二步上传数据包
        //$res1 = $this->cur_request($res['url'],'PUT',$xml,["Content-Type:text/xml; charset=UTF-8"]); //以前上传xml
        $res1 = $this->cur_request($res['url'],'PUT',$xml,["Content-Type:application/json; charset=UTF-8"]); //现在上传json
        if(isset($res1[0]) && $res1[0]==200){//上传成功
            //$payload2 = ["feedType"=>"POST_PRODUCT_PRICING_DATA","marketplaceIds"=>[$this->accountInfo['market_place_id']],"inputFeedDocumentId"=>$res['feedDocumentId']]; //以前的 POST_PRODUCT_PRICING_DATA
            $payload2 = ["feedType"=>"JSON_LISTINGS_FEED","marketplaceIds"=>[$this->accountInfo['market_place_id']],"inputFeedDocumentId"=>$res['feedDocumentId']]; //现在的 JSON_LISTINGS_FEED
            //第三步得到feedId
            $res2 = $requestReport->applicationreport($this->accountInfo['merchant_id'],$this->accountInfo['site'],'/feeds/2021-06-30/feeds','',$payload2,'POST');
            if(isset($res2['feedId'])){//成功需要时间
                $data['feedId'] = $res2['feedId'];
                $data['xml'] = $xml;
                return $data;
            }
        }
    }
}

//组建xml代码
public function getxml($merchant_id,$feeddata){
    $xml = '<?xml version="1.0" encoding="UTF-8"?><AmazonEnvelope xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Header><DocumentVersion>1.01</DocumentVersion><MerchantIdentifier>'.$merchant_id.'</MerchantIdentifier></Header><MessageType>Price</MessageType>';
    foreach ($feeddata as $key=>$val){
        $xml.='<Message><MessageID>'.($key+1).'</MessageID><Price><SKU>'.$val['sku'].'</SKU>';
        if(isset($val['saleprice'])){
            $xml .='<Sale><StartDate>'.$val['stime'].'</StartDate><EndDate>'.$val['etime'].'</EndDate><SalePrice currency="'.$val['currency'].'">'.$val['saleprice'].'</SalePrice></Sale>';
        }
        $xml.='<StandardPrice currency="'.$val['currency'].'">'.$val['stdprice'].'</StandardPrice><BusinessPrice>'.$val['BusinessPrice'].'</BusinessPrice></Price></Message>';
    }
    $xml .= '</AmazonEnvelope>';
    return $xml;
}

//组建json代码
public function getjson($merchant_id,$feeddata)
{
    $jsonarr = [
        'header' =>[
            'sellerId' => $merchant_id,
            'version' => '2.0',
            'issueLocale' => 'en_US'
        ]
    ];
    foreach ($feeddata as $key=>$val){
       $arr  = [
            'messageId' => ($key+1),
            'sku' => $val['sku'],
            'operationType' => 'PATCH',
            'productType' => 'PRODUCT',
            'patches' => [
                [
                    'op' => 'replace',
                    'path' => '/attributes/purchasable_offer',
                    'value' => [
                        [
                            'audience' => 'ALL',
                            'currency' => $val['currency'],
                            'our_price' => [
                                [
                                    'schedule' => [
                                        ['value_with_tax' => $val['stdprice']]
                                    ]
                                ]
                            ]
                        ],
                        [
                            'audience' => 'B2B',
                            'currency' => $val['currency'],
                            'our_price' => [
                                [
                                    'schedule' => [
                                        ['value_with_tax' => $val['BusinessPrice']]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ],
        ];
        $jsonarr['messages'][] = $arr;
    }
    return json_encode($jsonarr);
}

//上传数据函数
public function cur_request($URL,$type,$params,$headers,$types=0){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $URL);
    if($headers!=""){
        curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
    }else {
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 30);
    switch ($type){
        case "GET" : curl_setopt($ch, CURLOPT_HTTPGET, true);break;
        case "POST": curl_setopt($ch, CURLOPT_POST,true);
            curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
        case "PUT" : curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
        case "PATCH": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);break;
        case "DELETE":curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
    }
    $file_contents = curl_exec($ch);//获得返回值
    if($types){
        print_r('<pre>');
        print_r($file_contents);
        print_r('</pre>');
    }
    $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($types){
        print_r('<pre>');
        print_r($responseCode);
        print_r('</pre>');
    }
    curl_close($ch);
    return [$responseCode,json_decode($file_contents,true)];
}

 

4.根据 feedId 得到上传的状态 api路径:/feeds/2021-06-30/feeds/feedId  得到 resultFeedDocumentId  

以前的和现在的一样

Array
(
    [processingEndTime] => 2025-07-04T03:44:42+00:00
    [processingStatus] => DONE
    [marketplaceIds] => Array
        (
            [0] => ATVPDKIKX0DER
        )

    [feedId] => 85312020273
    [feedType] => JSON_LISTINGS_FEED
    [createdTime] => 2025-07-04T03:44:21+00:00
    [processingStartTime] => 2025-07-04T03:44:34+00:00
    [resultFeedDocumentId] => amzn1.tortuga.4.na.03201a01-0767-40a6-b65e-4f43ed35baba.TCXCKSX7OKHPG
)

5.根据第四步 resultFeedDocumentId   api路径:/feeds/2021-06-30/documents/resultFeedDocumentId   得到上传的结果路径

以前的

Array
(
    [feedDocumentId] => amzn1.tortuga.4.na.91bcb8a0-83d3-4c0b-adb7-eb28bc1e4357.T2OHPNZBUPGSOJ
    [url] => https://tortuga-prod-na.s3-external-1.amazonaws.com/91bcb8a0-83d3-4c0b-adb7-eb28bc1e4357.amzn1.tortuga.4.na.T2OHPNZBUPGSOJ?response-content-encoding=identity&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20250704T063305Z&X-Amz-SignedHeaders=host&X-Amz-Expires=300&X-Amz-Credential=AKIA5U6MO6RADQRQYCSG%2F20250704%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d085a6fce8681005d8e1a4dc7f86fe487a7ad67e7bf2d85582f7825960f6c191
)

新的

Array
(
    [compressionAlgorithm] => GZIP
    [feedDocumentId] => amzn1.tortuga.4.na.03201a01-0767-40a6-b65e-4f43ed35baba.TCXCKSX7OKHPG
    [url] => https://tortuga-prod-na.s3-external-1.amazonaws.com/03201a01-0767-40a6-b65e-4f43ed35baba.amzn1.tortuga.4.na.TCXCKSX7OKHPG?response-content-encoding=identity&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20250704T034538Z&X-Amz-SignedHeaders=host&X-Amz-Expires=300&X-Amz-Credential=AKIA5U6MO6RADQRQYCSG%2F20250704%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=98b0dd6df8e65168930ca06ef30b4ef7ad272c3dc116b62add4ab709af2ad798
)

代码

6.获取第5步url的结果

以前的

<AmazonEnvelope
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
    <Header>
        <DocumentVersion>1.02</DocumentVersion>
        <MerchantIdentifier>A11JVGTAKCKZET</MerchantIdentifier>
    </Header>
    <MessageType>ProcessingReport</MessageType>
    <Message>
        <MessageID>1</MessageID>
        <ProcessingReport>
            <DocumentTransactionID>85315020273</DocumentTransactionID>
            <StatusCode>Complete</StatusCode>
            <ProcessingSummary>
                <MessagesProcessed>3</MessagesProcessed>
                <MessagesSuccessful>3</MessagesSuccessful>
                <MessagesWithError>0</MessagesWithError>
                <MessagesWithWarning>1</MessagesWithWarning>
            </ProcessingSummary>
            <Result>
                <MessageID>0</MessageID>
                <ResultCode>Warning</ResultCode>
                <ResultMessageCode>99058</ResultMessageCode>
                <ResultDescription>The feed type used for this submission via the Selling Partner Feeds API is deprecated and will sunset soon. To continue submitting listings data through APIs (including pricing and inventory updates), you will need to migrate to the Selling Partner Listings Items APIs or the JSON_LISTINGS_FEED feed type submitted via the Selling Partner Feeds API. If you have received this message through a third-party solution, please contact your solution provider. If you are using the Selling Partner Feeds API directly, more details on migrating can be found on the Selling Partner API developer documentation website: https://developer-docs.amazon.com/sp-api/changelog/update-deprecation-of-feeds-api-support-for-xml-and-flat-file-listings-feeds-date-changed-to-june-30-2025.</ResultDescription>
            </Result>
        </ProcessingReport>
    </Message>
</AmazonEnvelope>

现在的

{"header":{"sellerId":"A11JVGTAKCKZET","version":"2.0","feedId":"85308020273"},"issues":[],"summary":{"errors":0,"warnings":0,"messagesProcessed":3,"messagesAccepted":3,"messagesInvalid":0}}

以前这里直接返回的xml 现在返回的json压缩包

第4,5,6代码

$xml = '';
$feedsinfo = $requestReport->applicationreport($account->merchant_id,$account->site,'/feeds/2021-06-30/feeds/'.$r['feed_sid'],'','','GET'); //根据 feedId 获取处理状态
if(isset($feedsinfo['processingStatus'])&&$feedsinfo['processingStatus']=='DONE'){
    $xmlurl = $requestReport->applicationreport($account->merchant_id,$account->site,'/feeds/2021-06-30/documents/'.$feedsinfo['resultFeedDocumentId'],'','','GET'); //根据上述返回的 resultFeedDocumentId 获取结果URL
    if($xmlurl['compressionAlgorithm'] && $xmlurl['compressionAlgorithm']=='GZIP'){
        $xml = $requestReport->getgzipFile($xmlurl['url']); //现在的获取json压缩包
    }elseif(isset($xmlurl['url'])){
        $xml = file_get_contents($xmlurl['url']);  //以前获取xml
    }
}

public function getgzipFile($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); // 告诉cURL你想要接受gzip压缩的内容
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用SSL证书验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 禁用SSL主机名验证
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    } else {
        $decoded = gzdecode($response);
        if ($decoded !== false) {
            // 成功解压并输出内容
            return $decoded;
        } else {
            echo 'Failed to decode the GZIP content.';
        }
    }
    curl_close($ch);
}