PHP Guzzle Empty Response on Post Request - php

I'm implementing a Drupal WebForm Handler for posting data to the PayU
Web Checkout Integration after submission, after hours of trying I started to think there was a problem with the Guzzle Client, so I took off the code from Drupal to test separately. I used a simple Rest API GET request and worked fine, however this POST request still doesn't return anything and I've tried everything from working with streams to changing Guzzle versions as mentioned here. I've used Postman as well and things work fine there.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
require_once './vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
//use GuzzleHttp\Stream\Stream;
try {
$client = new Client();
//$post_url = $this->configuration['submission_url'];
$post_url = 'https://sandbox.gateway.payulatam.com/ppp-web-gateway';
//$response = $client->request('GET', $post_url);
$response = $client->request('POST', $post_url,[
'debug' => true,
'form_params' => [
'merchantId' => '508029',
'ApiKey' => '4Vj8eK4rloUd272L48hsrarnUA',
'referenceCode' => 'TestPayU',
'accountId' => '512326',
'description' => 'Test PAYU',
'amount' => '3',
'tax' => '0',
'taxReturnBase' => '0',
'currency' => 'USD',
'signature' => 'ba9ffa71559580175585e45ce70b6c37',
'test' => '1',
'buyerEmail' => 'test#test.com'
]
]);
//$response = Psr7\stream_for($response->getBody());
var_dump($response->getBody()->getContents());
}
catch(Exception $e) {
echo($e->getMessage());
}
This is the debug report. I'd appreciate any help. Thanks.
* Trying 69.20.41.99... * Connected to sandbox.gateway.payulatam.com
(69.20.41.99) port 443 (#0) * Cipher selection:
ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:#STRENGTH *
successfully set certificate verify locations: * CAfile:
/Applications/DevDesktop/common/cert/cacert.pem CApath: none * SSL
connection using TLSv1.2 / AES256-SHA256 * Server certificate: *
subject: OU=Domain Control Validated; OU=COMODO SSL Unified
Communications; CN=payulatam.com * start date: 2017-06-07 00:00:00 GMT *
expire date: 2019-06-05 23:59:59 GMT * subjectAltName:
sandbox.gateway.payulatam.com matched * issuer: C=GB; ST=Greater
Manchester; L=Salford; O=COMODO CA Limited; CN=COMODO RSA Domain
Validation Secure Server CA * SSL certificate verify ok. > POST /ppp-
web-gateway HTTP/1.1 Host: sandbox.gateway.payulatam.com User-Agent:
GuzzleHttp/6.2.1 curl/7.44.0 PHP/7.0.14 Content-Type: application/x-www-
form-urlencoded Content-Length: 234 * upload completely sent off: 234
out of 234 bytes < HTTP/1.1 302 Found < Set-Cookie:
JSESSIONID=79253C01031875A1B442649D8B824674.gateway-nodo1;
Path=/ppp-web-gateway/; Secure; HttpOnly < X-FRAME-OPTIONS:
SAMEORIGIN < Set-Cookie: cookie-pol-checkout-version_512326=V2;
Expires=Fri, 28-Sep-2018 22:54:23 GMT; Path=/ppp-web-gateway/;
Secure < Location: /ppp-web-gateway/page-redirect.zul < Content-
Length: 0 < Date: Tue, 03 Oct 2017 22:54:22 GMT < Server: PayU
server < * Connection #0 to host sandbox.gateway.payulatam.com left
intact * Found bundle for host sandbox.gateway.payulatam.com:
0x7918c650 * Re-using existing connection! (#0) with host
sandbox.gateway.payulatam.com * Connected to
sandbox.gateway.payulatam.com (69.20.41.99) port 443 (#0) > GET
/ppp-web-gateway/page-redirect.zul HTTP/1.1 Host:
sandbox.gateway.payulatam.com User-Agent: GuzzleHttp/6.2.1
curl/7.44.0 PHP/7.0.14 Content-Type: application/x-www-form-
urlencoded < HTTP/1.1 200 OK < Set-Cookie:
JSESSIONID=EF0110093412FCDF3E56DD15F1937F30.gateway-nodo1;
Path=/ppp-web-gateway/; Secure; HttpOnly < X-FRAME-OPTIONS:
SAMEORIGIN < Set-Cookie: cookie-
pol=pol_190_238_194_79_1507071263918; Domain=pagosonline.net;
Expires=Fri, 28-Sep-2018 22:54:23 GMT; Path=/; Secure < Content-
Language: en-US < Content-Length: 0 < Date: Tue, 03 Oct 2017
22:54:22 GMT < Server: PayU server < * Connection #0 to host
sandbox.gateway.payulatam.com left intact string(0) ""

Related

Firebase not firebase not respons : Transfer-Encoding: chunked < * Connection #1 to host fcm.googleapis.com left intact

i want to send push notification for all of them user install application with Firebase Admin PHP SDK library in drupal 8 in the request time i have below error.
my code:
$messaging = (new Factory())->withServiceAccount(__DIR__ . '/file .json')->withEnabledDebug()->withProjectId('project name')->createMessaging();
$config = AndroidConfig::fromArray([
'ttl' => '3600s',
'priority' => 'normal',
'notification' => [
'title' => '$GOOG up 1.43% on the day',
'body' => '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
'icon' => 'stock_ticker_update',
'color' => '#f45342',
'sound' => 'default',
],
]);
$title = 'My Notification Title';
$body = 'My Notification Body';
$imageUrl = 'http://lorempixel.com/400/200/';
$notification = Notification::fromArray([
'title' => $title,
'body' => $body,
'image' => $imageUrl,
]);
$topic = 'b-topic';
$message = CloudMessage::withTarget('topic', $topic)
->withAndroidConfig($config)
->withNotification($notification);
$messaging->send($message);
When I activate the log :
Hostname in DNS cache was stale, zapped
Trying 216.58.208.106...
TCP_NODELAY set
Connected to oauth2.googleapis.com (216.58.208.106) port 443 (#0)
ALPN, offering http/1.1
successfully set certificate verify locations:
CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
Your question couldn’t be submitted
SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
ALPN, server accepted to use http/1.1
Server certificate:
subject: C=US; ST=California; L=Mountain View; O=Google LLC; CN=upload.video.google.com
start date: Oct 20 18:07:22 2020 GMT
expire date: Jan 12 18:07:22 2021 GMT
subjectAltName: host "oauth2.googleapis.com" matched cert's
.googleapis.com"
issuer: C=US; O=Google Trust Services; CN=GTS CA 1O1
SSL certificate verify ok.
> POST /token HTTP/1.1
Host: oauth2.googleapis.com
User-Agent: GuzzleHttp/6.5.4 curl/7.58.0 PHP/7.4.11
Cache-Control: no-store
Content-Type: application/x-www-form-urlencoded
Content-Length: 1209
* upload completely sent off: 1209 out of 1209 bytes
< HTTP/1.1 200 OK < Content-Type: application/json; charset=UTF-8 < Vary: X-Origin < Vary: Referer < Date: Sat, 07 Nov
2020 07:14:17 GMT < Server: scaffolding on HTTPServer2 < Cache-Control: private < X-XSS-Protection: 0 <
X-Frame-Options: SAMEORIGIN < X-Content-Type-Options: nosniff < Alt-Svc: h3-Q050=":443" ; ma=2592000,h3-29=":443" ;
ma=2592000,h3-T051=":443" ; ma=2592000,h3-T050=":443" ; ma=2592000,h3-Q046=":443" ; ma=2592000,h3-Q043=":443" ;
ma=2592000,quic=":443" ; ma=2592000; v="46,43" < Accept-Ranges: none < Vary: Origin,Accept-Encoding <
Transfer-Encoding: chunked < * Connection #0 to host oauth2.googleapis.com left intact * Trying 64.233.177.95... *
TCP_NODELAY set * Trying 2a00:1450:400e:800::200a... * TCP_NODELAY set * Immediate connect fail for
2a00:1450:400e:800::200a: Network is unreachable * Trying 2a00:1450:400e:806::200a... * TCP_NODELAY set * Immediate
connect fail for 2a00:1450:400e:806::200a: Network is unreachable * Trying 2a00:1450:400e:809::200a... * TCP_NODELAY
set * Immediate connect fail for 2a00:1450:400e:809::200a: Network is unreachable * Trying
2a00:1450:400e:80d::200a... * TCP_NODELAY set * Immediate connect fail for 2a00:1450:400e:80d::200a: Network is
unreachable * Connected to fcm.googleapis.com (64.233.177.95) port 443 (#1) * ALPN, offering http/1.1 * successfully
set certificate verify locations: * CAfile: /etc/ssl/certs/ca-certificates.crt CApath: /etc/ssl/certs * SSL
connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 * ALPN, server accepted to use http/1.1 * Server certificate: *
subject: C=US; ST=California; L=Mountain View; O=Google LLC; CN=edgecert.googleapis.com * start date: Oct 20
18:13:46 2020 GMT * expire date: Jan 12 18:13:46 2021 GMT * subjectAltName: host "fcm.googleapis.com" matched
cert's "fcm.googleapis.com" issuer: C=US; O=Google Trust Services; CN=GTS CA 1O1 * SSL certificate verify ok.>
POST /v1/projects/pj name/messages:send HTTP/1.1
Host: fcm.googleapis.com
User-Agent: GuzzleHttp/6.5.4 curl/7.58.0 PHP/7.4.11
Content-Type: application/json; charset=UTF-8
authorization: Bearer
"token"
Content-Length: 396
* upload completely sent off: 396 out of 396 bytes
< HTTP/1.1 200 OK < Content-Type: application/json; charset=UTF-8 < Vary: X-Origin < Vary: Referer < Date: Sat, 07
Nov 2020 07:14:18 GMT < Server: ESF < Cache-Control: private < X-XSS-Protection: 0 < X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff < Alt-Svc: h3-Q050=":443" ; ma=2592000,h3-29=":443" ;
ma=2592000,h3-T051=":443" ; ma=2592000,h3-T050=":443" ; ma=2592000,h3-Q046=":443" ; ma=2592000,h3-Q043=":443" ;
ma=2592000,quic=":443" ; ma=2592000; v="46,43" < Accept-Ranges: none < Vary: Origin,Accept-Encoding <
Transfer-Encoding: chunked < * Connection #1 to host fcm.googleapis.com left intact
i conected to google SDK but when i cant conected to fcm.googleapis.com and error to Transfer-Encoding .i try to ssl domain but not work again.

PHP Curl Error 35 - Peer reports incompatible or unsupported protocol version

I'm attempting to make POST requests to an external API(Code below). I manage to get the curl coding working on my localhost but when I go to my staging server the curl returns error Peer reports incompatible or unsupported protocol version(35). From reading into this I need to add an error buffer to get more debugging info but the documentation is confusing.
Yet when I make a curl request directly in the servers terminal with I receive a connection successful. Which makes me extremely confused as the server is clearly capable to make curl requests.
PHP Curl Code
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($body),
CURLOPT_HTTPHEADER => $header,
));
$response = curl_exec($curl);
$err = curl_error($curl);
echo "response: " . $response;
echo "<br><br>error: " . $err;
curl_close($curl);
Server Curl Response
curl https://support.zendesk.com/api/v2/users/create_or_update.json
* About to connect() to support.zendesk.com port 443 (#0)
* Trying 104.16.51.111...
* Connected to support.zendesk.com (104.16.51.111) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
* Server certificate:
* subject: CN= support.zendesk.com,O="CloudFlare, Inc.",L=San Francisco,ST=CA,C=US
* start date: Mar 08 00:00:00 2019 GMT
* expire date: Mar 08 12:00:00 2020 GMT
* common name: support.zendesk.com
* issuer: CN=CloudFlare Inc ECC CA-2,O="CloudFlare, Inc.",L=San Francisco,ST=CA,C=US
> GET /api/v2/users/create_or_update.json HTTP/1.1
> User-Agent: curl/7.29.0
> Host: support.zendesk.com
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Date: Fri, 12 Apr 2019 12:52:28 GMT
< Content-Type: application/json; charset=UTF-8
< Content-Length: 37
< Connection: keep-alive
< Set-Cookie: __cfduid=da0ecd56691c96b9b3dac091df58383d51555073548; expires=Sat, 11-Apr-20 12:52:28 GMT; path=/; domain=.ralphandrussoclientcare.zendesk.com; HttpOnly
< WWW-Authenticate: Basic realm="Web Password"
< Strict-Transport-Security: max-age=31536000;
< Cache-Control: no-cache
< X-Zendesk-Origin-Server: app23.pod17.euw1.zdsys.com
< X-Request-Id: 4c65566eacc82981-DUB
< X-Runtime: 0.032000
< X-Zendesk-Request-Id: 3360f95a861586e6f414
< Set-Cookie: __cfruid=7af98f1cbac97922c1c15b82f7c133c3945a446e-1555073548; path=/; domain=.ralphandrussoclientcare.zendesk.com; HttpOnly
< Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
< Server: cloudflare
< CF-RAY: 4c65566eacc82981-DUB
<
* Connection #0 to host support.zendesk.com left intact
{"error":"Couldn't authenticate you"}
In order to solve this problem I performed a server SSL test using https://www.ssllabs.com/ssltest/ which showed me which Protocols were already open and available on the server.
From that I followed the answer to this question TLS 1.2 not working in cURL which showed me which PHP CURLOPT_SSLVERSION number to use in order to access an open protocol.
Therefore I had to add the following line of code to my Curl Array
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2

How to open facebook, twitter page using PHP Curl

When I try to open url1(https://www.google.co.in), url2(https://www.amazon.com), url5(https://www.instagram.com) its working fine that is I can load url1, url2 and url5 but when I try to open url3(https://www.facebook.com), url4(https://www.twitter.com), its printing my error message:"Error, Unable to open." as it can't open facebook, twitter page. I dont want to use API. Thank you in advance.
<?php
$curl = curl_init();
//url1 = https://www.google.co.in
//url2 = https://www.amazon.com
//url3 = https://www.facebook.com
//url4 = https://www.twitter.com
//url5 = https://www.instagram.com
$url ="https://www.facebook.com";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
if($output)
{
echo $output;
}
else
{
echo "Error, Unable to open.";
}
?>
when debugging issues like that, enable CURLOPT_VERBOSE. furthermore, when debugging, don't use echo, use var_dump. if you did that, you'd see something like
* Rebuilt URL to: https://www.facebook.com/
* Trying 157.240.20.35...
* TCP_NODELAY set
* Trying 2a03:2880:f10a:83:face:b00c:0:25de...
* TCP_NODELAY set
* Immediate connect fail for 2a03:2880:f10a:83:face:b00c:0:25de: Network is unreachable
* Connected to www.facebook.com (157.240.20.35) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:#STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / ECDHE-ECDSA-AES128-GCM-SHA256
* ALPN, server accepted to use http/1.1
* Server certificate:
* subject: C=US; ST=California; L=Menlo Park; O=Facebook, Inc.; CN=*.facebook.com
* start date: Dec 15 00:00:00 2017 GMT
* expire date: Mar 22 12:00:00 2019 GMT
* subjectAltName: host "www.facebook.com" matched cert's "*.facebook.com"
* issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert SHA2 High Assurance Server CA
* SSL certificate verify ok.
> GET / HTTP/1.1
Host: www.facebook.com
Accept: */*
< HTTP/1.1 302 Found
< Strict-Transport-Security: max-age=15552000; preload
< Location: https://www.facebook.com/unsupportedbrowser
< Content-Type: text/html; charset=UTF-8
< X-FB-Debug: x3NeeaaJHxPQkX5Z9H7yMX3evzYJocXmZpzMV6GoWtacO8bXLL3O58vidPHZUvXTuP9iE9pHPEnbr/RvNsT23Q==
< Date: Mon, 19 Feb 2018 09:12:51 GMT
< Connection: keep-alive
< Content-Length: 0
<
* Connection #0 to host www.facebook.com left intact
string(0) ""
the problem being that facebook tried to issue a HTTP redirect (to https://www.facebook.com/unsupportedbrowser), and you didn't follow it. enable CURLOPT_FOLLOWLOCATION to have curl automatically handle redirects. why did facebook redirect you? because you didn't supply any user-agent header. set one that facebook will recognize as supported with CURLOPT_USERAGENT, for example Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0 (aka Firefox 52 ESR running on Windows 7 x64)
as for twitter.com,
* Rebuilt URL to: https://www.twitter.com/
* Trying 104.244.42.193...
* TCP_NODELAY set
* Connected to www.twitter.com (104.244.42.193) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:#STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use http/1.1
* Server certificate:
* subject: businessCategory=Private Organization; jurisdictionC=US; jurisdictionST=Delaware; serialNumber=4337446; C=US; ST=California; L=San Francisco; O=Twitter, Inc.; OU=tsa_o Point of Presence; CN=twitter.com
* start date: Jul 25 00:00:00 2017 GMT
* expire date: Jul 30 12:00:00 2018 GMT
* subjectAltName: host "www.twitter.com" matched cert's "www.twitter.com"
* issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert SHA2 Extended Validation Server CA
* SSL certificate verify ok.
> GET / HTTP/1.1
Host: www.twitter.com
Accept: */*
< HTTP/1.1 301 Moved Permanently
< content-length: 0
< date: Mon, 19 Feb 2018 09:17:51 GMT
< location: https://twitter.com/
< server: tsa_o
< set-cookie: personalization_id="v1_ersTgWQIOjuJkjk6VFUlXw=="; Expires=Wed, 19 Feb 2020 09:17:51 UTC; Path=/; Domain=.twitter.com
< set-cookie: guest_id=v1%3A151903187127250514; Expires=Wed, 19 Feb 2020 09:17:51 UTC; Path=/; Domain=.twitter.com
< strict-transport-security: max-age=631138519
< x-connection-hash: aae827a6347e88db5f417a0c31bba366
< x-response-time: 101
<
* Connection #0 to host www.twitter.com left intact
string(0) ""
it tried to redirect you to the non-www url version of the site, and again, you didn't follow the redirect. enable CURLOPT_FOLLOWLOCATION to have curl automatically follow http redirects.

Guzzle ~6 and Google Place API - error when using pagination (pagetoken)

I'm trying to get a set of universities near a couple of locations (lat/lng).
To do so I'm using the Google Maps Places API Web Services and this small script in PHP with Guzzle ~6.0.
I'm using this code to fetch Google APIs:
$positions = [
[51.388667, 2.557513], // <- no next_page_token
[51.388667, 2.750000], // <- next_page_token
];
foreach($geo in $positions) {
getJsonPlacesResponse($geo);
}
function getJsonPlacesResponse($geo)
{
$lat = $geo[0];
$lng = $geo[1];
if ($lat == 'Latitude') return;
$r1 = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?key='.getenv('GMAPS_API_KEY').'&radius=50000'.'&type=university'.'&location='.$lat.','.$lng;
return getAndParse($r1);
}
function getAndParse($url)
{
$client = new GuzzleHttp\Client();
$body = $client->get($url, ['debug' => true])->getBody();
$obj = json_decode($body, true);
if ($obj['status'] !== 'OK') {
return [];
}
if (isset($obj['next_page_token'])) {
echo "--Get additionals results\n";
return array_merge($obj['results'], getAndParse($url."&pagetoken=".$obj['next_page_token']));
} else {
return $obj['results'];
}
}
This script works just fine exept when the response contain a "next_page_token", in that case the api return a HTTP/1.1 200 OK:
{
"html_attributions" : [],
"results" : [],
"status" : "INVALID_REQUEST"
}
By enabling the debug mode I can see the url in the console:
* Trying 216.58.204.234...
* TCP_NODELAY set
* Connected to maps.googleapis.com (216.58.204.234) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:#STRENGTH
* successfully set certificate verify locations:
* CAfile: C:\cacert.pem
CApath: none
* SSL connection using TLSv1.2 / ECDHE-ECDSA-AES128-GCM-SHA256
* ALPN, server accepted to use http/1.1
* Server certificate:
* subject: C=US; ST=California; L=Mountain View; O=Google Inc; CN=*.googleapis.com
* start date: Dec 13 13:18:44 2017 GMT
* expire date: Mar 7 13:01:00 2018 GMT
* subjectAltName: host "maps.googleapis.com" matched cert's "*.googleapis.com"
* issuer: C=US; O=Google Inc; CN=Google Internet Authority G2
* SSL certificate verify ok.
> GET /maps/api/place/nearbysearch/json?key=AIzaSyAjKv57vnxrBpHQHFjUj3kzjJtBHn3PwgA&radius=50000&type=university&location=51.388667,2.750000&pagetoken=CqQCGwEAAMzahTCyfdinn6yQR9l0qp3oTPeETilcXXNQoYf3BKN-Nolz7nPJmWDx4ydLl0ZG42jo52uYIDG1kmHTj3cvFK4boSfSWEuJHfeDVSkPjAgjyd9I
oqbu-TPvaioozcQwmfY7q7XA3_lhoiuvcZbHkUDm9ntx1ujBE1z4PjFIyMyuljY0E36-usj3f3Nq0VMBHGayLwnx9AraPyg-iMaSbDLjz5gKs2wYTz3mnKw-fhl064oI3MFWHi7u7d3PLDEyJ3m-YPZQ_tuqeIudpuc8GeItOzYMvnVD8nXYP0a12PyFx-2EeKutZlhZHtnRmRmHr74_Zzmx0dasuZMTI3Ot5y8j6EvCQhmo2CmLlj5mpedBIgnr_LDZBYqQn8YAdtk
izxIQ0G7SnNzr-chGUqQO6kwCQRoUmNgPs4xMYbYsQ0rdVsG-veFh31E HTTP/1.1
Host: maps.googleapis.com
User-Agent: GuzzleHttp/6.2.1 curl/7.55.0 PHP/7.1.10
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8
< Date: Mon, 15 Jan 2018 20:46:56 GMT
< Expires: Mon, 15 Jan 2018 20:51:56 GMT
< Cache-Control: public, max-age=300
< Server: scaffolding on HTTPServer2
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"
< Accept-Ranges: none
< Vary: Accept-Language,Accept-Encoding
< Transfer-Encoding: chunked
<
* Connection #0 to host maps.googleapis.com left intact
{
"html_attributions" : [],
"results" : [],
"status" : "INVALID_REQUEST"
}
But when I test the url /maps/api/place/nearbysearch/json?key=AIza...31E directly in Google Chrome, and it's just works fine: Screenshot of the Google Chrome Dev Tools.
And I don't know where is the problem!
I'm thinking about some url encoding issue, but I've read that guzzle already encode the url, so yep, I don't know.
Note: I have restricted the key access (IP based) so it shouldn't work with this specific key for you.
Thanks for any help.
Duplicate of Google Places API : next_page_token error
See this comment:
https://stackoverflow.com/a/20499757/8738918
And yes, adding a few delay resolve it.

Authentication issues with the Twitter API

I'm trying to display the latest tweets of a Twitter account on my website, and I'm trying to fetch the data using cURL and PHP. When I use the OAuth tool (signature generator) on the Twitter Developers website. There is a cURL command that is generated and it runs just fine on my terminal. However, when I try to use cURL with the same parameters in my PHP code, I get the following error :
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
Here is the cURL command :
curl --get 'https://api.twitter.com/1.1/statuses/user_timeline.json' --data 'count=2&screen_name=[my user name]' --header 'Authorization: OAuth oauth_consumer_key="[my key]", oauth_nonce="[my key]", oauth_signature="[the signature]", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1439736924", oauth_version="1.0"' --verbose
And here is my PHP code :
$ch = curl_init("https://api.twitter.com/1.1/statuses/user_timeline.json?count=2&screen_name=XXXXX");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization' => 'OAuth',
'oauth_consumer_key' => '[my key]',
'oauth_nonce' => '[my key]',
'oauth_signature' => '[the signature]',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => '1439736924',
'oauth_version' => '1.0')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'count' => 2,
'screen_name' => '[my username]')
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
echo curl_exec($ch);
The values are exactly the same and I don't understand why it works with the curl command but not in the PHP code. Here are the two logs :
cURL command (works fine):
* Connected to api.twitter.com (199.16.156.199) port 443 (#0)
* successfully set certificate verify locations:
* CAfile: none
CApath: /etc/ssl/certs/
* TLSv1.2, TLS handshake, Client hello (1):
* TLSv1.2, TLS handshake, Server hello (2):
* TLSv1.2, TLS handshake, CERT (11):
* TLSv1.2, TLS handshake, Server key exchange (12):
* TLSv1.2, TLS handshake, Server finished (14):
* TLSv1.2, TLS handshake, Client key exchange (16):
* TLSv1.2, TLS change cipher, Client hello (1):
* TLSv1.2, TLS handshake, Finished (20):
* TLSv1.2, TLS change cipher, Client hello (1):
* TLSv1.2, TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* Server certificate:
* subject: C=US; ST=California; L=San Francisco; O=Twitter, Inc.; OU=Twitter Security; CN=api.twitter.com
* start date: 2014-08-03 00:00:00 GMT
* expire date: 2016-12-31 23:59:59 GMT
* subjectAltName: api.twitter.com matched
* issuer: C=US; O=VeriSign, Inc.; OU=VeriSign Trust Network; OU=Terms of use at https://www.verisign.com/rpa (c)10; CN=VeriSign Class 3 Secure Server CA - G3
* SSL certificate verify ok.
> GET /1.1/statuses/user_timeline.json?count=2&screen_name=XXX HTTP/1.1
> User-Agent: curl/7.38.0
> Host: api.twitter.com
> Accept: */*
> Authorization: OAuth oauth_consumer_key="BBBBBB", oauth_nonce="CCCCCCCC", oauth_signature="DDDDDDDD", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1439736924", oauth_version="1.0"
>
< HTTP/1.1 200 OK
< cache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
< content-disposition: attachment; filename=json.json
< content-length: 7512
< content-type: application/json;charset=utf-8
< date: Sun, 16 Aug 2015 16:09:46 GMT
< expires: Tue, 31 Mar 1981 05:00:00 GMT
< last-modified: Sun, 16 Aug 2015 16:09:46 GMT
< pragma: no-cache
< server: tsa_b
< set-cookie: guest_id=v1%3A143974138658672554; Domain=.twitter.com; Path=/; Expires=Tue, 15-Aug-2017 16:09:46 UTC
< status: 200 OK
< strict-transport-security: max-age=631138519
< x-connection-hash: ae1b9fcc59bb90b767b246dfd06f6c94
< x-content-type-options: nosniff
< x-frame-options: SAMEORIGIN
< x-rate-limit-limit: 300
< x-rate-limit-remaining: 298
< x-rate-limit-reset: 1439741812
< x-response-time: 23
< x-transaction: 8515dfd151751885
< x-twitter-response-tags: BouncerCompliant
< x-xss-protection: 1; mode=block
<
PHP log (returns the error message):
* Hostname in DNS cache was stale, zapped
* Trying 199.16.156.199...
* Connected to api.twitter.com (199.16.156.199) port 443 (#0)
* successfully set certificate verify locations:
* CAfile: none
CApath: /etc/ssl/certs/
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* Server certificate:
* subject: C=US; ST=California; L=San Francisco; O=Twitter, Inc.; OU=Twitter Security; CN=api.twitter.com
* start date: 2014-08-03 00:00:00 GMT
* expire date: 2016-12-31 23:59:59 GMT
* subjectAltName: api.twitter.com matched
* issuer: C=US; O=VeriSign, Inc.; OU=VeriSign Trust Network; OU=Terms of use at https://www.verisign.com/rpa (c)10; CN=VeriSign Class 3 Secure Server CA - G3
* SSL certificate verify ok.
> GET /1.1/statuses/user_timeline.json?count=2&screen_name=XXXX HTTP/1.1
Host: api.twitter.com
Accept: */*
Authorization: OAuth
oauth_consumer_key: BBBBBB
oauth_nonce: CCCCCCC
oauth_signature: DDDDDDD
oauth_signature_method: HMAC-SHA1
oauth_timestamp: 1439740787
oauth_version: 1.0
< HTTP/1.1 400 Bad Request
< content-length: 62
< content-type: application/json; charset=utf-8
< date: Sun, 16 Aug 2015 16:26:50 GMT
< server: tsa_b
< set-cookie: guest_id=v1%3A143974241022741403; Domain=.twitter.com; Path=/; Expires=Tue, 15-Aug-2017 16:26:50 UTC
< strict-transport-security: max-age=631138519
< x-connection-hash: abbabb47dc8a7d355f595f389f868de2
< x-response-time: 4
<
* Connection #0 to host api.twitter.com left intact
Any help would be appreciated. If possible, I really would like to use cURL instead of a third party library.
Thanks
EDIT : Michael's solution didn't work, but here is the updated PHP output :
Authorization: OAuth oauth_consumer_key="...", oauth_nonce="...", oauth_signature="...", oauth_signature_method="HMAC-SHA1" oauth_timestamp= "1439744503", oauth_version= "1.0"
The chief difference between these is that in the CLI curl command, the Authorization header is specified as a single string with multiple key=value pairs separated by commas. But in your PHP code you have specified those key=value pairs as multiple individual headers. You just need to add a single Authorization header with all of those values concatenated into one string.
The CLI request's header output:
Authorization: OAuth oauth_consumer_key="BBBBBB", oauth_nonce="CCCCCCCC", oauth_signature="DDDDDDDD", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1439736924", oauth_version="1.0"
The PHP request's header output differs:
Authorization: OAuth
oauth_consumer_key: BBBBBB
oauth_nonce: CCCCCCC
oauth_signature: DDDDDDD
oauth_signature_method: HMAC-SHA1
oauth_timestamp: 1439740787
oauth_version: 1.0
So the correct PHP to produce a comparable single-header string would be:
curl_setopt($ch, CURLOPT_HEADER, 0);
// All OAuth values in a single Authorization header string.
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization' => 'OAuth oauth_consumer_key="[my key]", oauth_nonce="[my key]", oauth_signature="[the signature]", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1439736924", oauth_version="1.0"'
)
);
// etc... Everything else should be fine as you have it

Categories