What do I need to do in my PHP file so that my Telegram bot replies to my message in a quote? - telegram-bot

I want to make a bot that responds to my message on Telegram.
In fact, the bot I wrote responds to me, but it does not respond by quoting my message.
What do I need to do in my PHP file so that my Telegram bot replies to my message in a quote?
This is my Lowercase Converter Bot's code:
<?php
$website = 'https://api.telegram.org/bot{API}/';
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (isset($update["message"])){
$chatID = $update["message"]["chat"]["id"];
$text = $update["message"]["text"];
if ( $text == '/start' ) {
// send welcome message
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=Send your Text for Converting to Lowercase");
}else{
$text = mb_strtolower($text,"UTF-8");
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=$text");
}
}
?>

You have to specify the reply_to_message_id parameter with the message_id of the message you sent to the bot in the sendMessage request.
<?php
$website = 'https://api.telegram.org/bot{API}/';
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (isset($update["message"])) {
$chatID = $update["message"]["chat"]["id"];
$text = $update["message"]["text"];
$message_id = $update["message"]["message_id"];
if ($text == '/start') {
// send welcome message
file_get_contents($website . "sendMessage?chat_id=" . $chatID . "&text=Send your Text for Converting to Lowercase");
} else {
$text = mb_strtolower($text, "UTF-8");
file_get_contents($website . "sendMessage?chat_id=" . $chatID . "&text=$text&reply_to_message_id=$message_id");
}
}
?>

Related

Google oAuth not working after 3600 seconds

