2012-06-07 5 views
4

curl을 사용하는 Google 계정에 대해 아래의 post 메소드를 사용하고 있지만 invalid_request 오류가 발생합니다. 여기 POST에서 CURL을 사용하는 POST가 잘못된 요청을합니다. 오류

POST /o/oauth2/token HTTP/1.1 
Host: accounts.google.com 
Content-Type: application/x-www-form-urlencoded 

code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf& 
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& 
client_secret=CENSORED& 
redirect_uri=http://localhost/oauth2callback& 
grant_type=authorization_code 

는 컬

$text ='test'; 

$URL = "https://accounts.google.com/o/oauth2/token"; 

$header = array(
"POST /o/oauth2/token HTTP/1.1", 
"Host: accounts.google.com", 
"Content-type: application/atom+xml;charset=\"utf-8\"", 
"Accept: text/xml", 
"Cache-Control: no-cache", 
"code=[my_code]&client_id=[my_client_id]&client_secret=[my_client_secret]& redirect_uri=http://localhost/curl_resp.php&grant_type=authorization_code", 
"Content-length: ".strlen($text), 
); 


$xml_do = curl_init(); 
curl_setopt($xml_do, CURLOPT_URL, $URL); 
curl_setopt($xml_do, CURLOPT_CONNECTTIMEOUT, 10); 
curl_setopt($xml_do, CURLOPT_TIMEOUT, 10); 
curl_setopt($xml_do, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($xml_do, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($xml_do, CURLOPT_SSL_VERIFYHOST, false); 
curl_setopt($xml_do, CURLOPT_POST, false); 
curl_setopt($xml_do, CURLOPT_POSTFIELDS, $text); 
curl_setopt($xml_do, CURLOPT_HTTPHEADER, $header); 

내 PHP 코드 그리고 잘못된 요청 오류 요청에 대한 응답이 실제로 문제의 매우 읽을 수있는 설명을 포함

+1

당신이 당신의 PHP 코드를 추가 할 수 있을까요? – Travesty3

+1

서버로 보내는 데이터에 POST 본문의 '&'문자 다음에 오는 새 줄이 있습니까? 왜냐하면 그들은해서는 안되기 때문입니다 ... – DaveRandom

+0

PHP 코드는 읽기가 어렵다고 말하는 것이 아니라 완전한 것으로 보입니다. 질문을 편집하고 거기에 PHP를 코드 블록으로 추가하십시오. – lanzz

답변

5

Google의 oAuth API 사용에 대해서는 잘 모르겠지만 지금까지 살펴본 예제에서 값 (예 : code, client_id 등)을 게시물에 전달해야합니다 필드가 아니라 HTTP 헤더에 직접.

다음 예제는 여전히 완전히 작동하지 않지만 invalid_request 오류가 발생하는 대신 invalid_grant을 제공합니다. 나는 (아마도 당신이 구글이나 뭔가의 새로운 자격 증명이 필요) 언급 한 내용 이외에 다른 문제가있는 생각하지만,이, 한 걸음 더 가까이 당신을 얻을 수있는 최소한 :

$post = array(
    "grant_type" => "authorization_code", 
    "code" => "your_code", 
    "client_id" => "your_client_id", 
    "client_secret" => "your_client_secret", 
    "redirect_uri" => "http://localhost/curl_resp.php" 
); 

$postText = http_build_query($post); 

$url = "https://accounts.google.com/o/oauth2/token"; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postText); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 

$result = curl_exec($ch); 
var_dump($result); // gets an error, "invalid_grant" 
+2

그냥 명확히하기 위해 일반적으로 "invalid_grant"코드가 있습니다 : your_code가 만료되었거나 폐기되었거나 이미 access_token을 부여하는 데 사용되었습니다 (한 번 사용할 수 있음)) –

+0

Thanks @Antonio ... 그 부분은 나에게 분명하지 않았습니다. 모든. – greg7gkb

+0

이 답변은 매우 유용하지만 인증 코드를 취소하거나 새 코드를 얻는 방법에 대해 질문이 있습니다. –

1

