@payjp/react-payments-js は React で payments.js を利用するためのラッパーライブラリです。 各種の Form を React Component として提供します。
npm install @payjp/react-payments-js @payjp/payments-jsimport { loadPayments } from '@payjp/payments-js'
import { Widgets, PaymentForm, AddressForm, useWidgets } from '@payjp/react-payments-js';
const CheckoutForm = () => {
const { widgets, payments } = useWidgets();
const [isLoading, setIsLoading] = useState(false);
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!widgets || !payments) {
return
}
setIsLoading(true);
const { error } = await widgets.confirmPayment({ return_url: "https://example.com/return_url" });
setIsLoading(false);
if (error) {
console.error(error);
}
};
return (
<form id="payment-form" onSubmit={onSubmit}>
<PaymentForm />
<AddressForm options={{ mode: "shipping" }} />
<AddressForm options={{ mode: "billing" }} />
<button type="submit" disabled={isLoading || !widgets || !payments} >
Pay
</button>
</form>
);
}
const paymentsPromise = loadPayments('pk_test_your-public-key-here')
const App = () => (
<Widgets
paymentsPromise={paymentsPromise}
options={{
clientSecret: "client-secret-for-flow-here",
}}
>
<CheckoutForm />
</Widgets>
);
createRoot(document.getElementById("app")!).render(
<StrictMode>
<App />
</StrictMode>
);PaymentForm および AddressForm コンポーネントは、以下のイベントハンドラーをサポートしています。
<PaymentForm
onChange={(event) => {
console.log('Payment method type:', event.value.type);
console.log('Is complete:', event.complete);
console.log('Is empty:', event.empty);
}}
onFocus={() => console.log('Payment form focused')}
onBlur={() => console.log('Payment form blurred')}
onReady={() => console.log('Payment form ready')}
/>onChange イベント:
elementType:"payment"(固定値)empty: フォームが空の場合truecomplete: フォームが完全に入力された場合truevalue.type: 選択された支払い方法のタイプ(payjp.PaymentMethodTypesまたはnull)
<AddressForm
options={{ mode: "shipping" }}
onChange={(event) => {
console.log('Address mode:', event.elementMode);
console.log('Name:', event.value.name);
console.log('Address:', event.value.address);
console.log('Phone:', event.value.phone);
console.log('Is complete:', event.complete);
}}
onFocus={() => console.log('Address form focused')}
onBlur={() => console.log('Address form blurred')}
onReady={() => console.log('Address form ready')}
/>onChange イベント:
elementType:"address"(固定値)elementMode: アドレスフォームのモード("shipping"または"billing")empty: フォームが空の場合truecomplete: フォームが完全に入力された場合truevalue.name: 入力された名前value.address: 入力された住所情報value.phone: 入力された電話番号
onReady: フォームの準備が完了したときに発火onFocus: フォーム内の要素がフォーカスされたときに発火onBlur: フォーム内の要素からフォーカスが外れたときに発火