https://github.com/cashfree/pg-svelte
A Svelte component library for seamless integration of Cashfree Payment Gateway into your Svelte applications. Supports multiple payment methods, event handling, and customizable styling for a flexible and efficient payment experience.
https://github.com/cashfree/pg-svelte
cashfree-payment svelte sveltekit upi-payment
Last synced: about 1 month ago
JSON representation
A Svelte component library for seamless integration of Cashfree Payment Gateway into your Svelte applications. Supports multiple payment methods, event handling, and customizable styling for a flexible and efficient payment experience.
- Host: GitHub
- URL: https://github.com/cashfree/pg-svelte
- Owner: cashfree
- License: apache-2.0
- Created: 2025-04-03T07:01:33.000Z (6 months ago)
- Default Branch: main
- Last Pushed: 2025-05-21T08:18:34.000Z (5 months ago)
- Last Synced: 2025-08-08T14:33:55.679Z (about 2 months ago)
- Topics: cashfree-payment, svelte, sveltekit, upi-payment
- Language: Svelte
- Homepage:
- Size: 588 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Cashfree Payments for Svelte
   A Svelte component library for integrating Cashfree Payment Gateway in your Svelte applications.
## Quick Start Guide
1. **Install the package**
```bash
npm install @cashfreepayments/pg-svelte
```2. **Import and set up the Cashfree component**
```svelte
import { Cashfree, CardNumber } from '@cashfreepayments/pg-svelte';
let cashfreeComponent;
let mode = 'sandbox';
let paymentSessionId = 'your-payment-session-id'; // Get this from your backend
let isReadyForPayment = false;function checkState(e) {
isReadyForPayment = e.detail.isComplete;
}async function handlePayment() {
const result = await cashfreeComponent.pay({
paymentSessionId
});if (result.error) {
//there is an error
//message at result.error.message
}
if (result.redirect) {
//console.log("User would be redirected");
}
if (result.paymentDetails) {
//only when redirect = 'if_required' for UPI payment
//payment is successful
//message is at result.paymentDetails.paymentMessage
}
}
Pay Now```
There are lot of other configurations that you can use. You can read them [here](https://www.cashfree.com/docs/payments/online/element/payment-options)
3. **Run your app** and test the integration!
## Table of Contents
1. Installation
2. Basic Setup
3. Payment Methods
- Card Payment
- UPI QR Code
- UPI App Intent
- UPI Collect
- Netbanking
- Wallets
4. Event Handling
5. Styling Components## Installation
Install the package using npm:
```bash
npm install @cashfreepayments/pg-svelte
```## Basic Setup
The first step is to import the Cashfree components and set up a `Cashfree` component that will host your payment method.
```svelte
import { Cashfree } from '@cashfreepayments/pg-svelte';
import { onMount } from 'svelte';let mode = 'sandbox'; // or 'production' for live payments
let cashfreeComponent;
let paymentSessionId = 'your-payment-session-id';let paymentOptions = {
paymentSessionId: paymentSessionId,
redirectTarget: '_self',
redirect: 'if_required'
};async function doPayment() {
try {
const result = await cashfreeComponent.pay(paymentOptions);
if (result.error) {
throw new Error(result.error.message);
}
// Handle success
} catch (error) {
// Handle error
console.error('Payment failed:', error);
}
}
```
## Payment Methods
### Card Payment
Card payment requires four components: CardNumber, CardHolder, CardExpiry, and CardCVV. Optionally, you can include SaveInstrument to let users save their card.
```svelte
import {
Cashfree,
CardNumber,
CardHolder,
CardExpiry,
CardCVV,
SaveInstrument
} from '@cashfreepayments/pg-svelte';// Track payment component state
let isReadyForPayment = false;function checkState(e) {
// Check if all required fields are complete
isReadyForPayment = e.detail.isComplete;
}
Card Number
Card Holder Name
Expiry
CVV
Pay Now
```
### UPI QR Code
Display a QR code that customers can scan with any UPI-enabled app.
```svelte
import { Cashfree, UPIQRCode } from '@cashfreepayments/pg-svelte';
let isReadyForPayment = false;
function ready(e) {
console.log('Component ready');
}function complete(e) {
isReadyForPayment = e.detail.isComplete;
}function handlePaymentRequested(e) {
console.log('Payment requested', e.detail);
}
Scan the QR Code
Pay Now
```
### UPI App Intent
Show UPI app icons for mobile users to select their preferred UPI app.
```svelte
import { Cashfree, UPIAPP } from '@cashfreepayments/pg-svelte';
// Define available UPI apps
let upiApps = [
{ type: 'gpay', name: 'Google Pay', component: null, selected: false },
{ type: 'phonepe', name: 'PhonePe', component: null, selected: false },
{ type: 'paytm', name: 'Paytm', component: null, selected: false }
];let selectedUPIApp = null;
function selectUPIApp(app) {
// Clear previous selections
upiApps.forEach((a) => {
a.selected = false;
});// Set new selection
app.selected = true;
selectedUPIApp = app;
upiApps = [...upiApps]; // Trigger reactivity
}
{#each upiApps as app}
selectUPIApp(app)}>
{app.name}
{/each}{#if selectedUPIApp}
Continue with {selectedUPIApp.name}
{/if}
```### UPI Collect
Allow customers to enter their UPI ID for direct payment collection.
```svelte
import { Cashfree, UPICollect } from '@cashfreepayments/pg-svelte';
let isReadyForPayment = false;
function checkState(e) {
isReadyForPayment = e.detail.isComplete;
}
UPI ID
Pay Now
```
### Netbanking
Display a list of banks for netbanking payment.
```svelte
import { Cashfree, Netbanking } from '@cashfreepayments/pg-svelte';
import netbankingBanksList from '@cashfreepayments/pg-svelte/netbanking-list';// Import bank list or define your own
let netbankingBanks = netbankingBanksList.map((bank) => ({
...bank,
component: null,
selected: false
}));let selectedBank = null;
function selectBank(bank) {
// Clear previous selection
netbankingBanks.forEach((b) => {
b.selected = false;
});// Set new selection
bank.selected = true;
selectedBank = bank;
netbankingBanks = [...netbankingBanks]; // Trigger reactivity
}
{#each netbankingBanks as bank}
selectBank(bank)}>
{bank.netbankingBankDisplay}
{/each}{#if selectedBank}
Continue with {selectedBank.netbankingBankDisplay}
{/if}
```### Wallets
Implement wallet payment options with phone number input.
```svelte
import { Cashfree, Wallet } from '@cashfreepayments/pg-svelte';
// Define available wallet providers
let walletProviders = [
{ provider: 'amazonpay', buttonText: 'Amazon Pay', component: null, selected: false },
{ provider: 'phonepe', buttonText: 'PhonePe', component: null, selected: false },
{ provider: 'paytm', buttonText: 'Paytm', component: null, selected: false }
];let phone = '';
let selectedWallet = null;function selectWallet(wallet) {
if (!phone) {
alert('Please enter phone number first');
return;
}// Clear previous selection
walletProviders.forEach((w) => {
w.selected = false;
});// Set new selection
wallet.selected = true;
selectedWallet = wallet;
walletProviders = [...walletProviders]; // Trigger reactivity
}
Enter Phone number
{#each walletProviders as wallet}
selectWallet(wallet)}>
{wallet.buttonText}
{/each}{#if selectedWallet}
Continue with {selectedWallet.buttonText}
{/if}
```### Hosted Checkout Page
```svelte
import { Cashfree } from '@cashfreepayments/pg-svelte';
let checkoutOptions: Record<string, any> = {
redirectTarget: '_modal'
};
let cashfreeRoot: any;
let mode: 'sandbox' | 'production';
mode = 'sandbox';
async function doCheckout(e: Event) {
checkoutOptions.paymentSessionId = $paymentSessionIdStore;
try {
let res = await cashfreeRoot.checkout(checkoutOptions);
if (!!res.error) {
throw new Error(res.error.message);
}
if (res.redirect) {
// This will be true when the payment redirection page couldnt be opened in the same window
// This is an exceptional case only when the page is opened inside an inAppBrowser
// In this case the customer will be redirected to return url once payment is completed
console.log('Payment will be redirected');
}
if (res.paymentDetails) {
// This will be called whenever the payment is completed irrespective of transaction status
console.log('Payment has been completed, Check for Payment Status');
console.log(res.paymentDetails.paymentMessage);
}
} catch (error: any) {
errorMsg = error.message;
console.error('Payment failed:', error);
}
}```
## Event Handling
Cashfree components emit various events you can listen to:
```svelte
import { Cashfree } from '@cashfreepayments/pg-svelte';
let isReadyForPayment = false;
function handleComplete(e) {
// e.detail contains information about the state
// For example, e.detail.isComplete indicates if all required fields are filled
isReadyForPayment = e.detail.isComplete;
}function handlePaymentRequested(e) {
// This event fires when payment is requested
console.log('Payment requested');
}function handleReady(e) {
// Component is ready to accept input
console.log('Component ready');
}function handleChange(e) {
// Field value has changed
console.log('Value changed', e.detail);
}function handleLoadError(e) {
// Handle any loading errors
console.error('Load error', e.detail);
}
```
## Styling Components
You can style components using Tailwind classes or custom CSS:
```svelte
import { Cashfree, CardNumber } from '@cashfreepayments/pg-svelte';
const customStyles = {
classes: {
base: 'my-input',
focus: 'input-focused',
invalid: 'input-error',
complete: 'input-complete'
},
fonts: [
{
family: 'Roboto',
src: 'https://fonts.googleapis.com/css2?family=Roboto'
}
],
style: {
base: {
color: '#333',
fontSize: '16px',
fontFamily: 'Roboto, sans-serif',
padding: '12px',
backgroundColor: '#fff',
border: '1px solid #ccc',
borderRadius: '4px'
},
focus: {
borderColor: '#0066cc'
},
invalid: {
borderColor: '#ff3333',
color: '#ff3333'
}
},
disabled: false,
loader: true
};
.custom-input {
width: 100%;
padding: 8px 12px;
border-radius: 4px;
border: 1px solid #ccc;
}.custom-input:focus-within {
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
}```