4
4

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 3 years have passed since last update.

Square APIを使ってみる(在庫数の取得)

Last updated at Posted at 2020-03-07

Square APIを使って、在庫数の取得まで出来たのでまとめておきます。

アクセストークンの取得

Application Dashboardで、新しいアプリケーションを作成すると、アプリケーションIDとアクセストークンが作られます。

実際の課金など発生しないSandboxモードと、本番環境のProductionモードがあり、それぞれアプリケーションIDとアクセストークンが違うので、まずはSandboxモードを使いましょう。

Image from Gyazo

curlでAPIを叩いてみる

curl -X POST \
-H 'Accept: application/json' \
-H 'Authorization: Bearer {{ACCESS_TOKEN}}' \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-d '{
    "idempotency_key": "TESTKEY123",
    "autocomplete": true,
    "amount_money": {
      "amount": 100,
      "currency": "JPY"
    },
    "source_id": "cnon:card-nonce-ok"
    }
}' \
'https://connect.squareupsandbox.com/v2/payments'

{{ACCESS_TOKEN}}を、先ほど取得したSnadboxのアクセストークンに置き換えます。

ドキュメントでは、curencyが、USDでしたが、JPYにしろ!ってERRORが表示されたので、JPYにしたところレスポンスが返ってきました。

Square Connect Node SDKを使ってAPIアクセス

Node.jsのSDK「Square Connect Node SDK」を使ってアクセスしてみます。

Square Connect Node SDKをインストール

$ yarn add square-connect

サンプルコードを動かしてみます。

var SquareConnect = require('square-connect');
var defaultClient = SquareConnect.ApiClient.instance;
// Set sandbox url
defaultClient.basePath = 'https://connect.squareupsandbox.com';
// Configure OAuth2 access token for authorization: oauth2
var oauth2 = defaultClient.authentications['oauth2'];
// Set sandbox access token
oauth2.accessToken = "YOUR SANDBOX ACCESS TOKEN";
// Pass client to API
var api = new SquareConnect.LocationsApi();


api.listLocations().then(function(data) {
  console.log('API called successfully. Returned data: ' + JSON.stringify(data, 0, 1));
}, function(error) {
  console.error(error);
});

実行すると、以下のように表示されました。

API called successfully. Returned data: {
 "locations": [
  {
   "id": "M513Y0SCF175A",
   "name": "Default Test Account",
   "address": {
    "address_line_1": "1",
    "locality": "Chiyoda City",
    "administrative_district_level_1": "13",
    "postal_code": "100-0014",
    "country": "JP"
   },
   "timezone": "Etc/UTC",
   "capabilities": [
    "CREDIT_CARD_PROCESSING"
   ],
   "status": "ACTIVE",
   "created_at": "2020-03-07T10:20:33Z",
   "merchant_id": "VFZJMXEYNJVYN",
   "country": "JP",
   "language_code": "ja-JP",
   "currency": "JPY",
   "business_name": "Default Test Account",
   "type": "PHYSICAL",
   "business_hours": {},
   "mcc": "5944"
  }
 ]
}

Sandboxに入っている店舗情報が返ってきました。

商品リストを取得してみる

CatalogApiのlistCatalogを使って、商品のリストを取得してみます。

どうもSandboxは、商品リストが空っぽのようで、何も結果が返ってこなかったので、本番のアクセストークンを使ってみました。

var SquareConnect = require('square-connect');
var defaultClient = SquareConnect.ApiClient.instance;

// Configure OAuth2 access token for authorization: oauth2
var oauth2 = defaultClient.authentications['oauth2'];
oauth2.accessToken = 'YOUR ACCESS TOKEN';

var apiInstance = new SquareConnect.CatalogApi();

var opts = { 
    'types': 'ITEM'
};
apiInstance.listCatalog(opts).then(function (data) {
    console.log('API called successfully. Returned data: ');
    console.log(JSON.stringify(data,null,2));
}, function (error) {
    console.error(error);
});

以下のような出力になりました。

