I create web application that will work with Google Calendar.
I use Guzzle for http requests.
I successfully authorized and got token.
I have some trouble when i tried to add event in some calendar.
$url = 'https://www.googleapis.com/calendar/v3/calendars/'. $calendar_id .'/events';
$client = new Guzzle\Http\Client();
$data = json_encode(array(
"end" => array("date" => "2015-04-02"),
"start" => array("date" => "2015-04-01"),
"summary" => "test3"
));
$request = $client->post($url, [], $data);
$request->setHeader('Authorization', $token_type . ' ' . $token);
$response = $request->send();
echo $response->getBody();
The response is
Client error response [status code] 400 [reason phrase] Bad Request [url] https://www.googleapis.com/calendar/v3/calendars/some_calendar/events
Please explain me what is wrong?
Thanks a lot!
I think you meant to do
use Guzzle\Http\Client;
$url = 'https://www.googleapis.com/calendar/v3/calendars/'. $calendar_id .'/events';
$client = new GuzzleClient($url);
Related
I have been trying to implement Google reCAPTCHA v3 by using the following PHP source code:
<script src="https://www.google.com/recaptcha/api.js?render=6Ldl-98fAAAAAKRPodblUlTcVgvrfWZ_8lODjmZA"></script>
<?php
if(isset($_POST) && isset($_POST["btnSubmit"]))
{
$secretKey = '6Ldl-98fAAAAAD3ekajHHVBi2X4fZTW37bI5IGUN';
$token = $_POST["g-token"];
$ip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = array('secret' => $secretKey, 'response' => $token, 'remoteip'=> $ip);
// use key 'http' even if you send the request to https://...
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data)
));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
if($response->success)
{
echo '<center><h1>Validation Success!</h1></center>';
}
else
{
echo '<center><h1>Captcha Validation Failed..!</h1></center>';
}
}
?>
The problem is that every time I run this and step through the code line by line, I notice that the file_get_contents() function is always returning false and is assigning false to the '$result' variable. Why is this?
$result = file_get_contents($url, false, $context);
I would appreciate any advice that I can get.
From docs: 'null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.'
Show us $response, so var_dump($response). In recaptcha v2 i had empty string or token lately. That's why I ask for response, json decode will decode if there is proper json value.
I'd bet you get empty result and json_decode fails.
I am facing an issue while sending API requests to by HTTP Client. I am getting a Pending Request. How to fulfill the response and get the response data from $response->collect()
here is my code:
public function postMultipleFiles($url, $files, $params)
{
$response = Http::withHeaders([
'Authorization' => auth()->check() ? 'Bearer '.auth()->user()->api_token:''
]);
foreach($files as $k => $file)
{
$response = $response->attach('images['.$k.']', $file);
}
$response->post($this->base_url.$url, $params);
return response()->json($response->collect());
}
The error I am getting
message: "Method Illuminate\\Http\\Client\\PendingRequest::collect does not exist."
I have this code :
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$curlHandle = curl_init('http://url.com');
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_POST, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $httpParams);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($curlHandle);
curl_close($curlHandle);
dump($curlResponse);die();
I have the response in $curlResponse with status = 200
But when I tried with Http from laravel :
$http = Http::asForm();
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$response = $http->send('post', 'http://url.com', $httpParams)->body();
dump($response);
Response is empty : "". The status is 200. Can you help me please, why using Http facade I have empty response ? Thx in advance. Please help me !!!
You can write reusable method inside separate class
public function apiCall($url, $method = "get",$data=[])
{
$htppCall = Http::withHeaders([
'Content-Type' => 'application/json',
])->{$method}($url,$data);
if ($htppCall->status() == 401) {
//error handling
}
return $htppCall->object();
}
Then call like this
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$response=$this->apiCall($url,'post',$httpParams);
dd($response);
Import right facade
use Illuminate\Support\Facades\Http;
checking what status code you got
$htppCall->status()
to get data as object
$htppCall->object()
To get data as array
$htppCall->json()
To check client errors
$htppCall->clientError()
to check server errors
$htppCall->serverError()
To Get the body of the response.
$htppCall->body()
If any issues let me know in comment
I'm trying to retrieve the value of a URL but it returns a null response. Not sure what I'm doing wrong I've been trying to retrieve the value but I get an empty value. Below is my code
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://fantasy.premierleague.com/api/bootstrap-static/');
dd($response->getBody()->getContents());
When trying to dump the response I get the below response
When trying to read the getBody() of the response I get this output
I'm using guzzle "guzzlehttp/guzzle": "^6.4"
OK I found the solution to my problem. It's got nothing to do with
$response->getBody()->getContents()
But the problem was the Endpoint/URL might require a user agent as part of the parameter of the url
my code I was able to retrieve the value using the code below
$url = 'https://fantasy.premierleague.com/api/bootstrap-static/';
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', $url, [
'verify' => false,
'headers' => [
'User-Agent' => 'CUSTOM_AGENT_YOU_WANT' // THIS IS WHAT I ADDED TO MAKE IT WORK
]
]);
dd(json_decode($response->getBody()->getContents(), true));
I'm trying to obtain an access token from Google so I can use a 'service account' to upload videos to YouTube automatically.
This code:
$credentials = array(
'client_id' => $my_client_id
);
$jwt = JWT::encode($credentials, $private_key);
$client = new Google_Client();
if ($client->authenticate($jwt))
{
// do something
}
Fails with this exception:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_request: Client must specify either client_id or client_assertion, not both'' in /home/google/client/google-api-php-client/src/Google/Auth/OAuth2.php:120
Where am I going wrong?
TY!
I had missed a large section of the documentation as shown here:
https://developers.google.com/accounts/docs/OAuth2ServiceAccount#creatingjwt
I had also missed that the algorithm had to be RSA256 not HSA256 as defaulted to in the JWT PHP encode function.
And further, that I needed to POST a request, appropriately, directly to get an access token to endpoint:
https://www.googleapis.com/oauth2/v3/token
The Google private JSON private key for the service account also was invalid for use by openssl due to the final character being encoded/included as:
\u003d
Swapping this, literally, with:
=
solved that problem.
Here is my now working (ish, see closing statement) code:
$claimset = array(
'iss' => $client_email,
'scope' => 'https://www.googleapis.com/auth/youtube.upload',
'aud' => 'https://www.googleapis.com/oauth2/v3/token',
'exp' => time() + 1800,
'iat' => time(),
'sub' => 'my google account email#gmail.com'); // not sure if reqd
$jwt = JWT::encode($claimset, $private_key, 'RS256');
// Now need to get a token by posting the above to:
// https://www.googleapis.com/oauth2/v3/token
# Our new data
$data = array(
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt
);
# Create a connection
$url = 'https://www.googleapis.com/oauth2/v3/token';
$ch = curl_init($url);
# Form data string
$postString = http_build_query($data, '', '&');
# Setting our options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Get the response
$response = curl_exec($ch);
curl_close($ch);
print "and here is what we got: ";
print_r($response);
exit;
Unfortunately, for some reason the response I'm getting is:
{ "error": "unauthorized_client", "error_description": "Unauthorized client or scope in request." }
Suspect my service account does not yet have the right to upload to YouTube.
I'm not an experr, but you should probably look at removing the "," at the end of you line here:
'client_id' => $private_key['client_id'],
//'client_email' => $private_ket['client_email']
change to:
'client_id' => $private_key['client_id']
//'client_email' => $private_ket['client_email']
I've used this example to get oauth working. It may be helpful:
http://msdn.microsoft.com/en-us/library/dn632721.aspx
you could also try oauth testing here:
https://developers.google.com/oauthplayground/
Good luck!