Here is my code to get the traffic stats from my Google Postmaster account. It works perfectly without the date parameters, but as soon as I add a startDate it doesn't work anymore
$url = 'https://gmailpostmastertools.googleapis.com/v1/domains/'.$this_domain.'/trafficStats/?pageSize=9999&startDate=20221001&endDate=20221030';
$ch = curl_init();
$headers = array(
'Authorization: Bearer ' . $token,
'Accept: application/json'
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING , "");
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$google_postmaster_api_json = curl_exec($ch);
$google_postmaster_api = json_decode($google_postmaster_api_json, true);
echo "<pre>";
var_dump($google_postmaster_api);
echo "</pre>";
if the StartDate parameter is added, the API returns this error:
Invalid JSON payload received. Unknown name "startDate": Cannot bind query parameter. 'startDate' is a message type. Parameters can only be bound to primitive types.
Invalid JSON payload received. Unknown name "endDate": Cannot bind query parameter. 'endDate' is a message type. Parameters can only be bound to primitive types.
If I try to POST it as a json instead, the result returned is NULL even if there should be data returned
$json_request = '{
"dateRanges": [{ "startDate": "2022-10-01", "endDate": "2022-10-15" }],
}';
$ch = curl_init();
$headers = array(
'Authorization: Bearer ' . $token,
'Accept: application/json'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_request);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING , "");
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$google_postmaster_api_json = curl_exec($ch);
As per the documentation (although I have to say it's not 100% clear) the "startDate" and "endDate" parameters are actually composites, and to generate a valid request you must specify each component of those dates (year, month and day) as separate parameters in your URL, in this format:
startDate.day=X&startDate.month=X&startDate.year=X&endDate.day=X&endDate.month=X&endDate.year=X
(where X is of course replaced by a valid numeric value for each parameter).
The documentation entries for "startDate" and "endDate" show the type as "Object (Date)", where the "Date" is a link to the Date section of the documentation where it describes the individual fields which make up a date for the purposes of the API requests.
I was able to confirm this by using the "Try this method" part of the documentation to generate a request to the API, and the Network tool in my browser showed the URL it generated as a result of submitting the request from the form, and the date portions of the URL querystring matched the format I've shown above.
P.S. It definitely does not support sending the data in JSON format via a POST request though. The documentation is clear that it must be a GET request and that the request body must be empty.
Related
i have curl command provided by some developer, i need to know how to call it in php.
Command is :
curl -H "x-api-key: xxxxxxxxxxxxxxxxxxxxxx"
"https://api.civicengine.com/office-
holders?address=1060+W+Addison+Chicago+IL"
i have written this
$data['api-key']='xxxxxxxxxxxxxxxxxxxxx';
/*$data['host']='https://api.civicengine.com';*/
$url='https://api.civicengine.com/office-holders?address=1060+W+Addison+Chicago+IL';
$ch = curl_init();
// set basic auth
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// set header accept
$headers = array('Accept:application/json', 'Accept-Language:en_US',"Authorization: Bearear xxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// set mode to POST
curl_setopt($ch, CURLOPT_POST, 1);
// add post fields (1)
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
print_r($result = json_decode(curl_exec($ch)));die;
i expect result but its giving
stdClass Object ( [message] => Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=FLUdjGvxuJ9liutivB0Ll5LW2t2xmv31lvK2guQi )
you forgot to add the x-api-key header to your php curl_ code. also your php code is altering the Accept Accept-Language, and Authorization header, your curl invocation proves that's not needed, and they may be incorrect to boot (idk), get rid of them while debugging (and once everything is working, you may add them back and check that they don't break anything..)
Follow this method to send api_key in header of API REQUEST
// Collection object
$ch = curl_init($url);
$headers = array(
"APIKEY: PUT_HERE_API_KEY",
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml"
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlreq);
$result = curl_exec($ch); // execute
$result;
//show response
curl_close($ch);
good evening,
I'm already breaking my head for 3 days I'm trying to send a message with the button from a page with a bot made in CURL PHP
I'm trying with CURL and PHP POST GRAPH
without success both of us can help me?
function SendRawResponse($Rawresponse){
$userPageConversation = 't_100005050355547';
$Access_token = "XXXX";
$url = "https://graph.facebook.com/v2.6/".$userPageConversation."/messages?access_token=".$Access_token;
//$url = "https://graph.facebook.com/v2.6/me/messages?access_token=".$Access_token;
$ch = curl_init($url);
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'charset=utf-8',
);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $Rawresponse);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($Rawresponse));
//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse));
curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
$erros = curl_errno($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
var_dump($erros);
var_dump($response);
curl_close($ch);
}
Mensage:
$teste = '{
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Try the postback button!",
"buttons":[
{
"type":"web_url",
"title":"GOOGLE",
"url":"https://www.google.com.br"
}
]
}
}
}}';
SendRawResponse($teste);
erros:
Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse)); = Missing message body
According to the docs
you must add domain to the whitelist in FB page settings.
Domains must meet the following requirements to be whitelisted:
Served over HTTPS
Use a fully qualified domain name, such as
https://www.messenger.com/. IP addresses and localhost are not
supported for whitelisting.
trying to make an API request via curl. The API docs say I must make a POST request as follows:
POST url
Headers:
Content-Type: “application/json”
Body:
{
Context: {
ServiceAccountContext: "[Authorization Token]"
},
Request:{
Citations:[
{
Volume: int,
Reporter: str,
Page: int
}
]
}
}
Here is my curl request:
$postFields = array(
'Volume' => int,
'Reporter' => str,
'Page' => int,
'ServiceAccountContext' => $API_KEY
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json"));
curl_setopt($ch, CURLOPT_POST, count($postFields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$output=curl_exec($ch);
But the API is not recognizing that I have submitted the API_KEY through a POST Field. The error I am getting back is to create a SecurityContext object, which I assume is something to do with the part of the POST body talking about Context and ServiceAccountContext.
I have looked in the cURL documentation and have not seen how I can set this. Any suggestions? Thanks a bunch.
The problem is that you use CURL options improperly. According to manual, when you set CURLOPT_POSTFIELDS option to an array, CURL forces Content-Type header to multipart/form-data. i.e. the line where you set CURLOPT_HTTPHEADER option is ignored.
You have to convert $postFields to JSON string by json_encode function before passing it to CURLOPT_POSTFIELDS option:
...
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
...
I am trying to do a free/busy query on a Google Resource Calendar (Google Apps). The API documentation for Freebusy query gives these directions about the request:
HTTP Request:
POST https://www.googleapis.com/calendar/v3/freeBusy
Request Body Structure:
{ "timeMin": {datetime},
"timeMax": {datetime},
"items": [
{"id": {string}
}
]
}
Here's my attempt, using curl:
$url = "https://www.googleapis.com/calendar/v3/freeBusy";
global $headers; // holds ClientLogin authentification
$freebusy_post = array(
"timeMin" => '2012-12-31T00:00:00',
"timeMax" => '2013-01-08T23:00:00',
"timeZone" => 'America/New York',
/*** "items" below commented out because posting a multidimensional array returns an
"Array to string conversion" error. However, I think the API requires
"items" to be an array. ***/
//"items" => array(
// "id" => "https://www.googleapis.com/calendar/v3/calendars/gdev.wellesley.edu_313736333535343332#resource.calendar.google.com"
// )
/*** My attempt at using a plain string instead of an array ***/
"items" => "gdev.wellesley.edu_313736333535343332#resource.calendar.google.com",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $freebusy_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
print_r($data);
My problem: $data doesn't print anything.
I'm brand new to PHP, curl, and the Google Apps Calendar API. I'd love any help/ lessons/ advice you can offer!
Not sure, but you have probably to convert the php array to a json first.
$freebusyjson = json_encode($freebusy_post);
i started with your code and modified it and the following worked for me...
Note how i formatted the calendar ID in the item variable. I also only needed to attach an API key to the URL as it is a public calendar. I don't think I needed it initially, but then I reached the number of requests that could be made without using an API key.
Finally, note the format of the Time/Date. I'm saying this is the only way to do it, but it worked for me.
$url = "https://www.googleapis.com/calendar/v3/freeBusy/?key=MY_API_KEY";
$freebusy_post = array(
"timeMin" => '2016-11-01T00:00:00.000Z',
"timeMax" => '2016-12-21T00:00:00.000Z',
"timeZone" => ' America/New York',
"items" => array(array('id'=>"mywebsite.com_randomlettershere#group.calendar.google.com")),
);
$freebusy_post = json_encode($freebusy_post);
$ch = curl_init();curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $freebusy_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
print_r($data);
I am using below post method for google account using curl but it gives me invalid_request error.
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
Here is my PHP code with curl
$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);
And I am having invalid request error
I don't know anything about using Google's oAuth API, but from the examples that I have looked at so far, it looks like you are supposed to pass the values (i.e. code, client_id, etc.) in the post fields, not directly in the HTTP header.
The following example still doesn't work completely, but instead of getting a invalid_request error, it gives you invalid_grant. I think there is something else wrong in addition to what I've mentioned (perhaps you need new credentials from Google or something), but this might get you one step closer, at least:
$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"
The response to your request actually includes a very readable description of the problem:
POST requests require a Content-length header.
Why do you have CURLOPT_POST set to false?
curl_setopt($xml_do, CURLOPT_POST, false);
Although some configurations of cURL will automatically change this to tru if CURLOPT_POSTFIELDS is set, you do not have a valid postfield.
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix.
It should either be in param=value syntax or an array passed.
I have used post array in CURL method and valid Google code and it worked for me
I was also having the same problem, where google returns an "invalid_xxx".
After much researching and troubleshooting, the problem lies with the encoding of the form itself! Do not use function 'http_builder_query', as it messses up the string and google cannot 'recognise' it. Example :
http_builder_query Output : "code=4%252FYYUT71KJ6..."
compared to
just a normal string : "code=4/YYUT71KJ6..."
Here is my working code, where i have placed 'x' in the locations that needs your own data (taken and modified from 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);
The result will be like :
'{
"access_token" : "ya29.AHES6ZSwJSHpTZ1t....",
"token_type" : "Bearer",
"expires_in" : 3599,
"id_token" : "eyJhbGciOiJSUzI1NiIsImtpZCI6IjU0MDQxOTZlMmQzOGNjYTA2MW...."
}'
Once you have the 'access_token', access the profile data with this url :
https://www.googleapis.com/oauth2/v1/userinfo?access_token=YOUR_ACCESS_TOKEN_HERE
~ end ~