Stripe API integration in Svelte

1) Install the Stripe Node library

npm install –save stripe

2) Load Stripe.js

<script src=”https://js.stripe.com/v3/”></script>

3) Define the payment form

<form id=”payment-form”>

<div id=”card-element”>

<!–Stripe.js injects the Card Element–>

</div>

<button id=”submit”>

<div class=”spinner hidden” id=”spinner”></div>

<span id=”button-text”>Pay now</span>

</button>

<p id=”card-error” role=”alert”></p>

<p class=”result-message hidden”>

Payment succeeded, see the result in your<a href=”” target=”_blank”>Stripe dashboard.</a> Refresh the page to pay again. </p>

</form>

4) Initialise Stripe.js

var stripe = Stripe(“pk_test_51BTUDGJAJfZb9HEBwDg86TN1KNprHjkfipXmEDMb0gSCassK5T3ZfxsAbcgKVmAIXF7oZ6ItlZZbXO6idTHE67IM007EwQ4uN3”);

5) Fetch a PaymentIntent

fetch(“/create-payment-intent”, {

method: “POST”,14 headers: {

“Content-Type”: “application/json”

},

body: JSON.stringify(purchase)

})

6) Fetch a PaymentIntent

var elements = stripe.elements();

7)Optional: Style the checkout form

var style = {

base: {

color: “#32325d”,

fontFamily: ‘Arial, sans-serif’,

fontSmoothing: “antialiased”,

fontSize: “16px”,

“::placeholder”: {

color: “#32325d”

}

},

invalid: {

fontFamily: ‘Arial, sans-serif’,

color: “#fa755a”,

iconColor: “#fa755a”

}

};

8)Create the Card Element

var card = elements.create(“card”, { style: style });

// Stripe injects an iframe into the DOM

card.mount(“#card-element”);

9)Handle the submit event

var form = document.getElementById(“payment-form”);

form.addEventListener(“submit”, function(event) {

event.preventDefault();

// Complete payment when the submit button is clicked

payWithCard(stripe, card, data.clientSecret);

});

10)Complete the payment

stripe .confirmCardPayment(clientSecret, {

payment_method: {

card: card

}

})

11)Handle the API response

.then(function(result) {

if (result.error) {

// Show error to your customer

showError(result.error.message);

} else {

// The payment succeeded!

orderComplete(result.paymentIntent.id);

}

});

Leave a comment

Your email address will not be published. Required fields are marked *