回上一頁

Rails串接 Google Sheets API

近期在管理產品,正好使用到Google sheets,因此就結合了api,透過程式進行串接。

以下是使用Ruby on Rails搭配Google Sheets API的方式來整理個串接步驟與應用。

 

本篇使用的Gem:

gem 'google-apis-sheets_v4'

bundle install

 

這時需要先 Google Cloud 找到 Google Sheets API,要有Google帳號,api會收費,斟酌有策略的使用。

找到Google Sheets API後,申請api金鑰和憑證。

 

這裡提供串接 service:

  
require 'googleauth'
require 'google/apis/sheets_v4'

class GoogleSheetService
  SCOPES = [Google::Apis::SheetsV4::AUTH_SPREADSHEETS].freeze
  CREDENTIALS_PATH = 'config/google_sheets.json'.freeze  # 服務帳戶 JSON 金鑰檔案
  API_KEY_PATH = 'config/api_key.txt'                    # API 金鑰檔案

  def initialize(use_api_key: false)
    @service = Google::Apis::SheetsV4::SheetsService.new
    @service.client_options.application_name = '自定義'
    @service.authorization = use_api_key ? authorize_with_api_key : authorize_with_service_account
  end

  def get_spreadsheet_values(spreadsheet_id, range)
    @service.get_spreadsheet_values(spreadsheet_id, range).values
  end

  private

  def authorize_with_service_account
    credentials = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: File.open(CREDENTIALS_PATH),
      scope: SCOPES
    )
    credentials.fetch_access_token!
    credentials
  end

  def authorize_with_api_key
    Google::Apis::RequestOptions.new.tap do |options|
      options.api_key = File.read(API_KEY_PATH).strip  
    end
  end

end