LoginSignup
1
1

More than 5 years have passed since last update.

Square APIの公式ライブラリを使ってみよう

Posted at

Square APIはHTTP/HTTPSで呼び出して使うものが多いですが、さらに使いやすくするために各プログラミング言語向けにライブラリを提供しています。square_connectという共通の名前なのですが、今回はRuby向けの利用法について紹介します。

ライブラリのインストール

square_connectはRubygemsでインストールできます。

gem install square_connect

セットアップ

まず最初にアクセストークンを含めたセットアップを行います。 REPLACE_WITH_YOUR_ACCESS_TOKEN は自分のアクセストークンに置き換えてください。

require 'square_connect'

access_token = 'REPLACE_WITH_YOUR_ACCESS_TOKEN'

SquareConnect.configure do |config|
  config.access_token = access_token
end

拠点情報を得る

今回はデモとして拠点情報を取得してみたいと思います。その場合、まずAPIのオブジェクトを作ります。

locations_api = SquareConnect::LocationsApi.new

そして呼び出します。

locations_response = locations_api.list_locations

ネットワーク接続やアクセストークンの問題があると SquareConnect::ApiError が発生します。

そして取得できた locations_response の中にある拠点一覧の中で利用できるもの(capabilitiesCREDIT_CARD_PROCESSING になっているかどうかで判定できます)を探します。この状態になっている拠点は利用可能です。

location = locations_response.locations.detect do |l|
  l.capabilities.include?("CREDIT_CARD_PROCESSING")
end

もしそうした拠点がなかったならば、Squareのアクティベーションが必要になります。

if location.nil?
  raise "Activation required. 
  Visit https://squareup.com/activate to activate and begin taking payments."
end

後は取得できた拠点に対して処理を行うだけです。今回は単に出力します。

puts location
=> {:id=>"CBASEJqRSQmT1vVfMXar4RcrtCcgAQ", :name=>"ヤマモト 東京", :address=>{:address_line_1=>"中 1丁目", :locality=>"東京都", :administrative_district_level_1=>"国立市", :postal_code=>"186-0004", :country=>"JP"}, :timezone=>"Asia/Tokyo", :capabilities=>["CREDIT_CARD_PROCESSING"]}

Square Connectを使うことでSquare APIの利用が簡単になります。Rubyの他、PHP/Java/Python/C#向けに提供されています。ぜひ自分たちのプロジェクトにあったものを選択してください。

Square Connect API Documentation

1
1
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
1
1