PayPal 400 Неверный запрос

Я попытался реализовать вход через PayPal. По сути, я просто скопировал этот пример: Как реализовать вход пользователя в PayPal. Тем не менее, я получаю ошибку 400 - Bad Request для второго ответа (в файле включения входа в систему PayPal). Я не могу сделать большую часть ошибки, может быть, кто-то знает, что случилось. Результат:

object(Httpful\Response)#14 (13) {
  ["body"]=>
  string(0) ""
  ["raw_body"]=>
  string(0) ""
  ["headers"]=>
  object(Httpful\Response\Headers)#15 (1) {
    ["headers":"Httpful\Response\Headers":private]=>
    array(10) {
      ["date"]=>
      string(29) "Sun, 23 Jul 2017 13:30:12 GMT"
      ["server"]=>
      string(6) "Apache"
      ["paypal-debug-id"]=>
      string(13) "bcd5c7f1d86b2"
      ["www-authenticate"]=>
      string(255) "Bearer error_description="GET /v1/oauth2/token/userinfo?schema=openidconnect returned a response status of 400 Bad Request",correlation_id="1283a4f54dc2a",error="400",information_link="https://developer.paypal.com/docs/api/#errors",realm="UserInfoService""
      ["set-cookie"]=>
      string(52) "X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT"
      ["vary"]=>
      string(29) "Accept-Encoding,Authorization"
      ["connection"]=>
      string(5) "close"
      ["http_x_pp_az_locator"]=>
      string(11) "sandbox.slc"
      ["transfer-encoding"]=>
      string(7) "chunked"
      ["content-type"]=>
      string(29) "text/html; charset=ISO-8859-1"
    }
  }
  ["raw_headers"]=>
  string(983) "HTTP/1.1 400 Bad Request
Date: Sun, 23 Jul 2017 13:30:12 GMT
Server: Apache
Paypal-Debug-Id: 1283a4f54dc2a
WWW-Authenticate: Bearer error_description="GET /v1/oauth2/token/userinfo?schema=openidconnect returned a response status of 400 Bad Request",correlation_id="1283a4f54dc2a",error="400",information_link="https://developer.paypal.com/docs/api/#errors",realm="UserInfoService"
Set-Cookie: Apache=10.72.108.11.1500816612903307; path=/; expires=Tue, 16-Jul-47 13:30:12 GMT
Vary: Accept-Encoding,Authorization
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: bcd5c7f1d86b2
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D1880%26app%3Didentityspartaweb_api%26TIME%3D3835982937%26HTTP_X_PP_AZ_LOCATOR%3Dsandbox.slc; Expires=Sun, 23 Jul 2017 14:00:12 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Transfer-Encoding: chunked
Content-Type: text/html; charset=ISO-8859-1"
  ["request"]=>
  object(Httpful\Request)#13 (22) {
    ["uri"]=>
    string(80) "https://api.sandbox.paypal.com/v1/identity/openidconnect/userinfo/?schema=openid"
    ["method"]=>
    string(3) "GET"
    ["headers"]=>
    array(2) {
      ["Authorization"]=>
      string(97) "A23AAHJ_6sujsm8hanJJWRQ8WqIjhbVvxqG-Z3g4Te3QzwkVdw6cLWgCeidGOgPng0kFx24dYlCoWhZNKlhTuDs-_knOqOERQ"
      ["Content-Length"]=>
      int(0)
    }
    ["raw_headers"]=>
    string(493) "GET /v1/identity/openidconnect/userinfo/?schema=openid HTTP/1.1