{
  "objects": [
    {
      "type": "ITEM",
      "id": "E5OD3ACUQ6GOTA2KFGTVDT5L",
      "updated_at": "2020-01-12T11:06:49.742Z",
      "version": 1578827209742,
      "is_deleted": false,
      "catalog_v1_ids": [
        {
          "catalog_v1_id": "9B78CDF8-8D3D-4D23-8F16-3E7D9534B9E8",
          "location_id": "454ACGR0V7GPA"
        }
      ],
      "present_at_all_locations": false,
      "present_at_location_ids": [
        "454ACGR0V7GPA"
      ],
      "item_data": {
        "name": "鯉口 虹",
        "label_color": "593C00",
        "available_online": false,
        "available_for_pickup": false,
        "available_electronically": false,
        "category_id": "B42OYZA5ENOYOVVYIDT6F5T2",
        "tax_ids": [
          "OIB76Q3LPWOXXKKRVJLFACKB"
        ],
        "variations": [
          {
            "type": "ITEM_VARIATION",
            "id": "5B3FDDMKODDFS5WP2NIU5ZTO",
            "updated_at": "2020-01-12T11:06:49.742Z",
            "version": 1578827209742,
            "is_deleted": false,
            "catalog_v1_ids": [
              {
                "catalog_v1_id": "993447A1-EB87-4BAA-AA98-1124D2A853DE",
                "location_id": "454ACGR0V7GPA"
              }
            ],
            "present_at_all_locations": false,
            "present_at_location_ids": [
              "454ACGR0V7GPA"
            ],
            "item_variation_data": {
              "item_id": "E5OD3ACUQ6GOTA2KFGTVDT5L",
              "name": "M",
              "sku": "",
              "ordinal": 0,
              "pricing_type": "VARIABLE_PRICING",
              "location_overrides": [
                {
                  "location_id": "454ACGR0V7GPA",
                  "track_inventory": true
                }
              ],
              "service_duration": 0,
              "available_for_booking": false,
              "transition_time": 0
            }
          },
          {
            "type": "ITEM_VARIATION",
            "id": "MWZZO64LINWIJVNIA7FDQQVR",
            "updated_at": "2020-01-12T11:06:49.742Z",
            "version": 1578827209742,
            "is_deleted": false,
            "catalog_v1_ids": [
              {
                "catalog_v1_id": "89215CEA-730E-4E3E-8C5E-88F88CAE5BC0",
                "location_id": "454ACGR0V7GPA"
              }
            ],
            "present_at_all_locations": false,
            "present_at_location_ids": [
              "454ACGR0V7GPA"
            ],
            "item_variation_data": {
              "item_id": "E5OD3ACUQ6GOTA2KFGTVDT5L",
              "name": "S",
              "sku": "",
              "ordinal": 1,
              "pricing_type": "VARIABLE_PRICING",
              "location_overrides": [
                {
                  "location_id": "454ACGR0V7GPA",
                  "track_inventory": true
                }
              ],
              "service_duration": 0,
              "available_for_booking": false,
              "transition_time": 0
            }
          }
        ],
        "product_type": "REGULAR",
        "skip_modifier_screen": false
      }
    },
    {
      "type": "ITEM",
      "id": "6CZOC256NZGH7R3Z5IRADPX5",
      "updated_at": "2019-03-08T00:44:30.092Z",
      "version": 1552005870092,
      "is_deleted": false,
      "catalog_v1_ids": [
        {
          "catalog_v1_id": "64B15EC3-36FC-4511-8CD2-96F7A150B751",
          "location_id": "454ACGR0V7GPA"
        }
      ],
      "present_at_all_locations": false,
      "present_at_location_ids": [
        "454ACGR0V7GPA"
      ],
      "item_data": {
        "name": "帽子",
        "label_color": "13B1BF",
        "available_online": false,
        "available_for_pickup": false,
        "available_electronically": false,
        "category_id": "LE6QTI6LQXHOOKH6GEHTLCUU",
        "tax_ids": [
          "OIB76Q3LPWOXXKKRVJLFACKB"
        ],
 :
 :
 

在庫数を取得してみる

在庫数の取得は、InventoryApiのretrieveInventoryCountを使います。

var SquareConnect = require('square-connect');
var defaultClient = SquareConnect.ApiClient.instance;

// Configure OAuth2 access token for authorization: oauth2
var oauth2 = defaultClient.authentications['oauth2'];
oauth2.accessToken = 'YOUR ACCESS TOKEN';

var apiInstance = new SquareConnect.InventoryApi();

var catalogObjectId = "catalogObjectId_example"; // String | ID of the `CatalogObject` to retrieve.

var opts = { 
//  'locationIds': "locationIds_example", // String | The `Location` IDs to look up as a comma-separated list. An empty list queries all locations.
//  'cursor': "cursor_example" // String | A pagination cursor returned by a previous call to this endpoint. Provide this to retrieve the next set of results for the original query.  See the [Pagination](https://developer.squareup.com/docs/docs/working-with-apis/pagination) guide for more information.
};

apiInstance.retrieveInventoryCount(catalogObjectId, opts).then(function (data) {
    console.log('API called successfully. Returned data: ');
    console.log(JSON.stringify(data, null, 2));
}, function (error) {
    console.error(error);
});

catalogObjectIdには、listCatalogで取得したアイテムのID
を入れます。

item_idという値もありますが、ここで使うのはidの値です。

「鯉口 虹」のバリエーション「S」のIDは、MWZZO64LINWIJVNIA7FDQQVRなので、この値をcatalogObjectIdに入れて在庫数を取得します。

結果は以下のようになりました。

{
  "counts": [
    {
      "catalog_object_id": "MWZZO64LINWIJVNIA7FDQQVR",
      "catalog_object_type": "ITEM_VARIATION",
      "state": "IN_STOCK",
      "location_id": "454ACGR0V7GPA",
      "quantity": "1",
      "calculated_at": "2020-01-12T11:06:41.11211Z"
    }
  ]
}

在庫数は1です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?