(async()=>{const response =awaitfetch('/secret');const{client_secret: clientSecret}=await response.json();// Render the form using the clientSecret})();
// Set your publishable key: remember to change this to your live publishable key in production// See your keys here: https://dashboard.stripe.com/apikeysconst stripe =Stripe(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
,{
betas:'payto_pm_beta_1',});
Payment Element を支払いページに追加する
Payment Element を決済ページに配置する場所が必要です。決済フォームで、一意の ID を持つ空の DOM ノード (コンテナー) を作成します。
checkout.html
<formid="payment-form"><divid="payment-element"><!-- Elements will create form elements here --></div><buttonid="submit">Submit</button><divid="error-message"><!-- Display error message to your customers here --></div></form>
前のフォームが読み込まれたら、Payment Element のインスタンスを作成して、それをコンテナーの DOM ノードにマウントします。Elements インスタンスを作成する際に、前のステップからの client secret を options に渡します。
const options ={
clientSecret:'{{CLIENT_SECRET}}',// Fully customizable with appearance API.
appearance:{/*...*/},};// Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in a previous stepconst elements = stripe.elements(options);// Optional: Autofill user's saved payment methods. If the customer's// email is known when the page is loaded, you can pass the email// to the linkAuthenticationElement on mount://// linkAuthenticationElement.mount("#link-authentication-element", {// defaultValues: {// email: 'jenny.rosen@example.com',// }// })// Create and mount the Payment Elementconst paymentElementOptions ={ layout:'accordion'};const paymentElement = elements.create('payment', paymentElementOptions);
paymentElement.mount('#payment-element');
stripe.confirmPayment を使用し、Payment Element からの詳細を指定して支払いを完了します。これにより、オーソリリクエストが買い手に送信されます。
const form = document.getElementById('payment-form');
form.addEventListener('submit',async(event)=>{
event.preventDefault();const{error, paymentIntent}=await stripe.confirmPayment({//`Elements` instance that was used to create the Payment Element
elements,
redirect:'if_required',
confirmParams:{
mandate_data:{
customer_acceptance:{
type:'online',
online:{
infer_from_client:true,},},}},});const message = document.querySelector('#message')if(error){// This point will only be reached if there is an immediate error when// confirming the payment. Show error to your customer (for example, payment// details incomplete)
message.innerText= error.message;}else{// This will execute if the confirm request is successful, or if the// payment fails asynchronously.switch(paymentIntent.status){case'succeeded':
message.innerText='Success! Payment received.';break;case'processing':
message.innerText="Payment processing. We'll update you when payment is received.";break;case'requires_payment_method':
message.innerText='Payment failed. Please try another payment method.';// Redirect your user back to your payment page to attempt collecting// payment againbreak;default:
message.innerText='Something went wrong.';break;}}});