Skip to content

Instantly share code, notes, and snippets.

@mfiyalka
Last active February 10, 2018 12:10
Show Gist options
  • Select an option

  • Save mfiyalka/f073c005be6e47b0e137cba9c93ee131 to your computer and use it in GitHub Desktop.

Select an option

Save mfiyalka/f073c005be6e47b0e137cba9c93ee131 to your computer and use it in GitHub Desktop.
<?php
namespace mfiyalka\telegram\common\google;
use Google_Client;
use Google\Spreadsheet\ServiceRequestFactory;
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\SpreadsheetService;
/**
* Class GoogleSpreadsheet
* @package mfiyalka\telegram\common
* @author Mykhailo Fiialka <mfiyalka@gmail.com>
*/
class GoogleSpreadsheet
{
/** @var string */
private $accessToken;
/**
* GoogleSpreadsheet constructor.
*/
public function __construct()
{
$this->apiClient();
}
private function apiClient()
{
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/../../config/client_secret.json');
$client = new Google_Client;
$client->useApplicationDefaultCredentials();
$client->setApplicationName("Something to do with my representatives");
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$this->accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
}
/**
* @param string $nameTable
* @param string $nameSheet
* @param array $data
* @return bool
* @throws \Google\Spreadsheet\Exception\SpreadsheetNotFoundException
* @throws \Google\Spreadsheet\Exception\WorksheetNotFoundException
*/
public function insert(string $nameTable, string $nameSheet, array $data)
{
$serviceRequest = new DefaultServiceRequest($this->accessToken);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheet = (new SpreadsheetService)
->getSpreadsheetFeed()
->getByTitle($nameTable);
$worksheet = $spreadsheet->getWorksheetFeed()->getByTitle($nameSheet);
$listFeed = $worksheet->getListFeed();
$listFeed->insert($data);
return true;
}
}
// insert
(new GoogleSpreadsheet())->insert(
'@bitcoinevent_bot',
'hotmine_services',
[
'title' => $service->title,
'priceusd' => $service->price,
'paid' => 'no',
'country' => '',
'city' => '',
'phone' => '',
'email' => '',
'name' => '',
'userid' => $user->id,
'username' => $user->username,
'datecreated' => date('d.m.Y')
]
);
Інструкція - https://www.twilio.com/blog/2017/03/google-spreadsheets-and-php.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment