Skip to content

Instantly share code, notes, and snippets.

@andronex
Created June 10, 2021 18:40
Show Gist options
  • Save andronex/ee437f80ea14492832f19ecaf7cafa2a to your computer and use it in GitHub Desktop.
Save andronex/ee437f80ea14492832f19ecaf7cafa2a to your computer and use it in GitHub Desktop.
Синхронизация остатков товаров с Гугл таблицами по номеру ячейки (MODX Revolution)
<?php
/*
* на основе статьи https://pocketadmin.tech/ru/%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0-%D1%81-4-%D0%B2%D0%B5%D1%80%D1%81%D0%B8%D0%B5%D0%B9-api-google-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%8B-%D0%BD%D0%B0-php/
* библиотека wget https://github.com/googleapis/google-api-php-client/releases/download/v2.7.2/google-api-php-client-v2.7.2-PHP7.0.zip
* номер ячейки, из которой следует брать остатки товара, указывается в TV поле товара
* остатки записываются в другое TV поле (при желании можно записать хоть куда)
*/
if (!isset($modx)) {
define('MODX_API_MODE', true);
while (!isset($modx) && ($i = isset($i) ? --$i : 10)) {
if (($file = dirname(!empty($file) ? dirname($file) : __FILE__) . '/index.php') AND !file_exists($file)) {
continue;
}
require_once $file;
}
if (!is_object($modx)) {
exit('{"success":false,"message":"Access denied"}');
}
$modx->getService('error', 'error.modError');
$modx->getRequest();
$modx->setLogLevel(modX::LOG_LEVEL_ERROR);
$modx->setLogTarget('FILE');
$modx->error->message = null;
}
$ctx = !empty($_REQUEST['ctx']) ? $_REQUEST['ctx'] : $modx->context->get('key');
if ($ctx != $modx->context->get('key')) {
$modx->switchContext($ctx);
}
// ID таблицы
$spreadsheetId = $modx->getOption('google_spreadsheet');
// GUID листа
$sheetId = $modx->getOption('google_sheet');
if(!$spreadsheetId || (!$sheetId && $sheetId != 0)){
$out = ['success' => false, 'message' => 'Не заданы переменные google_spreadsheet и google_sheet'];
die($out['message']);
}
// Подключаем клиент Google таблиц
require_once __DIR__ . '/vendor/autoload.php';
// Наш ключ доступа к сервисному аккаунту
$googleAccountKeyFilePath = __DIR__ . '/service_key.json';
if(!file_exists($googleAccountKeyFilePath)){
$out = ['success' => false, 'message' => 'Нет файла ключа ' . (__DIR__ . '/service_key.json')];
die($out['message']);
}
function translit($value)
{
$converter = array(
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd',
'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i',
'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n',
'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't',
'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch',
'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '',
'э' => 'e', 'ю' => 'yu', 'я' => 'ya',
'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D',
'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I',
'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N',
'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T',
'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Ch',
'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => '', 'Ы' => 'Y', 'Ъ' => '',
'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya',
);
$value = strtr($value, $converter);
return $value;
}
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $googleAccountKeyFilePath);
// Создаем новый клиент
$client = new Google_Client();
// Устанавливаем полномочия
$client->useApplicationDefaultCredentials();
// Добавляем область доступа к чтению, редактированию, созданию и удалению таблиц
$client->addScope('https://www.googleapis.com/auth/spreadsheets');
$service = new Google_Service_Sheets($client);
try {
$response = $service->spreadsheets->get($spreadsheetId);
if(!$response->getSheets()[$sheetId]){
$out = ['success' => false, 'message' => 'Нет листа под ID '. $sheetId];
die($out['message']);
}
$SheetProperties = $response->getSheets()[$sheetId]->getProperties();
$title = $SheetProperties->getTitle();
$prods = $modx->getCollection('modResource', array('template:IN' => array(3,9)));
foreach($prods as $prod){
if($range = $prod->getTVValue(6)){
$range = $title.'!'.$range;
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$value = $response->getValues();
if(isset($value[0][0])){
$prod->setTVValue(7, str_replace([',',' '],['.',''],$value[0][0]));
}
}
}
$out = ['success' => true, 'message' => 'Остатки успешно обновлены'];
die($out['message']);
} catch (Exception $e) {
$out = ['success' => false, 'message' => $e->getMessage()];
die($out['message']);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment