diadia

興味があることをやってみる。自分のメモを残しておきます。

django stripe 支払い請求をする

stripeの使い方イメージ

まずお客さんのカード情報をstripeにcheckout.jsまたはelementを使って送信する。するとそのお客さんのトークンが発行される。このトークンを使って支払い請求するようだ。それが以下のコードになる。でこのコードはサーバーサイドに書かれるもので、stripe APIsdkを使う。それは直下のコマンドで任意の環境下に入れておく。

pip install --upgrade stripe

#  https://github.com/stripe/stripe-python#installation

ドキュメント

stripe docs

https://stripe.com/docs/charges

stripe api reference

https://stripe.com/docs/api/charges/create?lang=python

メモ

# Set your secret key: remember to change this to your live secret key in production
# See your keys here: https://dashboard.stripe.com/account/apikeys
stripe.api_key = "sk_test_itU70BnUBk3oTQN3WiGzTh8T"

# Token is created using Checkout or Elements!
# Get the payment token ID submitted by the form:
token = request.form['stripeToken'] # Using Flask

charge = stripe.Charge.create(
    amount=999,
    currency='usd',
    description='Example charge',
    source=token,
)

amountはカートのトータル額を入れる。ここでamountを2000とすると、2000usd徴収することになる。
これはお客さんに提示する金額(formタグの金額)が999であってもこのamountが2000なら2000usd徴収することになる。
Cartオブジェクトのインスタンスとformタグ内の金額、そしてChargeのamountを連動するように結びつけるコードが必要となる。

運用のイメージ

まずカート精算時、またはその直前にstripeのChargeオブジェクトをcreateする。ChargeオブジェクトのデータをdjangoのChargeインスタンスにする。