Skip to content

Instantly share code, notes, and snippets.

@TLMcode
Last active February 23, 2022 16:09
Show Gist options
  • Save TLMcode/173a898207a77a349277a95ce415d3ef to your computer and use it in GitHub Desktop.
Save TLMcode/173a898207a77a349277a95ce415d3ef to your computer and use it in GitHub Desktop.
Google API Service Endpoints in PHP & cURL
<?php
class GoogleServices
{
public function __construct()
{
$this->SetVariables();
$this->VerifyToken();
}
private function SetVariables()
{
$this->scope = ( defined( 'SCOPE' ) ? SCOPE : '' );
$this->client_id = ( defined( 'CLIENT_ID' ) ? CLIENT_ID : '' );
$this->client_secret = ( defined( 'CLIENT_SECRET' ) ? CLIENT_SECRET : '' );
$this->access_token = ( defined( 'ACCESS_TOKEN' ) ? ACCESS_TOKEN : '' );
$this->refresh_token = ( defined( 'REFRESH_TOKEN' ) ? REFRESH_TOKEN : '' );
$this->redirect_url = ( defined( 'CLIENT_REDIRECT_URL' ) ? CLIENT_REDIRECT_URL : '' );
}
################
# Gmail
################
public function SendEmail( $sub, $to, $msg )
{
$url = "https://www.googleapis.com/gmail/v1/users/me/messages/send";
$line = "\n";
$raw = "to: $to" . $line;
$raw .= "subject: $sub" . $line . $line;
$raw .= $msg;
$base64 = $this->base64url_encode( $raw ); // base64_encode( $raw );
$curlPost = '{ "raw" : "' . $base64 . '" }';
return $this->Curl_Post( $url, $curlPost, true );
}
################
# Drive
################
public function ListDriveFiles()
{
$url = "https://www.googleapis.com/drive/v3/files?corpora=user&orderBy=name_natural&pageSize=100";
return $this->Curl_Post( $url, "", true, "GET" );
}
public function isJson( $json )
{
return json_decode( $json ) !== null;
}
public function CreateJsonFile( $filename, $json, $parentsId = "root" )
{
// Check json format
if ( $this->isJson( $json ) == false )
{
return array( "error" => "Incorrect or malformed json string! Make sure the array is structured correctly!" );
}
// Check if filename exists
$fileExist = null;
$driveFilesArr = $this->ListDriveFiles();
foreach( $driveFilesArr[ 'files' ] as $i => $file )
{
if( $file[ 'name' ] == $filename )
{
$fileExist = true;
}
}
if ( $fileExist == true )
{
return array( "error" => "File Exists! Please use a different name!" );
}
// Create Upload Link
$url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable";
$curlPost = array( "name" => $filename, "parents" => array( $parentsId ) );
$response = $this->Curl_Post( $url, json_encode( $curlPost ), true, "POST", true, true );
// Check if upload link was retrieved
if ( strpos( $response, "Location: https://www.googleapis.com/upload/drive/v3/files?uploadType" ) == false )
{
return array( "error" => "Could not retrieve upload link! Please try again!" );
}
preg_match_all( "|Location: (.*)\\n|U", $response, $arrUploadLinkUrl, PREG_PATTERN_ORDER );
// Upload & Return File Resource
return $this->Curl_Post( trim( $arrUploadLinkUrl[ 1 ][ 0 ] ), $json, true, "PUT", false, true, true );
}
public function UpdateJsonFile( $filename, $json, $parentsId = "root" )
{
// Check json format
if ( $this->isJson( $json ) == false )
{
return array( "error" => "Incorrect or malformed json string! Make sure the array is structured correctly!" );
}
// Check if File Exists
// Return File ID
$id = null;
$driveFilesArr = $this->ListDriveFiles();
foreach( $driveFilesArr[ 'files' ] as $i => $file )
{
if( $file[ 'name' ] == $filename )
{
$id = $file[ 'id' ];
}
}
if ( $id == null )
{
return array( "error" => "Cannot find " . $filename . "! Please try a different name!" );
}
// Create Upload Patch Link
$url = "https://www.googleapis.com/upload/drive/v3/files/$id?uploadType=resumable";
$curlPost = array( "name" => $filename );
$response = $this->Curl_Post( $url, json_encode( $curlPost ), true, "PATCH", true, true );
preg_match_all( "|Location: (.*)\\n|U", $response, $arrUploadLinkUrl, PREG_PATTERN_ORDER );
// Upload & Return File Resource
return $this->Curl_Post( trim( $arrUploadLinkUrl[ 1 ][ 0 ] ), $json, true, "PUT", false, true, true );
}
public function GetJsonFile( $filename )
{
$id = $this->GetFileId( $filename );
$url = "https://www.googleapis.com/drive/v3/files/$id?alt=media";
return array( "filename" => $filename, "fileid" => $id, "contents" => $this->Curl_Post( $url, "", true, "GET" ) );
}
public function EmptyTrash()
{
$url = "https://www.googleapis.com/drive/v3/files/trash";
$resp = $this->Curl_Post( $url, "", true, "DELETE" );
if ( $resp == "" )
{
return array( "success" => "Trash successfully emptied!" );
}
}
public function DeleteFile( $filename )
{
// Check if filename exists
$fileExist = false;
$driveFilesArr = $this->ListDriveFiles();
foreach( $driveFilesArr[ 'files' ] as $i => $file )
{
if( $file[ 'name' ] == $filename )
{
$id = $file[ 'id' ];
$fileExist = true;
}
}
if ( $fileExist == false )
{
return array( "error" => "File Not Found! Please try a different name!" );
}
$url = "https://www.googleapis.com/drive/v3/files/$id";
$this->Curl_Post( $url, "", true, "DELETE" );
// Check if file was deleted
$fileExist = false;
$driveFilesArr = $this->ListDriveFiles();
foreach( $driveFilesArr[ 'files' ] as $i => $file )
{
if( $file[ 'name' ] == $filename )
{
$fileExist = true;
}
}
if ( $fileExist == false )
{
return array( "success" => $filename . " was successfully deleted!" );
}
}
public function GetFileId( $filename )
{
$driveFilesArr = $this->ListDriveFiles();
foreach( $driveFilesArr[ 'files' ] as $i => $file )
{
if( $file[ 'name' ] == $filename )
{
$id = $file[ 'id' ];
}
}
return $id;
}
public function GetDriveIDs( $count = 10, $space = "drive" )
{
$url = "https://www.googleapis.com/drive/v3/files/generateIds?count=$count&space=$space";
return $this->Curl_Post( $url, "", true, "GET" );
}
################
# Youtube
################
public function GetYoutubePlaylists()
{
$url = "https://www.googleapis.com/youtube/v3/playlists?maxResults=5&channelId=UCwfNLRAhB8FYq4QJiJzB4dA&part=snippet%2CcontentDetails";
return $this->Curl_Post( $url, "", true, "GET" );
}
public function GetYoutubePlaylistsItems( $nextPageToken = "" )
{
$url = "https://www.googleapis.com/youtube/v3/playlistItems?playlistId=LLwfNLRAhB8FYq4QJiJzB4dA&maxResults=50&part=snippet%2CcontentDetails"; // << overly specific playlist id ... used in temporary history dump
if ( $nextPageToken != "" )
{
$url .= "&pageToken=$nextPageToken";
}
return $this->Curl_Post( $url, "test", true, "GET" );
}
################
# Calendar
################
public function GetUserCalendarTimezone()
{
$url = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
return $this->Curl_Post( $url, "", true, "", "", "", "", false )[ 'value' ];
}
public function GetCalendarEvents()
{
$url = "https://www.googleapis.com/calendar/v3/calendars/primary/events";
$eventItems = $this->Curl_Post( $url, "", true, "GET" )[ 'items' ];
$eventsArr = array();
foreach ( $eventItems as $i => $eventItem )
{
$eventsArr[ $eventItem[ 'summary' ] ] = $eventItem;
}
return $eventsArr;
}
public function GetCalendarsList()
{
$url_parameters = array();
$url_parameters[ 'fields' ] = 'items(id,summary,timeZone)';
$url_parameters[ 'minAccessRole' ] = 'owner';
$url_calendars = 'https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=10&' . http_build_query( $url_parameters );
return $this->Curl_Post( $url_calendars, "", true, "", "", "", "", false );
}
public function CreateCalendarEvent( $event_title, $event_time, $desc = null, $calendar_id = "primary", $all_day = 0 )
{
$event_timezone = $this->GetUserCalendarTimezone();
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events'; // ?sendNotifications=true'; # deprecated
$curlPost = array( 'summary' => $event_title );
// places an image url in the event but isn't really callable from the event api
// $curlPost[ 'source' ][ 'url' ] = 'https://i.imgur.com/OjCuRKv.jpg';
if( $all_day == 1 )
{
$curlPost[ 'start' ] = array( 'date' => $event_time[ 'event_date' ] );
$curlPost[ 'end' ] = array( 'date' => $event_time[ 'event_date' ] );
}
else
{
$curlPost[ 'start' ] = array( 'dateTime' => $event_time[ 'start_time' ], 'timeZone' => $event_timezone );
$curlPost[ 'end' ] = array( 'dateTime' => $event_time[ 'end_time' ], 'timeZone' => $event_timezone );
}
if ( isset( $desc ) )
{
$curlPost[ 'description' ] = $desc;
}
return $this->Curl_Post( $url, json_encode( $curlPost ), true );
}
public function DeleteCalendarEvent( $id, $calendar_id = "primary" )
{
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events/' . $id;
return $this->Curl_Post( $url, "", true, "DELETE" );
}
public function WatchChannel( $id, $calendar_id = "primary" )
{
$url = 'https://www.googleapis.com/calendar/v3/users/me/calendarList/watch'; // 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events/watch';
$curlPost = array(
'id' => $id,
'type' => 'web_hook',
'address' => 'callback.php'
);
return $this->Curl_Post( $url, json_encode( $curlPost ), true );
}
public function StopChannel( $id, $resId )
{
$url = 'https://www.googleapis.com/calendar/v3/channels/stop';
$curlPost = array(
"id" => $id,
"resourceId" => $resId
);
return $this->Curl_Post( $url, json_encode( $curlPost ), true );
}
################
# Token & Auth
################
private function VerifyToken()
{
$url = "https://www.googleapis.com/oauth2/v1/tokeninfo";
$curlPost = 'access_token=' . $this->access_token;
$response = $this->Curl_Post( $url, $curlPost );
if ( isset( $response[ 'error' ] ) )
{
// ## grab new token
$response = $this->GetRefreshToken();
$this->access_token = $response[ 'access_token' ]; // if refresh token is invalid, this will fail!!!!
}
}
public function Authenticate()
{
$this->GetAccessCode();
return $this->GetAccessToken();
}
private function GetAccessCode()
{
if ( !isset( $_GET[ 'code' ] ) )
{
header( "Location: https://accounts.google.com/o/oauth2/auth?client_id=" . $this->client_id
. "&redirect_uri=" . $this->redirect_url
. "&scope=" . $this->scope
. "&access_type=offline"
. "&response_type=code" );
}
else
{
$access_code = $_GET[ 'code' ];
return $access_code;
}
}
private function GetAccessToken()
{
$url = "https://accounts.google.com/o/oauth2/token";
$curlPost = 'code=' . $_GET[ 'code' ]
. '&client_id=' . $this->client_id
. '&client_secret=' . $this->client_secret
. '&redirect_uri=' . $this->redirect_url
. '&grant_type=authorization_code';
return $this->curl_post( $url, $curlPost );
}
private function GetRefreshToken()
{
$url = "https://accounts.google.com/o/oauth2/token";
$curlPost = '&client_id=' . $this->client_id
. '&client_secret=' . $this->client_secret
. '&refresh_token=' . $this->refresh_token
. '&grant_type=refresh_token';
return $this->Curl_Post( $url, $curlPost );
}
private function base64url_encode( $mime )
{
return rtrim( strtr( base64_encode( $mime ), '+/', '-_' ), '=' );
}
################
# ppl id coding
################
public function code_psid( $id )
{
if ( isset( $id ) && ( substr( $id, 0, 3 ) == 'INV' ) && strlen( $id ) == 24 )
{
$str = null;
foreach( explode( "-", $id ) as $i => $seg )
{
if ( $i > 0 )
{
foreach( str_split( strrev( $seg ) ) as $chr )
{
$str .= rand( 0, 1 ) ? $chr : strtolower( $chr );
}
}
}
$str = strrev( $str );
}
else if ( isset( $id ) && preg_match( "/^\w{16}$/i", $id ) == true && strlen( $id ) == 16 )
{
$str = "INV2";
foreach( str_split( strrev( $id ), 4 ) as $i => $seg )
$str .= "-" . strtoupper( strrev( $seg ) );
}
else
{
$str = false;
}
return $str;
}
################
# cURL
################
private function Curl_Post( $url, $curlPost = "", $header = "", $method = "POST", $curlOptHdr = false, $curlOptVerPeer = false, $binaryTransfer = false, $postOpt = true )
{
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, $curlOptVerPeer );
curl_setopt( $ch, CURLOPT_HEADER, $curlOptHdr );
if( $header == true )
{
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', "Authorization: Bearer " . $this->access_token ) );
}
// curl_setopt( $ch, CURLOPT_POST, 1 );
if ( $postOpt == true )
{
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $method );
}
if( $curlPost !== "" )
{
curl_setopt( $ch, CURLOPT_POSTFIELDS, $curlPost );
}
if( $binaryTransfer == true )
{
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
}
$resp = curl_exec( $ch );
$data = json_decode( $resp, true );
if( $data == null ) // if response isn't json, return string
{
$data = $resp;
}
$errno = curl_errno( $ch );
$http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
// if( $http_code != 200 )
// {
// throw new Exception( 'Error : Failed to receive access token' );
// }
curl_close( $ch );
return $data;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment