Coldfusion 使用标头和参数创建chttp

Coldfusion 使用标头和参数创建chttp,coldfusion,cfc,cfhttp,Coldfusion,Cfc,Cfhttp,我正试图从一个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",

我正试图从一个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
金额
。请尝试
value=“#序列化JSON(金额)#”

看起来您需要将数据作为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);

非常感谢。我很愚蠢。它可以工作,唯一的问题是没有授权。错误403错误403是因为服务器需要“POST”。不知何故,参数仍然是错误的。我得到响应{“status”:400,“errorCode”:“702”,“message”:“Unexpected input:m=”,“errorType”:“validation”}@myTest532myTest532-根据您的CURL示例,您需要在请求体中发送JSON。请参阅下面我的答案,了解如何执行此操作。尝试以字符串形式发送金额值,并用引号传递,如“金额”=“{‘值’:1000,‘货币’:‘美元’”