데 :

POST 요청에는 Content-length 헤더가 필요합니다.

+0

$ text = 'test'; $ URL = "https://accounts.google.com/o/oauth2/token"; $ header = array ( "POST/o/oauth2/token HTTP/1.1", "Host : accounts.google.com", "콘텐츠 유형 : application/atom + xml; charset = \"utf- 8 \ "", "수락 : 텍스트/XML을" "캐시 - 제어 : 노 캐시", "코드 = [my_code] CLIENT_ID = [my_client_id] client_secret = [my_client_secret] redirect_uri로 =에 http : // localhost를/curl_resp.php & grant_type = authorization_code ", "Content-length : ".strlen ($ text), ); –

+0

헤더에 content-length를 사용했지만 작동하지 않았습니다. –

+0

액세스 토큰을 얻기 위해 Google api php client 라이브러리를 사용했으며 저에게 적합했습니다. –

0

은 왜 CURLOPT_POST 거짓로 설정해야합니까?

curl_setopt($xml_do, CURLOPT_POST, false); 

컬의 일부 구성이 자동으로 CURLOPT_POSTFIELDS가 설정되어있는 경우 트루로 변경되지만, 유효한 postfield이 없습니다.

HTTP "POST"작업에 게시 할 전체 데이터입니다. 파일을 게시하려면 파일 이름 앞에 @를 붙이고 전체 경로를 사용하십시오. 파일 유형은 '; type = mimetype'형식의 파일 이름을 따라 명시 적으로 지정할 수 있습니다. 이 매개 변수는 'para1 = val1 & para2 = val2 & ...'과 같이 URL 인코딩 된 문자열로 전달되거나 필드 이름이 키이고 값이 필드 데이터 인 배열로 전달할 수 있습니다. value가 배열이면 Content-Type 헤더가 multipart/form-data로 설정됩니다. PHP 5.2.0부터 @ 접두사를 사용하여 파일을이 옵션에 전달하면 값이 배열이어야합니다.

param = value 구문 또는 배열이 전달되어야합니다.

0

내가 사용한 후 배열 CURL 메서드 및 유효한 Google 코드 및 나를 위해 일했습니다

0

또한 Google은 "invalid_xxx"반환 동일한 문제가있었습니다.

많은 연구와 문제 해결 후에 문제는 양식 자체의 인코딩에 있습니다! 'http_builder_query'함수를 사용하지 마십시오. 문자열이 엉망이되어 google이 '인식'할 수 없기 때문입니다. 예 :

http_builder_query 출력 : "code = 4 % 252FYYUT71KJ6 ..."

단지 일반 문자열에 비해

: "코드 = 4/YYUT71KJ6 ... "여기

내가 위치에 'x'를 배치 한 내 작업 코드입니다 (google oauth authentication에서 가져온 수정) 자신의 데이터를

$code_from_user_login = "4/YYUT71KJ6...."; 
    $ch = curl_init(); 

     curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token"); 
     curl_setopt($ch, CURLOPT_POST, TRUE); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 


     $post_params = "code=" . $code_from_user_login . "&"; 
     $post_params .= "redirect_uri=http://www.x.com/&"; 
     $post_params .= "client_id=x.apps.googleusercontent.com&"; 
     $post_params .= "client_secret=x&"; 
     $post_params .= "grant_type=authorization_code&"; 


     curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params); 
     $result = curl_exec($ch); 
     print($result); 

필요가있는 결과가 될 것 같은 :

당신은 'access_token은'하면
'{ 
    "access_token" : "ya29.AHES6ZSwJSHpTZ1t....", 
    "token_type" : "Bearer", 
    "expires_in" : 3599, 
    "id_token" : "eyJhbGciOiJSUzI1NiIsImtpZCI6IjU0MDQxOTZlMmQzOGNjYTA2MW...." 
}' 

,이 URL을 사용하여 프로파일 데이터에 액세스 : https://www.googleapis.com/oauth2/v1/userinfo?access_token=YOUR_ACCESS_TOKEN_HERE

~ 끝 ~

관련 문제