Host: api.sandbox.paypal.com
Expect:
User-Agent: Httpful/0.2.19 (cURL/7.47.0 PHP/7.0.18-0ubuntu0.16.04.1 (Linux) nginx/1.10.0 Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0)
Content-Type: application/json
Accept: */*; q=0.5, text/plain; q=0.8, text/html;level=3;
Authorization: A23AAHJ_6sujsm8hanJJWRQ8WqIjhbVvxqG-Z3g4Te3QzwkVdw6cLWgCeidGOgPng0kFx24dYlCoWhZNKlhTuDs-_knOqOERQ
Content-Length: 0
"
    ["strict_ssl"]=>
    bool(false)
    ["content_type"]=>
    string(16) "application/json"
    ["expected_type"]=>
    NULL
    ["additional_curl_opts"]=>
    array(0) {
    }
    ["auto_parse"]=>
    bool(true)
    ["serialize_payload_method"]=>
    int(2)
    ["username"]=>
    string(80) "[I removed this.]"
    ["password"]=>
    string(80) "[I removed this.]"
    ["serialized_payload"]=>
    NULL
    ["payload"]=>
    NULL
    ["parse_callback"]=>
    NULL
    ["error_callback"]=>
    NULL
    ["send_callback"]=>
    NULL
    ["follow_redirects"]=>
    bool(false)
    ["max_redirects"]=>
    int(25)
    ["payload_serializers"]=>
    array(0) {
    }
    ["_ch"]=>
    resource(4) of type (Unknown)
    ["_debug"]=>
    NULL
  }
  ["code"]=>
  int(400)
  ["content_type"]=>
  string(9) "text/html"
  ["parent_type"]=>
  string(9) "text/html"
  ["charset"]=>
  string(10) "ISO-8859-1"
  ["meta_data"]=>
  array(26) {
    ["url"]=>
    string(80) "https://api.sandbox.paypal.com/v1/identity/openidconnect/userinfo/?schema=openid"
    ["content_type"]=>
    string(29) "text/html; charset=ISO-8859-1"
    ["http_code"]=>
    int(400)
    ["header_size"]=>
    int(987)
    ["request_size"]=>
    int(486)
    ["filetime"]=>
    int(-1)
    ["ssl_verify_result"]=>
    int(0)
    ["redirect_count"]=>
    int(0)
    ["total_time"]=>
    float(0.919636)
    ["namelookup_time"]=>
    float(5.1E-5)
    ["connect_time"]=>
    float(0.193331)
    ["pretransfer_time"]=>
    float(0.708154)
    ["size_upload"]=>
    float(0)
    ["size_download"]=>
    float(0)
    ["speed_download"]=>
    float(0)
    ["speed_upload"]=>
    float(0)
    ["download_content_length"]=>
    float(-1)
    ["upload_content_length"]=>
    float(-1)
    ["starttransfer_time"]=>
    float(0.919562)
    ["redirect_time"]=>
    float(0)
    ["redirect_url"]=>
    string(0) ""
    ["primary_ip"]=>
    string(11) "173.0.82.78"
    ["certinfo"]=>
    array(0) {
    }
    ["primary_port"]=>
    int(443)
    ["local_ip"]=>
    string(9) "10.0.2.15"
    ["local_port"]=>
    int(50988)
  }
  ["is_mime_vendor_specific"]=>
  bool(false)
  ["is_mime_personal"]=>
  bool(false)
  ["parsers":"Httpful\Response":private]=>
  NULL
}

Мой код: (ppinit.php просто определяет константы)

require_once(dirname(__FILE__)."/ppinit.php");

$requestData = '?grant_type=authorization_code&code='.getGet("code").'&return_url=http://localhost/paypal/return';

$response = \Httpful\Request::get("https://" . PAYPAL_API_URL . "/v1/identity/openidconnect/tokenservice" . $requestData)
->authenticateWith(PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET)
->send();

$jsonResponse = json_decode($response->raw_body);

if(isset($jsonResponse->error))
{
    echo "Fehler bei der Anmeldung mit PayPal.";
    echo "<br/>";
    exit;
}
//that's the one that does not work.
$response = \Httpful\Request::get("https://" . PAYPAL_API_URL . "/v1/identity/openidconnect/userinfo/?schema=openid")
->contentType("application/json")
->authorization($jsonResponse->access_token)
->authenticateWith(PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET)
->send();
$ppuser = json_decode($response);

person Addi    schedule 23.07.2017    source источник
comment
Поделитесь, пожалуйста, своим PHP-кодом. Мы не можем перейти к учебнику, чтобы найти соответствующий код :)   -  person hatef    schedule 23.07.2017
comment
Добавил код. Сомневаюсь, что это было бы очень полезно, так как по сути это точно код примера, за исключением некоторых констант.   -  person Addi    schedule 23.07.2017


Ответы (2)


Вообще говоря, неверный запрос HTTP 400 означает, что отправленный запрос был неправильно сформирован, т. е. поток данных, отправленный клиентом на сервер, не соответствовал правилам — подробнее.

Трудно указать точный источник таких ошибок, поскольку их может быть много, но я предлагаю вам обернуть ваши HTTP-вызовы в блоки try/catch и отследить причину ошибки. Итак, в этом случае вы можете заменить свой код следующим:

try {
    $response = \Httpful\Request::get("https://" . PAYPAL_API_URL . "/v1/identity/openidconnect/tokenservice" . $requestData)
        ->authenticateWith(PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET)
        ->send();
} catch (Exception $e) {
    var_dump($e->getMessage());
    exit(1);
}

Если вы используете пространство имен, поставьте \ перед Exception -> \Exception

person hatef    schedule 23.07.2017

Замена второго запроса приведенным ниже кодом работает.

try 
{
    $params = array('access_token' => $jsonResponse->access_token);
    $userInfo = OpenIdUserinfo::getUserinfo($params, $paypal);

} catch (Exception $ex) 
{
    echo $ex;
    exit(1);
}
person Addi    schedule 23.07.2017
comment
Хорошей практикой является всегда размещать вызовы внешних библиотек в блоках try/catch. - person hatef; 23.07.2017