I'm using google oAuth for getting youtube latest streaming. It works for 3600 seconds. But then it stopped working. After some researching at stackoverflow, many people wrote to use "SetAccessType": "offline" .
I did it but same result.
Here is my snippet.
<?php
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
$stream_id = "";
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
$OAUTH2_CLIENT_ID = '972289696318-q037nr25oti8gs5h7hcj5lfkl7erklh6.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'cbmQyfeXWGb93RkN7KSHLQKB';
$client = new Google_Client();
$client->setAccessType('online');
$client->setClientId($OAUTH2_CLIENT_ID);
//$client->setExpires_in('10000000');
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
//print_r($youtube);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
/*
if ($client->isAccessTokenExpired()) {
$refreshToken = $client->getRefreshToken();
//print_r($refreshToken);
// $client->refreshToken($refreshToken);
$newAccessToken = $client->getAccessToken();
$newAccessToken['refresh_token'] = $refreshToken;
file_put_contents($credentialsPath, json_encode($newAccessToken));
}
*/
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Execute an API request that lists broadcasts owned by the user who
// authorized the request.
//print_r($youtube);
$broadcastsResponse = $youtube->liveBroadcasts->listLiveBroadcasts(
'id,snippet',
array(
'mine' => 'true',
));
//print_r($broadcastsResponse);
$htmlBody .= "<h3>Live Broadcasts</h3><ul>";
$count = 0;
foreach ($broadcastsResponse['items'] as $broadcastItem) {
// print_r($count+1);
$count = $count+1;
if($count == 1) {
$htmlBody .= sprintf('<li>%s (%s)</li>', $broadcastItem['snippet']['title'],
$broadcastItem['id']);
$stream_id = $broadcastItem['id'];
}
// print_r($broadcastItem);
}
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'Replace_me') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>My Live Broadcasts</title>
</head>
<body>
<?php echo $stream_id; ?>
</body>
</html>
Any idea what can i do?
NB: My purpose is, any one can authenticate here and can get latest youtube streaming id. But I'm struct with oAuth after 3600 seconds.
:(
Your Access Token has an expiry time. The expiry usually is half an hour (1800 seconds), although this can vary. The value is set by the Authentication Server. The expiry time is sent to you along with the Access Token.
After the Access Token expires, the server will no longer accept it. You must request a new one using your Refresh Token. You should have gotten it along with the first Access Token.
If you do not have a Refresh Token, you'll have to log in again.

Missing file in my email when doing resumable upload with gmail api

I'd like to have some help because I'm a bit lost right now.
I'm trying to send attachment with my email through resumable upload. But when I check my email in my inbox, I don't see any file. So I've probably forgot something.
Here's my code. So if someone see something ^^
$send_data = 'From: <FROM_EMAIL>' . "\n";
$send_data = 'To: <TO_EMAIL>' . "\n";
$send_data = 'Subject: <SUBJECT>' . "\n";
$send_data = '' . "\n";
$send_data = '<MY MESSAGE>' . "\n";
$send_data= rtrim(strtr(base64_encode($send_data), '+/', '-_'), '=');
$msg = new \Google_Service_Gmail_Mesage();
$msg->setRaw($send_data);
$this->client->setDefer(true);
$request = $this->service->users_messages->send('me', $msg, array('uploadType' => 'resumable'));
$chunkSizeBytes = 1 * 1024 * 1024;
$media = new \Google_Http_MediaFileUpload(
$this->client,
$request,
'message/rfc822',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize(TEST_FILE));
$status = false;
$handle = fopen(TEST_FILE, "rb");
$i = 0;
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
$result = false;
if($status != false) {
$result = $status;
}
fclose($handle);
$this->client->setDefer(false);
Thanks
I don't know much about gmail api, but I feel like setRaw() will need you to compose the full email (include the attachment) instead just of "body".

Got problems with webhook to Telegram Bot API

Why is my webhook not working? I do not get any data from telegram bot API. Here is the detailed explanation of my problem:
I got SSL cert from StartSSL, it works fine on my website (according to GeoCerts SSL checker), but still seems like my webhook to Telegram Bot API doesn't work (despite it says that webhook was set I do not get any data).
I am making a webhook to my script on my website in this form:
https://api.telegram.org/bot<token>/setWebhook?url=https://mywebsite.com/path/to/giveawaysbot.php
I get this text in response:
{"ok":true,"result":true,"description":"Webhook was set"}
So it must be working, but it actually doesn't.
Here is my script code:
<?php
ini_set('error_reporting', E_ALL);
$botToken = "<token>";
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents('php://input');
$update = json_decode($update);
print_r($update); // this is made to check if i get any data or not
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
switch ($message) {
case "/test":
sendMessage($chatId,"test complete");
break;
case "/hi":
sendMessage($chatId,"hey there");
break;
default:
sendMessage($chatId,"nono i dont understand you");
}
function sendMessage ($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
file_get_contents($url);
}
?>
I don't actually receive any data to $update. So webhook is not working. Why?
Just another one moment, why your webhooks not work.
In my case the reason was in allowed_updates webhook parameter.
By calling :
https://api.telegram.org/bot<your_bot_token>/getWebhookInfo
You can see
{
"ok": true,
"result": {
"url": "<your webhook url should be here>",
"has_custom_certificate": false,
"pending_update_count": 0,
"max_connections": 40,
"allowed_updates": [
"callback_query"
]
}
}
It means, that your bot can't react to your text messages, and you will not receive any webhooks!
You can note, that "allowed_updates" contains array. So, currently it will react only to inline button events (passed as keyboard layout!). According to the setWebhook documentation, allowed_updates is an "optional" parameter.
To start receieve text messages, you need to add "message" to your "allowed_updates" prop. To do it, just again set your webhooks and add it to query. Like here :
https://api.telegram.org/bot<your_token>/setWebHook?url=<your_url>&allowed_updates=["callback_query","message"]
You will receive something like "url already added", but don't worry, allowed_updates will be updated even in this case. Just try type your message to bot and test your webhooks.
That's all, now, telegram will send webhooks to each direct message from you to your bot. Hope, it helps someone.
I was with this problem. I was trying to look everywhere and couldn't find the solution for my problem, because people were all the time saying that the problem was the SSL certificate. But I found the problem, and that were a lot of things missing on the code to interact with the telegram API webhook envolving curl and this kind of stuff. After I looked in an example at the telegram bot documentation, I solved my problem. Look this example https://core.telegram.org/bots/samples/hellobot
<?php
//telegram example
define('BOT_TOKEN', '12345678:replace-me-with-real-token');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
function apiRequestWebhook($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
header("Content-Type: application/json");
echo json_encode($parameters);
return true;
}
function exec_curl_request($handle) {
$response = curl_exec($handle);
if ($response === false) {
$errno = curl_errno($handle);
$error = curl_error($handle);
error_log("Curl returned error $errno: $error\n");
curl_close($handle);
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) {
// do not wat to DDOS server if something goes wrong
sleep(10);
return false;
} else if ($http_code != 200) {
$response = json_decode($response, true);
error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
if ($http_code == 401) {
throw new Exception('Invalid access token provided');
}
return false;
} else {
$response = json_decode($response, true);
if (isset($response['description'])) {
error_log("Request was successfull: {$response['description']}\n");
}
$response = $response['result'];
}
return $response;
}
function apiRequest($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
foreach ($parameters as $key => &$val) {
// encoding to JSON array parameters, for example reply_markup
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
$url = API_URL.$method.'?'.http_build_query($parameters);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
return exec_curl_request($handle);
}
function apiRequestJson($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
$handle = curl_init(API_URL);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
return exec_curl_request($handle);
}
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
if (strpos($text, "/start") === 0) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
'keyboard' => array(array('Hello', 'Hi')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
} else if ($text === "Hello" || $text === "Hi") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
} else if (strpos($text, "/stop") === 0) {
// stop now
} else {
apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool'));
}
} else {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages'));
}
}
define('WEBHOOK_URL', 'https://my-site.example.com/secret-path-for-webhooks/');
if (php_sapi_name() == 'cli') {
// if run from console, set or delete webhook
apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL));
exit;
}
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (!$update) {
// receive wrong update, must not happen
exit;
}
if (isset($update["message"])) {
processMessage($update["message"]);
}
?>
I had similar problem. Now solved.
The problem is possibly in a wrong public certificate. Please follow with attention instructions I propose in my project:
https://github.com/solyaris/BOTServer/blob/master/wiki/usage.md#step-4-create-self-signed-certificate
openssl req -newkey rsa:2048 -sha256 -nodes -keyout /your_home/BOTServer/ssl/PRIVATE.key -x509 -days 365 -out /your_home/BOTServer/ssl/PUBLIC.pem -subj "/C=IT/ST=state/L=location/O=description/CN=your_domain.com"
Telegram setWebhooks API do not check data inside your self-signed digital certificate, returning "ok" even if by example you do not specify a valid /CN! So be carefull to generate a public .pem certificate containing /CN=your_domain corresponding to your REAL HOST domain name!
It may be the SSL cert. I had the same problem: Webhook confirmed but actually SSL cert borked.
This reddit thread was helpful: https://www.reddit.com/r/Telegram/comments/3b4z1k/bot_api_recieving_nothing_on_a_correctly/
This may help who works with Laravel Telegram SDK.
I had a problem with self-signed webhook in Laravel 5.3.
After setup and getting OK result from Telegram with "Webhook was set" message, it didn't work.
The problem was related to CSRF verification. So I added the webhook url to CSRF exceptions and now everything works like a charm.
I had this problem too, after somehow the telegram didn't run my bot, so I tried to renew the certificate and set web hooks again, but again it didn't work, so I updated my VPS(yum update) and then renew my certificate and set web hooks again. after these it started working again.
This is because you are not setting the certificate like this
curl -F "url=https://bot.sapamatech.com/tg" -F "certificate=#/etc/apache2/ssl/bot.pem" https://api.telegram.org/bot265033849:AAHAs6vKVlY7UyqWFUHoE7Toe2TsGvu0sf4/setWebhook
Check this link on how to set Telegram Self Signed Certificate
Try this code. If you have a valid SSL on your web host and you have properly run the setWebhook, it should work (does for me). Make sure you create a file called "log.txt" and give write permission to it:
<?php
define('BOT_TOKEN', '????');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
// compose reply
$reply ="";
switch ($message) {
case "/start":
$reply = "Welcome to Siamaks's bot. Type /help to see commands";
break;
case "/test":
$reply = "test complete";
break;
case "/hi":
$reply = "hey there";
break;
case "/help":
$reply = "commands: /start , /test , /hi , /help ";
break;
default:
$reply = "NoNo, I don't understand you";
}
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);
// Create a debug log.txt to check the response/repy from Telegram in JSON format.
// You can disable it by commenting checkJSON.
checkJSON($chatID,$update);
function checkJSON($chatID,$update){
$myFile = "log.txt";
$updateArray = print_r($update,TRUE);
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, $chatID ."nn");
fwrite($fh, $updateArray."nn");
fclose($fh);
}
I had this problem too. In my case was mistake in declaring my API method. I created GET method instead of POST at first.
#api.route('/my-webhook-url')
class TelegramWebhook(Resource):
def post(self): # POST, Carl!
# ...
return response
In my case the error was due to the PHP configuration ( using cPanel )
[26-Jan-2021 09:38:17 UTC] PHP Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/myUsername/public_html/mydomain.com/my_bot_file.php on line 40
and
[26-Jan-2021 09:38:17 UTC] PHP Warning: file_get_contents(https://api.telegram.org/bot<my-bot-id>/sendmessage?chat_id=647778451&text=hello charlie ! k99 ): failed to open stream: no suitable wrapper could be found in /home/myUsername/public_html/myDomain.com/my_bot_file.php on line 40
so - it is pretty self explanatory.
The allow_url_fopen=0 var in the php configuration actually disables the requiered action.
But anyhow your best bet is to look at the error log on your server and see if there are any other errors in the script or server config.

PayPal PDT SSL connection hangs up on my addon domain

On my PayPal autoReturn page with a known-to-work PHP script to accommodate Payment Data Transfer, no matter what I do I keep getting this error message: "Warning: fgets(): SSL: Connection reset by peer...*(on the line where this is: '$line = fgets($fp, 1024);'* "
Before I ask my question, let me just say that I've tried everything suggested here and in any other forum or article that I've been advised to read, e.g. changing HTTP 1.0 to HTTP 1.1, using $res=stream_get_contents($fp, 1024) instead of the while loop with $line = fgets($fp, 1024), etc., etc. My problem persists.
Here's what I think might be the problem (and I'm hoping someone can tell me if I'm on the right track): My auto return page for PDT is on an add-on site and I'm thinking that PayPal hangs up when the shared SSL (for my primary domain on a shared server) isn't recognized. So I've asked my web host for SSL to be installed specifically for my add-on domain.
Could the add-on domain SSL thing be the reason for my warning message? Again, that message is: "Warning: fgets(): SSL: Connection reset by peer...*(on the line where this is: '$line = fgets($fp, 1024);'* "
Here's my code:
//look if the parameter 'tx' is set in the GET request and that it does not have a null or empty value
if(isset($_GET['tx']) && ($_GET['tx'])!=null && ($_GET['tx'])!= "") {
$tx = $_GET['tx'];
verifyWithPayPal($tx);
}
else {
exitCode();
}
function verifyWithPayPal($tx) {
$req = 'cmd=_notify-synch';
$tx_token = $tx;
$auth_token = "MY SANDBOX AUTH_TOKEN HERE";
$req .= "&tx=$tx_token&at=$auth_token";
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
// url for paypal sandbox
//$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
// url for payal
// $fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
// If possible, securely post back to paypal using HTTPS
// Your PHP server will need to be SSL enabled.
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
exitCode();
} else {
fputs($fp, $header . $req);
// read the body data
$res = '';
$headerdone = false;
while (!feof($fp)) {
$line = fgets($fp, 1024);
// $res=stream_get_contents($fp, 1024);
if (strcmp($line, "\r\n") == 0) {
// read the header
$headerdone = true;
}
else if ($headerdone) {
// header has been read. now read the contents
$res .= $line;
}
}
// parse the data
$lines = explode("\n", $res);
$response = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$response[urldecode($key)] = urldecode($val);
}
$itemName = $response["item_name"];
$amount = $response["payment_gross"];
$myEmail = $response["receiver_email"];
$userEmailPaypalId = $response["payer_email"];
$paymentStatus = $response["payment_status"];
$paypalTxId = $response["txn_id"];
$currency = $response["mc_currency"];
// check the payment_status is Completed
if($paymentStatus!="Completed") {
payment_complete();
emailer($userEmailPayPalID);
} else {
payment_incomplete($paymentStatus);
}
/*
// check that txn_id has not been previously processed
checkIfTransactionHasAlreadyBeenProcessed($paypalTxId);
// check that receiver_email is your Primary PayPal email
checkThatPaymentIsReceivedAtYourEmailAddress($myEmail);
// check that payment_amount/payment_currency are correct
checkPaymentAmountAndCurrency($amount, $currency);
// process the order
processOrder();
} else {
exitCode();
*/
}
}
fclose ($fp);
}
I notice you're connecting to www.sandbox.paypal.com. I believe you want to connect to api.sandbox.paypal.com.

