> For the complete documentation index, see [llms.txt](https://capsurelabs.gitbook.io/technical-documentation-1/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://capsurelabs.gitbook.io/technical-documentation-1/payment-gateways-and-financial-integration/fiat-payment-systems-integration.md).

# Fiat Payment Systems Integration

## 1.1 Overview

{% hint style="info" %}
To integrate fiat payment systems, you’ll need access to third-party payment processing services like Stripe, PayPal, or Square. These services enable secure handling of user payments and offer APIs to manage transactions, refunds, and customer information.
{% endhint %}

***

## 1.2 Integration with Stripe API

### 1.2.1 Setup and Installation

```bash
npm install stripe
```

### 1.2.2 Initialize Stripe and Create a Payment Session

```javascript
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

async function createPaymentSession(req, res) {
    try {
        const session = await stripe.checkout.sessions.create({
            payment_method_types: ['card'],
            line_items: [{
                price_data: {
                    currency: 'usd',
                    product_data: {
                        name: 'CapsureLabs Premium Subscription',
                    },
                    unit_amount: 1999,
                },
                quantity: 1,
            }],
            mode: 'payment',
            success_url: `${req.headers.origin}/success?session_id={CHECKOUT_SESSION_ID}`,
            cancel_url: `${req.headers.origin}/cancel`,
        });

        res.json({ id: session.id });
    } catch (error) {
        console.error('Error creating payment session:', error);
        res.status(500).send('Payment session creation failed');
    }
}
```

### 1.2.3 Frontend Payment Button

```html
<button id="checkout-button">Pay with Card</button>
<script src="https://js.stripe.com/v3/"></script>
<script>
    const stripe = Stripe('YOUR_PUBLISHABLE_KEY');

    document.getElementById('checkout-button').addEventListener('click', async () => {
        const response = await fetch('/create-payment-session', { method: 'POST' });
        const session = await response.json();

        stripe.redirectToCheckout({ sessionId: session.id });
    });
</script>
```

### 1.2.4 Handle Payment Confirmation via Webhooks

```javascript
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
    const sig = req.headers['stripe-signature'];

    let event;
    try {
        event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET);
    } catch (error) {
        console.error('Webhook signature verification failed:', error);
        return res.status(400).send(`Webhook Error: ${error.message}`);
    }

    switch (event.type) {
        case 'payment_intent.succeeded':
            const paymentIntent = event.data.object;
            console.log('Payment succeeded:', paymentIntent);
            break;
        case 'payment_intent.payment_failed':
            const failedPaymentIntent = event.data.object;
            console.log('Payment failed:', failedPaymentIntent);
            break;
        case 'checkout.session.completed':
            const session = event.data.object;
            console.log('Checkout session completed:', session);
            break;
        default:
            console.log(`Unhandled event type ${event.type}`);
    }

    res.json({ received: true });
});
```

### 1.2.5 Error Handling and Testing

```javascript
if (!session) {
    return res.status(400).json({ error: 'Payment session failed to create' });
}
```
