1

我正在尝试POST使用 Nodejs 将 XML 定价文件发送到加拿大沃尔玛。我收到响应代码200,但在沃尔玛端读取我的文件时出错。我相信它与Buffer.from()解析文件的方式有关,这会导致文件在被服务器接收时不可读。

这是我的代码:

  import { createSign, randomBytes } from 'crypto'
  import fetch from 'node-fetch';
  import { resolve } from 'url';
  import FormData from 'form-data';



  const method = 'POST';

  const BASE_URL = 'https://marketplace.walmartapis.com'

  const PK_HEADER = '\n-----BEGIN PRIVATE KEY-----\n'
  const PK_FOOTER = '\n-----END PRIVATE KEY-----\n'

  const WALMART_CONSUMER =  "walmart consumer";
  const WALMART_CHANNEL = 'walmart channel';
  const WALMART_SECRET = 'walmart secret';


  function generateCorrelationId () {
    return randomBytes(16).toString('hex')
   }

 function generateSignature (url, method, timestamp) {

 const privateKey = `${PK_HEADER}${WALMART_SECRET}${PK_FOOTER}`



const stringToSign = WALMART_CONSUMER + '\n' +
                 url + '\n' +
                 method.toUpperCase() + '\n' +
                 timestamp + '\n'

const sign = createSign('RSA-SHA256')

sign.update(stringToSign)
return sign.sign(privateKey, 'base64')
}
const url = BASE_URL + "/v3/ca/feeds?feedType=price";

const timestamp = Date.now()
const signature = generateSignature(url, method, timestamp)

const headers = {
  'WM_SVC.NAME': 'Walmart Marketplace',
  'WM_CONSUMER.ID': WALMART_CONSUMER,
  'WM_SEC.TIMESTAMP': timestamp,
  'WM_SEC.AUTH_SIGNATURE': signature,
  'WM_QOS.CORRELATION_ID': generateCorrelationId(),
  'WM_CONSUMER.CHANNEL.TYPE': WALMART_CHANNEL,
  'WM_TENANT_ID' : 'WALMART.CA',
  'WM_LOCALE_ID' : 'en_CA',
  "Content-Type": "multipart/form-data",
  'accept':'application/xml'

}

var form = new FormData();
const fileBuffer = Buffer.from("./prices.xml","utf8");
form.append('file',fileBuffer,"./prices.xml");

fetch(url, {
  method: method,
  headers: headers,
  body: form
 })
.then(response => console.log(response))
.catch(function (error) {
console.log(error)
});

xml文件——

<?xml version="1.0" encoding="UTF-8"?>
<PriceFeed xmlns="http://walmart.com/">
  <PriceHeader>
     <version>1.5.1</version>
  </PriceHeader>
   <Price>
      <itemIdentifier>
          <sku>SKU</sku>
      </itemIdentifier>
      <pricingList>
          <pricing>
              <currentPrice>
                  <value currency="CAD" amount="340.00"/>
              </currentPrice>
          </pricing>
      </pricingList>
   </Price>
</PriceFeed> 
4

1 回答 1

1

Buffer.from接受一个字符串,而不是文件路径。这可能就是它不起作用的原因。您可以尝试读取文件并将字符串传递给Buffer.from

https://nodejs.org/api/buffer.html#buffer_static_method_buffer_from_string_encoding

于 2021-08-10T03:14:32.617 回答