Blog
AWSでStripe (TypeScript)を扱う時にやっておくとよいこと
Outdated Information
This article contains outdated information. Please note that some content may no longer be accurate or applicable.
これはStripeアドベントカレンダーの記事です。
Stripeの処理系統は原則サーバー側で実行されます。そうなるとAWSであれば、だいたいLambda + API Gatewayを使うことになります。
この場合に意識しておくと良いかなと思ったことをいくつかまとめました。
1: APIキーはSystems Manager or Secret Managerに入れる
APIキーをコードに書いてコミットするのはあまり良い手とはいえません。AWSであればSecret Manager、せめてSystems Managerのパラメータストアに暗号化して保存しましょう。
Serverless Frameworkの場合以下のような書き方をすると、Lambdaの環境変数として取り出せます。
service: new-service
provider: aws
functions:
hello:
name: hello
handler: handler.hello
environment:
SECURE_STRING: ${ssm:/path/to/secureparam~true}
SECRET_PARAMETER: ${ssm:/aws/reference/secretsmanager/secret_ID_in_Secrets_Manager~true}
ドキュメント: https://serverless.com/framework/docs/providers/aws/guide/variables/
この方法にすることで、APIキーを1箇所で管理することができますし、変更のためのデプロイなども必要なくなります。
devとprodの切り替えについても、Serverless Frameworkであればこのような形で処理できます。
service: new-service
provider:
name: aws
runtime: nodejs12.x
stage: development
environment:
STRIPE_API_KEY: ${ssm:${self:custom.stripeApiKey.${self:custom.stage}, self:custom.stripeApiKey.development}}
custom:
stage: ${opt:stage, self:provider.stage}
stripeApiKey:
production: "stripe-api-key-production~true"
development: "stripe-api-key-development~true"
2: Stripe APIのバージョンもSSMにいれておこう
Stripe APIは定期的にアップデートされます。もしバージョンを固定して使いたい場合は、これもSSMのパラメータストアにいれて環境変数として扱うとよいでしょう。nullにするとlatestを利用するので、以下のような形でフォールバックさせてもよいかと思います。
const stripe = Stripe('sk_test_...', {
apiVersion: process.env.STRIPE_API_VERSION || null
});
もしdev / prodで検証したい場合は、1と同様にパラメタを2つにしてもよいかもしれません。
3: 型定義ファイルは@types/stripeを使う
StripeのJSライブラリは型定義ファイルを持ちません。そのため@typesから取ってくる必要がありますが、Stripeに関しては2種類存在します。
「どっちだ・・・?」となるかもしれませんが、@types/stripe-v3はフロントエンドで使う方のライブラリ「Stripe.js」の型情報です。
ですので、以下のようなイメージで使い分けましょう。もちろん例外もありますが。
- Stripe Elementを使いたい -> stripe-v3
- Subscriptionの更新をしたい -> stripe
- Angular / Reactとかで作る -> stripe-v3
- Serverless FW / CDKとかで作る -> stripe
Tools to Support Stripe Development
We provide helpful tools to extend the Stripe Dashboard and streamline development and testing.
View All ToolsRelated Articles
Support This Project
If you find this content helpful, consider supporting the project through GitHub Sponsors. Your support helps maintain and improve these tools.
