我正在尝试从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属性的值无效。字符串值是必需的。
我发送的参数错误吗?
谢谢
答案 0 :(得分:2)
您正在将结构传递到cfhttpparam
amount
中。尝试value="#serializeJSON( amount )#"
答案 1 :(得分:2)
您似乎需要将数据作为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);