4
2

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-12-24

はじめに

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 が呼出できます。

呼出するためのエンドポイント(URI)はリファレンスを参照します。
今回は Google Drive を操作します。API Reference | Drive REST API | Google Developers

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(status, data);
    })
    .fail(function(data, status){
        console.log(status, data);
    });
});

メモ

ここで、ステータス 403(Access Not Configured. ... API has not been used in project ... before or it is disabled.)になりました。Google Developer Console で呼出する API を有効にしてないと発生します。

また、ステータス 403(Insufficient Permission)になりました。ログイン認証するときに指定するスコープが適切でないと発生します。

おわりに

Cordova アプリで Google API 呼出できるようになりました。
続いて、Google Apps Script で書いたプログラムを呼出できるようにしたいと思います。
次回の記事 Cordova アプリで Google Apps Script で書いたプログラムを呼出してみた - Qiita

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2