DEV Community

Cover image for The Holy Grail of Payment Integration: A React Native Safari 🎒
Sherifdeen Adebayo
Sherifdeen Adebayo

Posted on

The Holy Grail of Payment Integration: A React Native Safari 🎒

Bismillah! As we journey through Ramadan (yes, we're fasting AND coding πŸ˜…), let's dive into the world of payment gateways. Don't worry, this implementation is easier than resisting samosas at iftar!

The Batman and Robin of Web Development πŸ¦Ήβ€β™‚οΈ

Ever wondered why frontend and backend developers are like hot suya and yaji? They're better together!

Just like how Batman needs Robin (or how developers need coffee β˜•οΈ), our frontend needs the backend for payment processing. The backend is like that friend who keeps all your secrets safe (API keys, we're looking at you πŸ‘€), while the frontend is the charming face that users actually see.

Backend Magic: Where Money Goes to Party πŸŽ‰

Warning: No actual money was harmed during the writing of this code!

Remember when your mom said "money doesn't grow on trees"? Well, it now flows through APIs! We've got payment gateways galore:

  • Stripe (for the fancy folks 🎩)
  • Paystack (African excellence 🌍)
  • Flutterwave (making waves, get it? 🌊)
  • Squad (not related to Suicide Squad, promise! πŸ˜…)

Here's our magical money-moving endpoint:

// POST /api/wallet/top-up 
// AKA "The Money Maker" πŸ’Έ
{
    "amount": 2000, // Your wallet's workout plan
    "redirect_url": "https://example.com?amount=200&foo=bar" // Where money goes to rest
}
Enter fullscreen mode Exit fullscreen mode

The response (if the money gods are pleased πŸ™):

{
    "message": "Topup initialized", // fancy way of saying "We're cooking!"
    "data": {
        "link": "https://checkout-v2.dev-flutterwave.com/..." // The golden ticket 🎫
    },
    "success": true // Alhamdulillah! 
}
Enter fullscreen mode Exit fullscreen mode

Frontend Shenanigans: Where The Magic Happens ✨

Fun fact: This code was written while dreaming about iftar buffets!

Configuration: The Boring-But-Important Part πŸ₯±

export const CONFIGS = {
    APP_ENV: "development", // AKA "Please don't break in production"
    PAYMENTS_CALLBACK_URL: "https://example.com?foo=bar", // The comeback kid
};
Enter fullscreen mode Exit fullscreen mode

The Wallet Component: Money's Best Friend πŸ’°

// This function is like a waiter at a fancy restaurant
// It takes your order (amount) and brings back a payment link
async function fetchPaymentLink({ amount }) {
    // Magic happens here... or at least we hope so 🎩✨
    const response = await fetch(`/api/wallet/top-up`...);
    return data.data.link; // The golden ticket to happiness
}

// The component that makes your wallet cry tears of joy
function WalletCardComponent() {
    const balance = 1000; // Probably more than my actual bank account 😭
    const handleTopUp = useCallback(async () => {
        // Time to make it rain! πŸ’Έ
        const paymentLink = await fetchPaymentLink({ amount: 2000 });
        router.replace({/*... navigation magic ...*/});
        // HINT: You can pass the nextPath as a query param or a pathname
        // router.replace({ pathname: "/wallet/payment", params: { link: paymentLink, nextPath: "/wallet" } });
        // router.replace(`/wallet/payment?link=${paymentLink}&nextPath=/wallet`)
    }, []);

    return (
        <View>
            <Text>Wallet - {balance}</Text>
            <Button title="Make Money Disappear" onPress={handleTopUp} />
        </View>
    );
}
Enter fullscreen mode Exit fullscreen mode

The WebView: Where Dreams (and Transactions) Come True 🌈

function PaymentScreen() {
    // More params than a Hollywood movie
    const { link, nextPath, amount } = useLocalSearchParams();

    return (
        <WebView
            source={{ uri: link }} // The gateway to emptying your wallet
            startInLoadingState
            renderLoading={() => <ShowLoadingScreen />} // The "please wait" dance
            onNavigationStateChange={({ url }) => {
                if (url.includes("cancelled")) {
                    // When the user chickens out πŸ”
                    toast.error("Your money is still safe with you!");
                    return;
                }

                if (url.includes("success")) {
                    // Time to celebrate! πŸŽ‰
                    toast.success(`Successfully made money disappear! ✨`);
                    // HINT: you can redirect to the nextPath (Blessed flow πŸ‘ΌπŸ») or reload the entire app (Ibliss πŸ”ͺπŸ‘Ί)
                    // router.replace(nextPath...)
                }
            }}
        />
    );
}
Enter fullscreen mode Exit fullscreen mode

Conclusion: The End of Our Money Adventure 🎬

Like breaking fast with dates, every good implementation needs a sweet ending!

As we navigate through Ramadan (trying not to think about food while coding πŸ˜…), remember that implementing payments is like fasting - it requires patience, attention to detail, and a good sense of humor when things go wrong!

May your transactions be successful, your bugs be minimal, and your iftar be delicious! πŸ™


Written while dreaming about iftar, powered by dates and coffee (not at the same time, obviously!) πŸŒ™

P.S. If this code works, congratulations! If it doesn't, well... there's always next Ramadan! πŸ˜‰

Remember: In software development, like in Ramadan, patience is not just a virtue - it's a requirement! πŸ’«

Top comments (4)

Collapse
 
john_olatubosun profile image
John Olatubosun

Instresting and insightgul read 😌😌

Collapse
 
zahlen12 profile image
Sam

Thanks for the enlightenment

Collapse
 
ashiru_hammed_c63adb9f450 profile image
Ashiru Hammed

Interesting article keep it up

Collapse
 
becca_akin profile image
Rebecca Akinlade

Beautiful Piece. Learnt something new πŸ’―πŸ”₯πŸ”₯