I am trying to get in a Google spreadsheet via the PHP API Client, but I am getting a 404->You need permission. The file has been given edit permissions to my user, which is the user I used to set up the JSON credentials via the Google Developers Console. What am I missing?
Here is my code :
$this->client = new Google_Client();
$this->client->setApplicationName('BreezingForms Google Drive Spreadsheets');
$this->client->addScope(array('https://spreadsheets.google.com/feeds'));
// testing:
// 197794184197-bt2q9knrdu1i54vgladd97ob196k4c6s.apps.googleusercontent.com
// dImciIWj3WNOrIcYRbu9MFeA
if (isset($_POST['gdata_custom_client_id']) && trim($_POST['gdata_custom_client_id']) != '' && trim($_POST['gdata_custom_client_secret']) != '') {
$this->client->setClientId(trim($_POST['gdata_custom_client_id']));
$this->client->setClientSecret(trim($_POST['gdata_custom_client_secret']));
$db->setQuery("Update #__breezingforms_addons_gdata Set custom_client_id = " . $db->quote(trim($_POST['gdata_custom_client_id'])) . ", custom_client_secret = " . $db->quote(trim($_POST['gdata_custom_client_secret'])) . " Where form_id = " . intval($_REQUEST['form']));
$db->execute();
} else {
$form_id = -1;
if(JRequest::getInt('ff_form',-1) > 0){
$form_id = JRequest::getInt('ff_form',-1);
}else if(isset($_REQUEST['form'])){
$form_id = intval($_REQUEST['form']);
}
$db->setQuery("Select * From #__breezingforms_addons_gdata Where form_id = " . $db->quote($form_id));
$client = $db->loadObject();
if ($client) {
$this->client->setClientId($client->custom_client_id);
$this->client->setClientSecret($client->custom_client_secret);
}
}
$this->client->setApprovalPrompt('auto');
$this->client->setPrompt('consent');
$this->client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$this->client->setAccessType('offline');
}
function onPropertiesDisplay($form_id, $tabs){
if(!$form_id) return '';
$error = '';
$db = JFactory::getDBO();
$db->setQuery("Select `title`,`name`,`id` From #__facileforms_elements Where form = " . intval($form_id) . " And `title` Not In ('bfFakeTitle','bfFakeTitle2','bfFakeTitle3','bfFakeTitle4','bfFakeTitle5') And `type` Not In ('','UNKNOWN') Order By ordering");
$breezingforms_fields = $db->loadObjectList();
$db->setQuery("Select `enabled`, `username`, `password`, `worksheet_id`, `spreadsheet_id`, `fields`, `meta`, `debug` From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$gdata = $db->loadObject();
if( $gdata === null ){
$gdata = new stdClass();
$gdata->username = '';
$gdata->password = '';
$gdata->enabled = 0;
$gdata->worksheet_id = '';
$gdata->spreadsheet_id = '';
$gdata->fields = '';
$gdata->meta = '';
$gdata->debug = 0;
}
$gdata->fields = explode('/,/', $gdata->fields);
$gdata->meta = explode('/,/', $gdata->meta);
$gdata_spreadsheets = array();
$gdata_worksheets = array();
$gdata_columns = array();
//if( $gdata->enabled == 1 ){
try{
$spreadsheetFeed = null;
$auth_url = '';
$db->setQuery("Select password From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$accessToken = $db->loadResult();
// $accessToken='{"access_token":"ya29.a0ARrdaM--_ZKuuOfK3CyRsAubHXYgGlwMhLfg9x10fLbYhOq0Polqela1GjGYjhBO9Fi0v7LKuDauV4qA-uFLCilun0_NuQDuEFHjYb9iX0rcOjS6YWMDTHfe2UsyxJkyvlULrMIV7sh4_-_-vORj0kh6sw7o","expires_in":3599,"refresh_token":"1\/\/09aQ4SG_STBzBCgYIARAAGAkSNwF-L9Ir9FDHRmbwiLoCXglVSksa1tfyes6AdQedbTx2dqZKGh-ZTMT-M2i665x18NzT1luWu1Q","scope":"https:\/\/www.googleapis.com\/auth\/spreadsheets","token_type":"Bearer","created":1635842294}';
if(!$accessToken){
$auth_url = $this->client->createAuthUrl();
} else {
try{
$this->client->setAccessToken($accessToken);
$token = json_decode($accessToken);
if ($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($token->refresh_token);
$tok = json_encode($this->client->getAccessToken());
$token = json_decode($tok);
$db->setQuery("Update #__breezingforms_addons_gdata set password = " . $db->quote($tok) . " Where form_id = " . intval($form_id));
$db->execute();
}
$serviceRequest = new DefaultServiceRequest($token->access_token, $token->token_type);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
}catch(Exception $ee){
//$accessToken = null;
//$auth_url = $this->client->createAuthUrl();
$error=$ee->getMessage();
}
}
if($spreadsheetFeed !== null){
foreach($spreadsheetFeed As $sheet){
$gdata_spreadsheets[$sheet->getId()] = $sheet->getTitle();
}
}
if($gdata->spreadsheet_id != '' && isset( $gdata_spreadsheets[$gdata->spreadsheet_id] ) && $spreadsheetFeed !== null){
$spreadsheet = $spreadsheetFeed->getByTitle($gdata_spreadsheets[$gdata->spreadsheet_id]);
$worksheetFeed = $spreadsheet->getWorksheets();
foreach ( $worksheetFeed as $sheet ){
$gdata_worksheets[$sheet->getId()] = $sheet->getTitle();
}
if($gdata->worksheet_id != '' && isset( $gdata_worksheets[$gdata->worksheet_id] )){
$worksheet = $worksheetFeed->getByTitle($gdata_worksheets[$gdata->worksheet_id]);
$cellFeed = $worksheet->getCellFeed();
foreach($cellFeed->getEntries() as $cellEntry) {
$row = $cellEntry->getRow();
$col = $cellEntry->getColumn();
if( $row > 1 ){
break;
}
$gdata_columns[] = $cellFeed->getCell($row, $col)->getContent();
}
}
}
} catch(Exception $e){
$error = $e->getMessage();
}
//}
ob_start();
$version = new JVersion();
if(version_compare($version->getShortVersion(), '1.6', '<')){
require_once JPATH_SITE . DS . 'plugins' . DS . 'breezingforms_addons' . DS . 'breezingforms_addons_gdata_tmpl' . DS . 'properties.php';
}else{
require_once JPATH_SITE . DS . 'plugins' . DS . 'breezingforms_addons' . DS . 'gdata' . DS . 'breezingforms_addons_gdata_tmpl' . DS . 'properties.php';
}
$c = ob_get_contents();
ob_end_clean();
return $c;
}
function onPropertiesSave($form_id){
if(!$form_id) return '';
$accessToken = '';
$reset_accessToken = false;
if(isset($_POST['gdata_code']) && $_POST['gdata_code'] != ''){
$accessToken =json_encode($this->client->authenticate($_POST['gdata_code']));
}
if(isset($_POST['gdata_reset'])){
$reset_accessToken = true;
$accessToken = '';
}
if(isset($_POST['gdata_fields']) && is_array($_POST['gdata_fields'])){
$_POST['gdata_fields'] = implode('/,/', $_POST['gdata_fields']);
}else{
$_POST['gdata_fields'] = '';
}
if(isset($_POST['gdata_meta']) && is_array($_POST['gdata_meta'])){
$_POST['gdata_meta'] = implode('/,/', $_POST['gdata_meta']);
}else{
$_POST['gdata_meta'] = '';
}
$db = JFactory::getDBO();
$db->setQuery("Select form_id From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$exists = $db->loadResult();
if(!$exists){
$db->setQuery("Insert Into #__breezingforms_addons_gdata (
`form_id`, `enabled`,`password`,`spreadsheet_id`,`worksheet_id`,`fields`,`meta`) Values
( ".intval($form_id).",
".JRequest::getInt('gdata_enabled', 0).",
".($accessToken ? $db->quote($accessToken).',' : '"",')."
".$db->quote(hexToStr(JRequest::getVar('gdata_spreadsheet_id', "''"))).",
".$db->quote(hexToStr(JRequest::getVar('gdata_worksheet_id', "''"))).",
".$db->quote($_POST['gdata_fields']).",
".$db->quote($_POST['gdata_meta'])."
)");
$db->query();
}
else {
//$token1=json_encode(array("username" => "text",
//"password" => "text"));
$gspid = $reset_accessToken ? "''" : hexToStr(JRequest::getVar('gdata_spreadsheet_id', "''"));
$wid = $reset_accessToken ? "''" : hexToStr(JRequest::getVar('gdata_worksheet_id', "''"));
$db->setQuery("Update #__breezingforms_addons_gdata Set
`enabled` = ".JRequest::getInt('gdata_enabled', 0).",
".($accessToken || $reset_accessToken ? "`password` = " . $db->quote($accessToken).',' : '')."
`spreadsheet_id` = ".$db->quote(trim($gspid) == '' ? "''" : $gspid).",
`worksheet_id` = ".$db->quote(trim($wid) == '' ? "''" : $wid).",
`fields` = ".$db->quote($_POST['gdata_fields']).",
`meta` = ".$db->quote($_POST['gdata_meta'])."
".($reset_accessToken ? ",`custom_client_id` = " . $db->quote("34263101371-4rcre0p6r9ehuhoat1d6ls8u84etuanp.apps.googleusercontent.com").', `custom_client_secret` = ' . $db->quote("IDq59sdLo6wC81KCUweDKVf2") : '')."
Where form_id = " . intval($form_id) . "
");
$db->query();
}
I give permission app to access on my Goole account, then I get auth token back from the Google account, but then I got "you to need permission"!?
Any idea?
The error you are encountering comes from the fact that the https://spreadsheets.google.com/feeds scope you are using is an invalid one.
The list of authorized scopes for Sheets API is the following one:
https://www.googleapis.com/auth/drive which allows you to see, edit, create, and delete all of your Google Drive files;
https://www.googleapis.com/auth/drive.file which allows you to view and manage Google Drive files and folders that you have opened or created with this app;
https://www.googleapis.com/auth/drive.readonly which allows you to see and download all your Google Drive files;
https://www.googleapis.com/auth/spreadsheets which allows you to see, edit, create, and delete your spreadsheets in Google Drive;
https://www.googleapis.com/auth/spreadsheets.readonly which allows you to view your Google Spreadsheets.
Therefore, depending on the exact actions you want to allow your users to make, you will have to choose one of the scopes from the list above. Moreover, make sure to delete the token.json file if you end up modifying the scopes.
Reference
Sheets API Authorize Requests.
I'm trying to decode my message with base 64 decode method. Does anybody know how to do this, or maybe via a php function?
<?php
class Gmail
{
public function __construct($client)
{
$this->client = $client;
}
public function readLabels()
{
$service = new Google_Service_Gmail($this->client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
$the_html = "";
if (count($results->getLabels()) == 0) {
// print "No labels found.\n";
$the_html .= "<p>No labels found</p>";
} else {
// print "Labels:\n";
$the_html .= "<p>labels</p>";
foreach ($results->getLabels() as $label) {
// printf("- %s\n", $label->getName());
$the_html .= "<p>" . $label->getName() . "</p>";
}
return $the_html;
}
}
/**
* Get list of Messages in user's mailbox.
*
* #param Google_Service_Gmail $service Authorized Gmail API instance.
* #param string $userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* #return array Array of Messages.
*/
public function listMessages()
{
$service = new Google_Service_Gmail($this->client);
// Print the labels in the user's account.
$userId = 'me';
$pageToken = null;
$messages = array();
$opt_param = array();
$messagesResponse = array();
$i = 0;
do {
if ($i == 5) break;
$i++;
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
}
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
foreach ($messages as $message) {
print 'Message with ID: ' . $message->getId() . '<br/>';
$msg = $service->users_messages->get($userId, $message->getId());
echo "<pre>" . var_export($msg->payload->parts[1]->body->data->base64_decode, true) . "</pre>";
}
return $messages;
}
}
As mentioned on the comment above by #Marvin, try to use base64_decode function.
Here is an example:
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str); // This is an encoded string
So in your case, instead of using
echo "<pre>" . var_export($msg->payload->parts[1]->body->data->base64_decode, true) . "</pre>";
try
echo "<pre>" . var_export(base64_decode($msg->payload->parts[1]->body->data), true) . "</pre>";
Reference
base64_decode
I have uploaded this code for solving facebook login problem. there're 3 files to implement this.. (login.php/playground_fb.php/member_index_fb.php) ... First you can find the simple button for href to playground_fb.php. and then there's some algorithm in playground_fb.php and then finally if user accept this app, then go to the member_index_fb.php with info sessions such as email address, first name, last name... I have searched a lot about these problems, but I only found the advice like input the session_start or stop the sessions or keep in 'www' like this... But it still remain unchanged... Who else help me please?
<!-- login.php -->
<div onclick="facebookLogin()" style="cursor: pointer;" align="center">
<img src="../build/img/login/login_facebook.png">
</div>
function facebookLogin() {
top.location.href = 'http://www.peeknchews.com/playground_fb.php';
}
<!-- playground_fb.php -->
<?php
session_start();
require_once('/home/kukkim/peeknchews.com/build/apis/facebook-php-sdk-v4/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => '257184091349723',
'app_secret' => '6c079349483a1bc959ce515df4e8138a',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getRedirectLoginHelper();
try {
if(isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
}
else {
$accessToken = $helper->getAccessToken();
}
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
//When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
//When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if(!isset($accessToken)) {
$permissions = ['email']; // optional
$loginUrl = $helper->getLoginUrl('http://'.$_SERVER['SERVER_NAME'].'/playground_fb.php', $permissions);
// die($_SESSION['FBRLH_' . 'state']);
echo "<script> top.location.href = '$loginUrl'; </script>";
// $permissions = ['email']; // optional
// $loginUrl = $helper->getLoginUrl('http://www.peeknchews.com/playground_fb.php', $permissions);
// echo 'LOG IN WITH FACEBOOK!';
}
else {
if(isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
else {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short lived access token for a long lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
try {
$response = $fb->get('/me?fields=email,first_name,last_name,name');
$userNode = $response->getGraphUser();
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returne d an error: ' . $e->getMessage();
unset($_SESSION['facebook_access_token']);
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returend an error: ' . $e->getMessage();
exit;
}
$fbId = $userNode->getId();
$fbEmail = $userNode->getProperty('email');
$fbName = $userNode->getName();
$fbFirstName = $userNode->getProperty('first_name');
$fbLastName = $userNode->getProperty('last_name');
$_SESSION['fbId'] = $fbId;
$_SESSION['fbEmail'] = $fbEmail;
$_SESSION['fbName'] = $fbName;
echo 'Name: ' . $fbName;
echo "<br>";
echo 'User ID: ' . $fbId . '<br>';
echo 'Email: ' . $fbEmail . '<br><br>';
echo 'Firstname : ' . $fbFirstName . '<br><br>';
echo 'Lastname : ' . $fbLastName . '<br><br>';
$image = 'https://graph.facebook.com/' . $fbId . '/picture?width=100';
echo "Picture<br><br>";
echo "<img src='$image' /><br><br> ";
//Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
echo "<script>top.location.href = 'http://www.peeknchews.com/member_index_fb.php';</script>";
}
?>
<!-- member_index_fb.php -->
<?php
session_start();
require_once('/home/kukkim/peeknchews.com/build/apis/facebook-php-sdk-v4/src/Facebook/autoload.php');
$sessionEmail=$_SESSION['user_email'];
//facebook
$fbSessionId = $_SESSION['fbId'];
$fbSessionEmail = $_SESSION['fbEmail'];
$fbSessionName = $_SESSION['fbName'];
require_once('/home/kukkim/peeknchews.com/config.php');
?>
<li>
<a class="nav-login fancybox fancybox.iframe" href="php_login/login.php"><img src="build/img/icons/login.png">
<?php
echo "<br>";
echo $fbSessionName . "<br>";
echo $fbSessionEmail . "<br>";
$image = 'https://graph.facebook.com/' . $fbSessionId . '/picture?width=100';
echo "<img src='$image' /><br><br> ";
?>
</a>
</li>
i try test web service with nusoap and php. And here is my code:
Server.php:
require_once ("lib/nusoap.php");
$URL= 'http://myexample/service.php';
$namespace = $URL.'?wsdl';
$server = new soap_server();
$server->configureWSDL("topUsers",$namespace);
$server->register("getTopUser");
$server->soap_defencoding = 'UTF-8';
$server->decode_utf8 = false;
$server->encode_utf8 = true;
function getTopUser(){
$conn = mysql_connect('localhost','root','test#123') or die(mysql_error());
mysql_select_db('test',$conn)or die(mysql_error());
mysql_query("SET charactor_set_results=utf8",$conn);
mysql_query("SET NAMES 'utf8'");
$query = mysql_query("SELECT * FROM player ORDER BY money DESC LIMIT 0,10",$conn) or die (mysql_error());
while($row = mysql_fetch_array($query)){
$data[] = array(
'userid'=>$row['userid'],
'username'=>$row['nick'],
'money'=>$row['money']
);
}
return $data;
}
if(!isset ( $HTTP_RAW_POST_DATA ))$HTTP_RAW_POST_DATA = file_get_contents ('php://input');
$server -> service ( $HTTP_RAW_POST_DATA );
Client.php:
require_once("lib/nusoap.php");
$url = 'http://myexample/service.php?wsdl';
$client = new nusoap_client($url);
$reponse = $client->call('getTopUser',array());
$client->soap_defencoding = 'UTF-8';
$client->decode_utf8 = false;
//$client->decode_utf8 = false;
$err = $client->getError();
echo $err;
echo $reponse;
echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
And here is result of my code:
2015-08-27 03:14:09.228293 nusoap_parser: parsed successfully, found root struct: 2 of name getTopUserResponse
2015-08-27 03:14:09.228530 nusoap_client: sent message successfully and got a(n) string
return=string(0) ""
I don't know i wrong somewhere? Somebody help me, please. Thanks!
I tried running this code which creates a SESSION variable for the Google email but for some reason the $_SESSION['email'] does not want to store the data. I run the code and the only output I get after signing in with google is
hello world 1
hello world 2
<?php
session_start();
require 'openid.php';
$openid = new LightOpenID('http://www.splunk.com');
if (!$openid->mode)
{
$openid->identity = 'https://www.google.com/accounts/o8/id';
$openid->required = array('contact/email');
header('Location: ' . $openid->authUrl());
}
else
{
if ($openid->validate())
{
//echo "Hello World!";
$attributes = $openid->getAttributes();
$google_email = $attributes['contact/email'];
$_SESSION['email'] = $google_email;
echo $google_email."<br />";
echo "<pre>" . print_r($_GET, true) . "</pre>";
echo $_GET['contact_email'];
header("Location: " . google_login.php);
}
else
{
echo '<p>hello world 1</p>';
echo "<p>". $_SESSION['email']. "</p>";
echo '<p>hello world 2</p>';
}
}
?>
I modified the above example with the google example from the LightOpenID site but now it doesn't validate for some reason.
<?php
# Logging in with Google accounts requires setting special identity, so this example shows how to do it.
require 'openid.php';
try
{
# Change 'localhost' to your domain name.
$openid = new LightOpenID('http://www.splunk.com');
if(!$openid->mode)
{
if(isset($_GET['login']))
{
$openid->identity = 'https://www.google.com/accounts/o8/id';
$openid->required = array('contact/email');
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<button>Login with Google</button>
</form>
<?php
}
else if($openid->mode == 'cancel')
{
echo 'User has canceled authentication!';
}
else
{
$attributes = $openid->getAttributes();
$google_email = $attributes['contact/email'];
echo $google_email;
echo 'User ' . ($openid->validate() ? $openid->identity . ' has ' : 'has not ') . 'logged in.';
}
} catch(ErrorException $e) {
echo $e->getMessage();
}