如何用libcurl正确设置Payhip许可证API的PUT请求参数?
解决libcurl调用Payhip License Usage API的400参数缺失问题
问题背景
已成功通过以下curl命令调用Payhip Software License Keys usage API:
curl https://payhip.com/api/v1/license/usage -d "product_link=MY_PRODUCT" -d "license_key=MY_KEY" -X PUT --header "payhip-api-key: API_KEY_HERE"
但用libcurl编写的C代码执行后,curl_easy_perform返回0,却得到HTTP/2 400响应,响应体为:
{"code":"required_parameters","message":"Missing or empty required parameters","success":false}
原C代码如下:
// curl CURL *curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, "https://payhip.com/api/v1/license/usage"); struct curl_slist *list = NULL; list = curl_slist_append(list, "API_KEY_HERE"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "product_link=MY_PRODUCT"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "license_key=MY_KEY"); CURLcode res = curl_easy_perform(curl);
错误原因
- HTTP请求头格式错误:API密钥头缺少
payhip-api-key:前缀,服务器无法识别该认证字段。 - 请求参数被覆盖:两次调用
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ...),第二次的参数会完全覆盖第一次,导致实际仅发送了license_key=MY_KEY,缺失product_link参数。
修正后的代码
// curl CURL *curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "https://payhip.com/api/v1/license/usage"); // 正确设置API密钥请求头 struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "payhip-api-key: API_KEY_HERE"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // 指定PUT请求方法 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); // 合并所有请求参数为单个字符串,用&分隔 const char *post_data = "product_link=MY_PRODUCT&license_key=MY_KEY"; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); CURLcode res = curl_easy_perform(curl); // 清理资源,避免内存泄漏 curl_slist_free_all(headers); curl_easy_cleanup(curl); }
补充说明
- 传递PUT请求的表单数据时,需将所有参数合并为
key1=value1&key2=value2格式的字符串,仅调用一次CURLOPT_POSTFIELDS设置。 - 严格按照API要求设置HTTP头,确保认证字段格式为
payhip-api-key: [你的密钥]。 - 代码中添加了资源清理步骤,避免长期运行导致内存泄漏。
内容的提问来源于stack exchange,提问作者Ueda Takeyuki
相关产品推荐
相关产品推荐

