回答編集履歴

2

回答の追記、ソースコードを記載

2022/04/21 03:31

投稿

k.a_teratail
k.a_teratail

スコア845

test CHANGED
@@ -4,3 +4,178 @@
4
4
  - GCPのOAuth同意画面、認証情報のAPIキーとOAuth 2.0 クライアント IDの作成
5
5
  - GAS側で実行可能APIを使用
6
6
  上記をすることでjsのfetchから実行できることを確認しました。
7
+
8
+ 実装したコードは以下になります。
9
+
10
+ **index.html**
11
+ ```html
12
+ <!doctype html>
13
+ <html lang="ja">
14
+
15
+ <head>
16
+ <meta charset="UTF-8">
17
+ </head>
18
+
19
+ <body>
20
+ <div id="auth-div" style="display: none;">
21
+ <span>アカウント認証していないので、認証ボタンを表示する</span>
22
+ <button id="auth-btn" onclick="handleAuthClick(event)">認証</button>
23
+ </div>
24
+ <div id="exec-div" style="display: none;">
25
+ <span>アカウント認証が問題無いので、実行ボタンを表示する</span>
26
+ <button id="exec-btn" onclick="execution(event)">実行</button>
27
+ <div>
28
+ 実行結果: <label id="exec-result"></label>
29
+ </div>
30
+ </div>
31
+ <script defer src="https://apis.google.com/js/api.js"
32
+ onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()"></script>
33
+ <script src="index.js"></script>
34
+ </body>
35
+ </html>
36
+ ```
37
+
38
+ **index.js**
39
+ ```js
40
+
41
+ var CLIENT_ID = 'GCPの認証情報 Auth 2.0のクライアントID';
42
+
43
+ var API_KEY = 'GCPの認証情報 APIキー';
44
+
45
+ var SCOPES = [
46
+ 'https://www.googleapis.com/auth/userinfo.email'
47
+ , 'https://www.googleapis.com/auth/script.external_request'
48
+ ];
49
+
50
+ var SCRIPT_ID = 'GASの実行可能APIにある、/exec前のID';
51
+
52
+ var DISCOVERY_DOCS = [
53
+ "https://script.googleapis.com/$discovery/rest?version=v1"
54
+ ];
55
+
56
+ // 認証用div
57
+ var authDiv = document.getElementById('auth-div');
58
+ // 実行用div
59
+ var execDiv = document.getElementById('exec-div');
60
+
61
+ // アクセス時に実行
62
+ function handleClientLoad() {
63
+ gapi.load('client:auth2', initClient);
64
+ }
65
+
66
+ // 初期化処理
67
+ function initClient() {
68
+ // GoogleAPIの初期化
69
+ gapi.client.init(
70
+ {
71
+ apiKey: API_KEY
72
+ , discoveryDocs: DISCOVERY_DOCS
73
+ , clientId: CLIENT_ID
74
+ , scope: SCOPES.join(' ')
75
+ }
76
+ ).then(function () {
77
+ // ログイン状態取得
78
+ let isSignIn = gapi.auth2.getAuthInstance().isSignedIn.get();
79
+
80
+ if (isSignIn) {
81
+ // ログイン済みなら、実行用の項目表示
82
+ execDisplay();
83
+ } else {
84
+ // 未ログインなら、ログイン用の項目表示
85
+ loginDisplay();
86
+ }
87
+ }, function (error) {
88
+ console.log("エラー: " + error);
89
+ });
90
+ }
91
+
92
+ // ログイン用の項目表示
93
+ function loginDisplay() {
94
+ // 未ログイン
95
+ authDiv.style.display = 'inline';
96
+ execDiv.style.display = 'none';
97
+ }
98
+
99
+ // 実行用の項目表示
100
+ function execDisplay() {
101
+ // ログイン済み
102
+ authDiv.style.display = 'none';
103
+ execDiv.style.display = 'inline';
104
+ }
105
+
106
+
107
+ // 認証ボタンクリック時
108
+ function handleAuthClick(event) {
109
+ gapi.auth2.getAuthInstance().signIn()
110
+ .then(function (res) {
111
+ // ログイン認証成功
112
+ execDisplay();
113
+ }, function (error) {
114
+ // ログイン認証失敗
115
+ console.log("ログイン認証失敗: " + JSON.stringify(error, null, 2));
116
+ });
117
+ }
118
+
119
+ // 実行ボタンクリック時
120
+ function execution(event) {
121
+
122
+ let request = {
123
+ 'function': 'exec'
124
+ , 'parameters': []
125
+ };
126
+
127
+ let op = gapi.client.request(
128
+ {
129
+ 'root': 'https://script.googleapis.com'
130
+ , 'path': 'v1/scripts/' + SCRIPT_ID + ':run'
131
+ , 'method': 'POST'
132
+ , 'body': request
133
+ }
134
+ );
135
+
136
+ op.execute(function (res) {
137
+ // console.log("実行結果: " + JSON.stringify(res, null, 2));
138
+
139
+ if (res.error) {
140
+ // エラーがある場合
141
+ if (res.error.status) {
142
+ console.log('API実行エラー: ' + JSON.stringify(res, null, 4));
143
+ } else {
144
+ // スクリプトエラーの場合
145
+ let error = res.error.details[0];
146
+ console.log('スクリプトエラー: ' + error.errorMessage);
147
+ }
148
+ } else {
149
+ let json = JSON.parse(res.response.result);
150
+ // console.log(json);
151
+
152
+ // 実行結果表示ラベル
153
+ let execLabel = document.getElementById('exec-result');
154
+
155
+ if (json.result === 'ok') {
156
+ execLabel.innerText = '' + '\r\n';
157
+ execLabel.innerText += '正常終了しました。';
158
+ } else {
159
+ execLabel.innerText = '処理エラー';
160
+ }
161
+ }
162
+ });
163
+ }
164
+ ```
165
+
166
+ **index.gs**
167
+ ```gs
168
+ function exec() {
169
+ let res = {
170
+ "test": 123
171
+ }
172
+ let json = res
173
+ return JSON.stringify(json)
174
+ }
175
+ ```
176
+
177
+ index.html表示すると
178
+ 未ログインの時は、「認証ボタン」が表示されます。
179
+ ログイン済みの時は、「実行ボタン」が表示されます。
180
+
181
+ 「実行ボタン」をクリックすると、問題ない場合は「実行結果: 正常終了しました。」が表示されます。

1

解決方法の記載

2022/04/21 00:22

投稿

k.a_teratail
k.a_teratail

スコア845

test CHANGED
@@ -1,3 +1,6 @@
1
- 解決しました。
1
+ 自己解決しました。
2
2
 
3
+ - Google OAuth 2.0 認証を使用したログイン
4
+ - GCPのOAuth同意画面、認証情報のAPIキーとOAuth 2.0 クライアント IDの作成
3
- 後ほど、解決方法記載します。
5
+ - GAS側で実行可能API使用
6
+ 上記をすることでjsのfetchから実行できることを確認しました。