Cordova アプリで Google API 呼出してみた

Cordova アプリで Google API 呼出してみた:


はじめに

Google Apps Script で書いたプログラムを Cordova アプリから Google アカウント認証して使用しようと思いました。

まず、Cordova アプリで Google アカウント認証できるようにしました。

以前の記事 Cordova アプリで Google アカウント認証してみた

続いて、Google API の呼出できるようにしたいと思います。

この記事のサンプルを動かせるようにします。
OAuth 2.0 for Client-side Web Applications | Google Identity Platform | Google Developers

こんな記事を見つけました。

Google APIの各種リソースに対する大抵の操作はREST風かつOAuth2なAPIになっていて、Access TokenとAPIのURLさえわかっていれば、例えば次のようにcurlコマンドを使って簡単にAPIを実行できます。
Google APIのAccess Tokenをお手軽に取得する - Qiita


Cordova アプリを作成して Google アカウント認証できるようにする

以前に作成した Cordova プロジェクトを使います。


Google API 利用できる用意する

  1. Google アカウントを作成する。既にあればそれを使用する

    (https://www.google.com/accounts)
  2. プロジェクトを作成する

    (https://console.developers.google.com/project)
  3. 使用したい API を選択して有効にする

    (https://console.developers.google.com/apis/library)
  4. 認証情報を作成

    (https://console.developers.google.com/apis/credentials)


利用したい API を有効にする

今回は Google Drive の情報を取得したいので、対象プロジェクトに対して Google Drive API を有効にしておきます。


スコープを調べておく

使用したい Google API に対応するスコープを調べておきます。

OAuth 2.0 Scopes for Google APIs | Google Identity Platform | Google Developers

今回は Google Drive API を使用したいので https://www.googleapis.com/auth/drive になります。


Cordova アプリで Goolge API 呼出する


認証したタイミングでトークンを取得する

認証したタイミングで認証コード(Authorization Code)が取得できます。
offline プロパティを true に指定しているとリフレッシュトークンも取得できます。

これを使ってアクセストークンを取得します。

index.js
var accessToken = null; 
 
    // ①認証 
    window.plugins.googleplus.login({     
            'webClientId': clientId, 
            'offline': true, 
            'scopes': scope 
        }, 
        function(obj){    // 認証に成功した 
            // ②トークンを取得 
            $.post('https://www.googleapis.com/oauth2/v4/token', {     
                'client_id': clientId, 
                'client_secret': clientSecret, 
                'grant_type': 'authorization_code', 
                'code': obj.serverAuthCode, 
            },{ 
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded' 
                } 
            }) 
            .done(function(data, status){    // トークンの取得に成功 
                $('status').html(status); 
                console.log(status, data); 
                accessToken = data.access_token; 
            }) 
            .fail(function(data, status){    // トークンの取得に失敗 
                $('status').html(status); 
                console.log(status, data); 
                accessToken = null; 
            }); 
        }, 
上記のコードで、POST しているが、Refused to connect to 'https://www.googleapis.com/oauth2/v4/token' because it violates the following Content Security Policy directive: "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback. エラーになる。index.html<meta http-equiv="Content-Security-Policy" content=default-src 'self'https://www.googleapis.com/ を追加してやる。


メモ

このとき、サンプルコードに従って redirect_uri を指定すると、ステータス 400(redirect_uri_mismatch)になりました。OAuth クライアント ID を作成したときに指定したリダイレクト URIと一致していないといけません。今回はここを空にしています。


Google API 呼出ボタンを用意する

アプリの画面に、Goolge API 呼出するためのボタンを用意しましょう。また、状態が分かるためのラベルも用意しましょう。

index.html
<button id="request">Call API</button> 
<p id="result"></p> 


取得したトークンを使って Google API を呼出する

アクセストークンがあれば Google API が呼出できます。

index.js
$('#request').click(function(){ 
    if (!accessToken) { 
        return; 
    } 
    // ③リクエストを送信 
    $.get('https://www.googleapis.com/drive/v3/about', { 
        'fields': 'user', 
        'access_token': accessToken 
    }) 
    .done(function(data, status){ 
        console.log(data, status); 
    }) 
    .fail(function(data, status){ 
        console.log(data, status); 
    }); 
}); 


おわりに

Cordova アプリで Google API 呼出できるようになりました。

続いて、Google Apps Script で書いたプログラムを呼出できるようにしたいと思います。

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)