
最近もっぱらペイメント漬けになっています。
仕事、お付き合いでのボランティア開発、なんやかんやでのプライベートシステム。
そんな時に便利なのがStripeですよね。
Stripe決済サービス
そして、Stripeは非常に簡単に課金ページの構築ができてしまうので、そのソースコード部分のみブログに書き残しておきます。
これは、以後自分が再利用することを目的としているので、他の人がどう使おうと知ったこっちゃないことは初めにお断りしておきます。
ソースコード
payment.html
<form id="payment-form">
<div id="card-number-element"></div>
<div id="card-expiry-element"></div>
<div id="card-cvc-element"></div>
<input type="text" id="zip" name="zip" placeholder="郵便番号">
<button id="submit">支払う</button>
</form>
<script src="stripe.js"></script>
stripe.js
import "https://js.stripe.com/v3/"
class Sample{
stripe = null
form = null
card = null
cardNumber = null
cardExpiry = null
cardCvc = null
elements = null
constructor(){
this.set_stripe()
this.create_form()
this.set_event()
}
stripe_style = {
base: {
color: '#32325d',
fontFamily: 'Arial, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '12px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
get elm_form(){
return document.getElementById('payment-form')
}
set_stripe(){
this.stripe = Stripe('pk_test_xxx') // 公開キー
this.elements = this.stripe.elements()
}
create_form(){
// カード番号フィールド
this.cardNumber = this.elements.create('cardNumber', { style: this.stripe_style });
this.cardNumber.mount('#card-number-element');
// 有効期限フィールド
this.cardExpiry = this.elements.create('cardExpiry', { style: this.stripe_style });
this.cardExpiry.mount('#card-expiry-element');
// CVCフィールド
this.cardCvc = this.elements.create('cardCvc', { style: this.stripe_style });
this.cardCvc.mount('#card-cvc-element');
}
set_event(){
if(this.elm_form){
this.elm_form.addEventListener("submit", this.form_submit.bind(this))
}
}
async form_submit(e){
e.preventDefault()
const res = await this.stripe.createToken(this.cardNumber)
// Error
if (res.error) {
alert(res.error.message)
}
// トークンをPHPに送信
else {
const formData = new FormData()
formData.append('api' , "payment/charge_test")
formData.append('token' , res.token.id)
const xhr = new XMLHttpRequest()
xhr.open('POST' , `check.php` , true)
xhr.setRequestHeader("X-Mkb-Authorization", window.auth_key)
xhr.onload = this.form_submited.bind(this)
xhr.send(formData)
}
}
form_submited(e){
const res = JSON.parse(e.target.response)
console.log(res)
}
}
new Sample()
check.php
require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey('sk_test_xxx'); // 秘密キー
$token = $_POST['token'];
$charge = \Stripe\Charge::create([
'amount' => 2000, // 単位は「セント」(=¥20.00)
'currency' => 'jpy',
'source' => $token,
'description' => 'テスト決済',
]);
注意点
PHPのcomposerで、事前にstripeのSKDをインストールしておいてください。
composer require stripe/stripe-php
あとがき
Stripeの公開キーと秘密キーは、Stripeの管理画面から、取得してくださいね。
あと、phpのamountは、任意に金額を設定して処理してください。
javascript側から送信する方式でもいいかもしれませんね。
商品テーブルなどと紐づけてphpで処理しても良し。
ということで、現時点での決済手数料等は以下のようになっています。
[2025年4月末日]
手数料 : 3.6%
銀行への振り込み手数料 : 250円(1回当たり)
スマホアプリの料率が20%~30%なのを考えると、非常にありがたい手数料です。
デジタル課金で副収入狙いのWebコンテンツを作ってみるのも悪くないかもね。
0 件のコメント:
コメントを投稿