使用 header 和参数创建 chttp

creating chttp using header and parameters

我正在尝试根据 curl 请求创建 cfhttp。这是请求:

curl https://url/paymentMethods \
-H "x-API-key: YOUR_X-API-KEY" \
-H "content-type: application/json" \
-d '{
  "merchantAccount": "YOUR_MERCHANT_ACCOUNT",
  "countryCode": "NL",
  "amount": {
    "currency": "EUR",
    "value": 1000
  },
  "channel": "Web"
}'

我创建了一个函数 运行 cfhttp:

try{
    apiKey = 'myKey';
    requestURL = 'https://url/';
    merchantAccount = 'myAccount';
    amount = {
      'value': 1000,
      'currency': 'USD'  
    };

    cfhttp(method="GET", url="#requestURL#/paymentMethods", result="data"){
        cfhttpparam(name="x-API-key", type="header", value="#apiKey#");
        cfhttpparam(name="content-type", type="header", value="application/json");
        cfhttpparam(name="merchantAccount", type="formfield", value="#merchantAccount#");
        cfhttpparam(name="countryCode", type="formfield", value="US");
        cfhttpparam(name="amount", type="formfield", value="#amount#");
        cfhttpparam(name="channel", type="formfield", value="web");
    }
    data = deserializeJSON(charge.data);
    WriteDump(data);
} catch(any e){
    WriteDump(e);
}

当我 运行 它时,我收到错误:CFHTTPPARAM 的属性验证错误。 VALUE 属性的值无效。需要一个字符串值。

我是不是传错参数了?

谢谢

您正在将结构传递到您的 cfhttpparam amount。尝试 value="#serializeJSON( amount )#"

您似乎需要将数据作为 JSON 打包到您的请求正文中。我更喜欢下面的语法而不是 cfhttp/cfhttpparam,但是下面的代码本质上是一样的:

// the api is expecting json in the body
requestData = {
    "merchantAccount": "YOUR_MERCHANT_ACCOUNT",
    "countryCode": "NL",
    "amount": {
        "currency": "EUR",
        "value": 1000
    },
    "channel": "Web"
};

apiKey = "your_api_key";

http = new http(argumentCollection={
    "url": "https://myendpoint.com/",
    "method": "post",
    "timeout": 30,
    "throwOnError": false,
    "encodeUrl": false
});

http.addParam(type="header", name="x-API-key", value=apiKey);
http.addParam(type="header", name="content-type", value="application/json");
http.addParam(type="body", value=serializeJSON(requestData));

// send the request
var httpResult = http.send().getPrefix();

// validate the response
param name="httpResult.status_code" default=500;

if (httpResult.status_code != 200) {
    throw(message="Failed to reach endpoint");
}

dump(var=httpResult);