Google Plus Login API not working on production server

I have implemented the google plus api on development server and it works fine. I used the same code on production server. But after requesting the permission it takes a long time to return to my site and login.
Can anyone please let me know what might be the cause. I have used oauth2.
Below is the code I am using
<?php
session_start();
require_once 'googleplus/src/Google_Client.php';
require_once 'googleplus/src/contrib/Google_Oauth2Service.php';
class Webpage_UserGPlusLogin extends Webpage
{
public function __construct()
{
$temp_redirect = $_SESSION['RETURN_URL_AFTERLOGIN'];
$this->title = 'User Account';
$client = new Google_Client();
$client->setApplicationName(WEBSITE_NAME);
$client->setClientId(GOOGLE_PLUS_CLIENT_ID); // Client Id
$client->setClientSecret(GOOGLE_PLUS_CLIENT_SECRET); // Client Secret
$client->setRedirectUri(GOOGLE_PLUS_REDIRECT_URI); // Redirect Uri set while creating API account
$client->setDeveloperKey(GOOGLE_PLUS_DEVELOPER_KEY); // Developer Key
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = GOOGLE_PLUS_REDIRECT_URI;
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); // Redirects to same page
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if(!isset($_SESSION['email_address_user_account'])) // Check if user is already logged in or not
{
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get(); // Google API call to get current user information
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$img = filter_var($user['picture'], FILTER_VALIDATE_URL);
$googleuserid = $user['id'];
$given_name = $user['given_name'];
$family_name = $user['family_name'];
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
// If email address is present in DB return user data else insert user info in DB
$this->result = UserAccount::gplus_sign_up($email, $googleuserid, $given_name, $family_name);
// Create new user object.
$this->user_account = new UserAccount($this->result['id'],$this->result['email_address'],$this->result['password'],$this->result['confirmation_code'],$this->result['is_confirmed'], $this->result['first_name'], $this->result['last_name']);
$_SESSION['gplus_email_address'] = $email;
$_SESSION['gplus_first_name'] = $given_name;
$_SESSION['gplus_last_name'] = $family_name;
$_SESSION['gplus_id'] = $googleuserid;
$_SESSION['gplus_profile_pic'] = $img;
$_SESSION['email_address_user_account'] = $email;
} else {
$authUrl = $client->createAuthUrl();
}
}
if(isset($temp_redirect))
header("Location:".$temp_redirect);
else
header("Location:/");
}
}
Thanks in advance
Try this
use following code
$temp = json_decode($_SESSION['token']);
$request = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$request);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_TIMEOUT,30);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Authorization: OAuth '.$temp->access_token));
$response = trim(curl_exec($curl));
$info = curl_getinfo($curl);
$request_header_info = curl_getinfo($curl, CURLINFO_HEADER_OUT);
//var_dump($info);
//var_dump($request_header_info);
curl_close($curl);
echo "<pre>";
print_r(json_decode($response));
instade of
$user = $oauth2->userinfo->get(); // Google API call to get current user information`enter code here`
Hope this will help you .. :)