6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ShopifyApp gem(ShopifyApi)の操作方法

Last updated at Posted at 2019-12-26

はじめに

ShopifyのAPIをRubyで操作するために公開されているShopifyApp(ShopifyApi gem含む) gemの操作方法をメモしておきます。
公式のドキュメントの情報が少なすぎて萎えてる人が多いのかなと思ったので、参考になれば幸いです。
ちなみにShopifyApp gemにはShopifyApi gemが内包されているので、ShopifyApp gemをインストールすれば、ShopifyApiモジュールも使えます。

全部を網羅的に書くのではなく、あくまでもなかなか調べても出てこないものだけを書いておきます。

以下が情報ソース

この記事では導入方法については触れません

webhookの登録

webhookを登録することでストアでのイベントを取得して任意の処理を任意のタイミングで行うことが出来ます。

ShopifyAPI::Webhook.create(:format => 'json or xml', :topic => 'topic', :address: 'POST先のエンドポイント')

上記が基本のフォーマットとなります。
例えば注文が作成された時に指定のエンドポイントへjson形式でデータをPOSTしてほしい時は以下のようになります。

ShopifyAPI::Webhook.create(:format => 'json', :topic => 'orders/create', :address: 'https://hoge.com/order_create')

トピック一覧(イベント一覧)はこちらから確認することが出来ます。

Product

取得

# 全取得(max50件まで)
ShopifyAPI::Product.all

# idを元に取得
ShopifyAPI::Product.find("#{product_id}")

# 商品タイトルで該当商品を取得
ShopifyAPI::Product.where(title: "#{オリジナルTシャツ}")

参考:REST Admin API - Product

Metafieldの追加

# metafieldを追加したい商品を取得しておく
product = ShopifyAPI::Product.find('商品id')
# metafieldのインスタンスを生成する
update_metafield = ShopifyAPI::Metafield.new(
  key: 'hoge',
  namespace: 'product_info',
  value: 'ほげ', # metafieldに保存する値
  value_type: 'string or integer or json_string' # 文字列型 or 整数型 or JSONか
)

# 以下で追加完了。saveは必要ない
product.add_metafield(update_metafield)

Order

取得

# 全件取得(max50件まで)
ShopifyAPI::Order.all

# idを元に検索
ShopifyAPI::Order.find('12412121')

# 支払い済みの注文だけを取得
ShopifyAPI::Order.where(financial_status: 'paid')

# 出荷済みの注文だけを取得
ShopifyAPI::Order.where(fulfillment_status: 'shipped')

参考:REST Admin API - Order

NoteAttributeの追加

注文詳細の詳細項目に追加出来るAPIです。

# idを元に注文を取得
order = ShopifyAPI::Order.find('12224121')
# noteattributeを追加
order.note_attributes.append(ShopifyAPI::NoteAttribute.new(name: 'ほげ', value: 'テストテスト'))
# 変更を保存
order.save

Metafieldの追加

商品とほぼ変わりませんが、一応書いておきます。

order = ShopifyAPI::Order.find('12224121')
update_metafield = ShopifyAPI::Metafield.new(
  key: 'hogekey',
  namespace: 'hogename',
  value: 'hogevalue',
  value_type: 'string'
)
order.add_metafield(update_metafield)
6
8
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
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?