Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ryo-endo
Created December 6, 2020 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryo-endo/98e3b6db69acbb8727e225ba8cc297ab to your computer and use it in GitHub Desktop.
Save ryo-endo/98e3b6db69acbb8727e225ba8cc297ab to your computer and use it in GitHub Desktop.
スプレッドシートのGoogleAppsScriptからEC-CUBE4.0 Web APIを利用するサンプル
function getService() {
return OAuth2.createService('eccube')
.setAuthorizationBaseUrl(PropertiesService.getScriptProperties().getProperty('admin_url') + 'authorize')
.setTokenUrl(PropertiesService.getScriptProperties().getProperty('site_url') + 'token')
.setClientId(PropertiesService.getScriptProperties().getProperty('client_id'))
.setClientSecret(PropertiesService.getScriptProperties().getProperty('client_secret'))
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('read')
.setCallbackFunction('usercallback')
}
function showSidebar() {
var service = getService();
if (!service.hasAccess()) {
var authorizationUrl = service.getAuthorizationUrl();
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
SpreadsheetApp.getUi().showSidebar(page);
} else {
getProduct(service.getAccessToken());
}
}
// クライアント作成時に登録したコールバックURIでここが呼び出される
function usercallback(request) {
var service = getService();
var isAuthorized = service.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
function getProduct(token) {
const apiUri = PropertiesService.getScriptProperties().getProperty('site_url') + 'api';
const queryBody = `{
product(id:2) {
id,
name
}
}`;
const options = {
method: "post",
contentType: "application/json",
headers: {
Authorization: 'Bearer ' + token,
},
payload: JSON.stringify({ query: queryBody })
}
var response = UrlFetchApp.fetch(apiUri, options);
var result = JSON.parse(response.getContentText());
// 取得した商品名をA1セルに書き出す
const productName = result.data.product.name;
const sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1).setValue(productName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment