Alright I'm at the end of the rope here. I've tried just about everything to try to get this working. I've done Google OAUTH API calls before on web hosts and everything works great, but when I use the same scripts on my WAMP server, google does not reply to my cURL posts. I've tested cURL post by posting to my own server as well as to this server someone set up:
http://www.newburghschools.org/testfolder/dump.php
And it works just fine. Here's the script I'm using after I get the user to allow my application:
<?
//This script handles the response from google. If the user as authed the app, it will continue the process by formulating another URL request to Google to get the users information. If there was an error, it will simply redirect to index.
include_once($_SERVER['DOCUMENT_ROOT']."/../src/php/google/initialize.php");
if (!isset($_GET['error'])) {
//No error found, formulate next HTTP post request to get our auth token
//Set URL and get our data encoded for POST
$url = "https://accounts.google.com/o/oauth2/token";
$fields = array(
'code' => $_GET['code'],
'client_id' => $google['clientID'],
'client_secret' => $google['clientSecret'],
'redirect_uri' => "http://www.dealertec.com/scripts/php/google/reg_response.php",
'grant_type' => "authorization_code"
);
//$data = http_build_query($fields);
$data = "code=".$fields['code'].'&client_id='.$fields['client_id'].'&client_secret='.$fields['client_secret'].'&redirect_uri='.$fields['redirect_uri'].'&grant_type='.$fields['grant_type'];
echo $data."<br> /";
//Begin cURL function
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response;
curl_close($ch);
//Decode the JSON and use it to make a request for user information
print_r($response);
$response = json_decode($response, true);
/*if (!isset($response['error'])) {
//No error in response, procede with final step of acquiring users information
$apiURL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=".$response['access_token'];
$apiCall = curl_init($apiURL);
curl_setopt($apiCall, CURLOPT_RETURNTRANSFER, true);
curl_setopt($apiCall, CURLOPT_HEADER, false);
$apiResponse = curl_exec($apiCall);
$apiResponse = json_decode($apiResponse, true);
var_dump($apiResponse);
}else{
echo $response['error'];
}*/
}else{
header("LOCATION: http://www.dealertec.com/");
}
?>
When I echo out what is supposed to be the google response, all I get is a singular "/". When I run this same exact script on my webhost, after changing back the DNS IP, it works fine. I'm thinking either Google doesn't like my WAMP server and won't even talk to it, or perhaps it's something with my cURL configuration. It's only a minor annoyance not being able to develop for Google API on my WAMP server, but if anyone has any ideas whatsoever, it would be greatly appreciated.
Thanks!
I was getting a FALSE coming back from curl_exec(), but this is how I fixed it:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
http://us3.php.net/manual/en/function.curl-setopt.php
hope this helps!
Related
I want to build a WhatsApp bot, for that, we are using Gupshup WhatsApp bot API, for integration they asked to give a callback URL, so created index.php in cPanel of one domain(https://sample_url/WhatsappBot/index.php), and gave the URL (https://sample_url/WhatsappBot/). As per their API documentation, they will pass a response to that URL, so I want to fetch that. Here is the remaining part of API documentation API documentation2, API documentation3, API documentation4. So I created one curl.php named file, that code is given below.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://sample_url/WhatsappBot/');
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch))
{
echo 'Error:' . curl_error($ch) ."\n";
}
else
{
$result_value = json_decode($result,true,JSON_PRETTY_PRINT);
echo $result_value;
// var_dump($result_value);
}
curl_close($ch);
?>
they provided a collection of API for reference, but I am getting the wrong result. In their collection API have the result,
Collection API result
but I am getting this,
myresult
What is the wrong in this code? Can anyone please help me...
Your Callback URL should contain a program that receive a POST data as JSON, Go ahead to decode the JSON data, using the data received, proceed with what ever logic you plan to execute.
//this should be in your call back URL index.php
$post_data_expected = file_get_contents("php://input");
$decoded_data = json_decode($post_data_expected, true);
You can your POSTMAN to always test your callback URL to see it behaves the way you expects.
How can I send a pageview event via Measurement Protocol to a GA4 property with PHP?
This is how I'm doing, but inside my Google Analytics 4 property I can't see any traffic.
$data = array(
'api_secret' => 'XXXX-YYYYY',
'measurement_id' => 'G-12345678',
'client_id' => gen_uuid(), // generates a random id
'events' => array(
'name' => 'page_view',
'params' => array(),
)
);
$url = 'https://www.google-analytics.com/mp/collect';
$content = http_build_query($data);
$content = utf8_encode($content);
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch,CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
I'm working on registering pageviews to track API usage right now, here's what I've found:
XTOTHEL is right about setting the content type to content/json above. In addition to specifying the content type you also have to send JSON data as the CURLOPT_POSTFIELDS data.
Also per their specification the api_secret and measurement_id need to be part of the URI: https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag#required_parameters
Lastly, you can use debug mode to validate your responses and figure out what's going on now by simply changing the URL to google-analytics.com/debug/mp/collect
Here's the code I'm working with right now:
//retrieve or generate GA tracking id
if (empty($_COOKIE['_cid'])) {
setcookie('_cid', vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4)));
}
$data = '{"client_id":"'.$_COOKIE['_cid'].'","events":[{"name":"load_endpoint","params":{"page_location":"'.$request->fullUrl().'"}}]}';
echo '<pre>';
print_r($data);
$measurement_id = 'G-xxxxx';
$api_secret = 'xxxx';
$url = 'https://www.google-analytics.com/debug/mp/collect?api_secret='.$api_secret.'&measurement_id='.$measurement_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
This works to a certain extent. Currently it's registering the page view as a custom event instead of an actual pageview though. I'm still trying to figure out how to get them to come through as page views.
Follow up
After a little more debugging I figured out page views are actually working, they just weren't showing up in some of the views. The fix for that was to add page_title into the params:
$data = '
{
"client_id": "'.$_COOKIE['_cid'].'",
"events": [
{
"name": "page_view",
"params": {
"page_location": "'.$request->fullUrl().'",
"page_title": "'.$request->path().'"
}
}
]
}
';
A few extra notes for whoever comes next:
Debug mode did return some useful validation errors for invalid top-level parameters (client_id, events) - but it didn't return errors for anything inside of the "params" for events. IE - i put "page_asdtitle" instead of "page_title" and it accepted it just fine.
None of the tests I sent through actually showed up in the debug panel while using debug mode. I suspect this is because of the data propagation delay, it's probably not loading realtime data.
Using a JSON validator can help. Make sure you use objects and arrays where GA tells you to.
If you get stuck figuring out why your PHP code doesn't work, write the code as a browser event in JavaScript and run it in your browser. There's tons of examples on how to do that. From there, you can use Dev Tools -> Network to inspect the request. If you right click on the google analytics request to the 'collect' endpoint you'll see an option to Copy Request as CURL. Put that into a text editor and compare it to what your PHP code is sending.
To ACTUALLY test this without the massive propagation delay you can login to Google Analytics, go to Reports -> Realtime, and you should see your data show up within 30-60 seconds if it's working. Realtime data will NOT show up if you're using the /debug/ endpoint though.
I am trying to get a token to use the Microsoft Graph API (https://learn.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0) via Curl. I have set up a simple Php file with this function:
function getToken() {
echo "start gettoken";
var_dump(extension_loaded('curl'));
$jsonStr = http_build_query(Array(
"client_id" => "***",
"scope" => "https://graph.microsoft.com/.default",
"client_secret" => "***",
"grant_type" => "client_credentials"
));
$headers = Array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($jsonStr));
$ch = curl_init("https://login.microsoftonline.com/***.onmicrosoft.com/oauth2/v2.0/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$token = curl_exec($ch);
echo "test after curl";
return $token;
curl_error($ch);
}
However, what I want to know is why the curl request is not working. Also the echo after the curl codeblock is not being executed, while 'start gettoken' is. PHP_curl is enabled in my WAMP. Why is this?
Are you sure CURL is enabled because that code you have posted is ok and giving echo response before and after curl execution.
you're sending the token request in a JSON-format, and then you're lying to the server saying it's application/x-www-form-urlencoded-encoded when it's actually application/json-encoded! since these 2 formats are completely incompatible, the server fails to parse it, and... ideally it should have responded HTTP 400 bad request (because your request can't be parsed as x-www-form-urlencoded)
anyhow, to actually send it in the application/x-www-form-urlencoded-format, replace json_encode() with http_build_query()
also get rid of the "Content-Length:"-header, it's easy to mess up (aka error-prone) if you're doing it manually (and indeed, you messed it up! there's supposed to be a space between the : and the number, you didn't add the space, but the usual error is supplying the wrong length), but if you don't do it manually, then curl will create the header for you automatically, which is not error-prone.
trying to send post request to api, to get an image back.
example url:
https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php?user=1003123&format=png&cloudid=asdasdasd&pass=123123123
the above url works fine in the browser,
the api doesnt care if the request is get/post,
result of my code is always 'invalid input'.
code:
$url='https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php';
$u = rand();
$p = rand();
$fields = array(
'user'=> urlencode($u),
'pass'=> urlencode($p),
'format'=> urlencode('jpg'),
'cloudid' => urlencode('test')
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
on a side note: is there a way to debug the request in order to see what is being sent ?
The URL provided isn't working for POST request. Here is resulting screenshot (I tried using Advance Rest Client)
However Its working perfectly with GET method. So you can continue using GET request method to generate QR code.
I agree that GET isn't much secure compare to POST method but in your case while requesting from curl user won't get to know about such URL parameters (userid, password). Because curl request will be sending from your web server and not from client/user's browser.
Later you can just output the response image you got from the api.
I'm working to understand how to get the results of a Instagram Subscription that looks for a specific tag. Ultimately, what I would like to do is as images are posted with the tag I'm looking for add the link to the photo as well as the username to a database.
I was able to create my subscription no problem but now I'm not sure how to get the POST information from the subscription.
Working with two files...subscribe.php and callback.php
subscribe.php
<?php
//ALL YOUR IMPORTANT API INFO
$client_id = 'XXX';
$client_secret = 'XXX';
$object = 'tag';
$object_id = 'taglookingfor';
$aspect = 'media';
$verify_token='';
$callback_url = '(full URL here)/callback.php';
//SETTING UP THE CURL SETTINGS...
$attachment = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'object' => $object,
'object_id' => $object_id,
'aspect' => $aspect,
'verify_token' => $verify_token,
'callback_url'=>$callback_url
);
//URL TO THE INSTAGRAM API FUNCTION
$url = "https://api.instagram.com/v1/subscriptions/";
$ch = curl_init();
//EXECUTE THE CURL...
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
curl_close ($ch);
//PRINT THE RESULTS OF THE SUBSCRIPTION, IF ALL GOES WELL YOU'LL SEE A 200
print_r($result);
?>
callback.php
<?php
if (isset ($_GET['hub_challenge'])){
echo $_GET['hub_challenge'];
}
//This is an update
else {
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
echo $answer;
}
?>
In my callback.php I'm attempting to echo out the results of the json_decode...but that also begs the question how will I catch that echo? Sorry, this might be really silly but how do I catch the moment when the callback.php script is being fired by a new image with the specific tag I'm looking for. As I mentioned what I hope to do is take the info in the $answer and insert some of the info into a database.
I'm new at this so any help would be greatly appreciated.
Thanks a million!!
I feel your pain. Their API isn't the easiest to work with and their documentation leaves lot to be desired. That said, this is what happens:
You send a request to the subscription API endpoint
Instagram sends a response to your callback.php file
The response contains a hub_challenge parameter that you need to echo to confirm your subscription
If it's successful you will get a post to your callback.php with the subscriptionid of your new subscription
Everytime you get a post to your callback.php you need to fire a request to Instagram for their latest media that matches your tag.
i think your callback url is not able to receive any post data, you may try to post something to your callback url
I hope this answer of mine will be helpful to people having similar problem.