LoginSignup
1
0

More than 5 years have passed since last update.

Square Connect Node SDKのChargeオブジェクトの使い方

Posted at

SquareのAPIで何がしたいかと言えば、決済ではないでしょうか。そのためのAPIがCharge APIになります。

POST /v2/locations/{location_id}/transactions

この時にNode SDKで送信するオブジェクトが ChargeRequest なのですが、使い方が分かりづらいかも知れません。

基本はユニークなIDと金額

ChargeRequest はそのまま生成することもできます。

const body = new SquareConnect.ChargeRequest();

また、引数としてユニークなIDと金額を渡すこともできます。ユニークなIDについてはkelektiv/node-uuidを使うと楽だと思います。

$ npm install uuid --save
const uuidv1 = require('uuid/v1');
const uuid = uuidv1();
const body = new SquareConnect.ChargeRequest(
  uuid, {
    amount: 1000,   // 金額
    currency: 'JPY' // 通貨単位
  }
);

この他使える情報

ChargeRequestにはこの他、下記の情報が適用できます。すべてオプションですが、card_nonce と customer_id/customer_card_id のいずれかは必須です。

キー 意味
card_nonce 一時的に使えるカードトークン
customer_card_id 顧客化したカードID
delay_capture trueにすると確定せず、オーソリのみ
reference_id 自社システム用のID
note 取引に関するメモ
customer_id 顧客ID。customer_card_idと一緒に使用
billing_address 請求先住所
shipping_address 配送先住所
buyer_email_address 購入者のメールアドレス
order_id 別途作成できる注文データのID
additional_recipients 追加の注文者

これらは JSON に対するキーとして指定します。

body.card_nonce = 'aaavvvv';

普通のJSONでもOKです

なお、 SquareConnect.ChargeRequest.constructFromObject を使うと単なるオブジェクトからChargeRequestに使える形式に変換してくれます。例えば数値から文字列にするなど、エラーが発生しないように変換ができます。

const body = SquareConnect.ChargeRequest.constructFromObject({
  idempotency_key: 100,
  amount_money: {
    amount: 100,
    currency: 'JPY'
  }
});

この場合、本来 idempotency_key は文字列でないといけないので、自動で変換されます。入力チェックの目的で使っても良さそうです。

{
  "idempotency_key": "100",
  "amount_money": {
    "amount": 100,
    "currency": "JPY"
  }
}

constructFromObject はすべてのWeb APIモデルに対して用意されています。


Square Connect Node SDKはまだできたばかりで、これから機能追加が行われていきます。ぜひ使ってみて、分からないところがあればSquareのエラー・バグ・問題の解決方法|teratailへお寄せください!

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