我正在尝试通过curl与授权令牌交换OAuth代码。服务器API文档说,我应该发送POST数据,我正在做:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return result
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); // disallow redirection
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // timeout 5s
curl_setopt($ch, CURLOPT_URL, $url); // OAuth access token url
curl_setopt($ch, CURLOPT_POST, 1); // send via POST
// I have prepared query arguments as an array $args
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($args));
// Turning on some debug info
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
// Executing curl
$data = curl_exec($ch);
问题在于服务器响应。我总是收到OAuth错误: unsupported_grant_type 。所有文档资源都说参数grant_type必须设置为“authorization_code”值(在所有情况下都在这个OAuth步骤中),但无论如何它都不起作用。有什么想法吗?
答案 0 :(得分:1)
这是SalesForce OAuth吗?
如果是这样,他们需要设置Content-Type和Content-Length,例如:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded", "Content-length: ".strlen($params)));
答案 1 :(得分:0)
由于(根据评论)http_build_query($args)
返回一个数组,curl正在发送内容类型为multipart/form-data
的POST(请参阅docs for curl_setopt)。 OAuth服务器可能需要application/x-www-form-urlencoded
,在这种情况下,http_build_query
需要返回类似para1=val1¶2=val2&...
的urlencoded字符串。
答案 2 :(得分:0)
您的通用CURL请求应使用
进行自定义答案 3 :(得分:0)
以下是一个工作代码,它使用来自google服务器的client_and client_secret返回身份验证令牌。
`tok_url:OAuth Token url, Auth_token: authentication token returned from google servers when cust_id and cust_secret are passed`
int get_refresh_token(char* tok_url,char* auth_token,char*cust_id,char*cust_secret)
{
CURL *curl;
CURLcode res;
char data[1024]="\0";
strcat(data,"code=");
strcat(data,auth_token);
strcat(data,"&client_id=");
strcat(data,cust_id);
strcat(data,"&client_secret=");
strcat(data,cust_secret);
strcat(data,"&redirect_uri=");
strcat(data,"urn:ietf:wg:oauth:2.0:oob");
strcat(data,"&grant_type=authorization_code");
puts(data);
/* In windows, this will init the winsock stuff */
curl_global_init(CURL_GLOBAL_ALL);
/* get a curl handle */
curl = curl_easy_init();
if(curl) {
/* First set the URL that is about to receive our POST. This URL can
just as well be a https:// URL if that is what should receive the
data. */
curl_easy_setopt(curl, CURLOPT_URL, tok_url);
/* Now specify the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
curl_global_cleanup();
}