Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lgs/b71e8354af9e88e021d846530b3f400a to your computer and use it in GitHub Desktop.
Save lgs/b71e8354af9e88e021d846530b3f400a to your computer and use it in GitHub Desktop.
<script>
import { stores } from '@sapper/app';
import { onMount } from 'svelte';
import {loadStripe} from '@stripe/stripe-js';
let paymentToken = '';
let paymentError;
const { preloading, page, session } = stores();
$ : unitName = ($page.params && $page.params.unitName) ? $page.params.unitName[0] : ''; // The reactive part here I read the params to know about what is the selected unit by the user
let getStripeSessionToken = async function () {
try {
const response = await fetch(
`https://youramazingapp.com/payments/as?unitName=${unitName}` // Generate stripe token here
);
console.log(response);
const data = await response.json();
console.log(data);
return data.id;
}catch(e) {
console.log('Error in loading Stripejs: ', e);
return e;
}
}
let payReservation = async function () {
const stripe = await loadStripe('some-super-secret');
const sessionToken = await getStripeSessionToken();
const {error} = await stripe.redirectToCheckout({
// Make the id field from the Checkout Session creation API response
// available to this file, so you can provide it as parameter here
// instead of the {{CHECKOUT_SESSION_ID}} placeholder.
sessionId: sessionToken
})
paymentError = error.message;
}
let payPalLoaded = () => {
const payPalButtons = paypal.Buttons();
paypal.Buttons({
style: {
"layout": "vertical"
},
createOrder: function(data, actions) {
return actions.order.create({
"description": `Reservation ${unitName} of Aldea Savia`,
"purchase_units": [
{
"description": `Reservation ${unitName} of Aldea Savia`,
"amount": {
"currency_code": "MXN",
"value": "20000.00"
}
}
]
})
},
onApprove: function(data, actions) {
// This function captures the funds from the transaction.
return actions.order.capture().then(function(details) {
// This function shows a transaction success message to your buyer.
console.log('details of transcation: ', details);
alert('Transaction completed by ' + details.payer.name.given_name);
});
}
})
.render('#paypal-button-container');
}
</script>
<svelte:head>
<script
src="https://www.paypal.com/sdk/js?currency=MXN&client-id=some-super-secret&disable-funding=card"
on:load={() => payPalLoaded()}
>
</script>
</svelte:head>
<div>
<div>
¡Reserve the unit {unitName} in Aldea Savia now!
</div>
<div>
<button
on:click={() => payReservation()}
class="border text-lg rounded px-4 py-2 border-solid
border-2 border-green-500 text-green-800
"
>
Pay with Debit or Credit Card
</button>
</div>
<div class="py-4">
<div id="paypal-button-container"></div>
</div>
<div>
Errors:
{paymentError}
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment