Skip to content

magpieimdev/magpie-nextjs-ecommerce-sample

Repository files navigation

Magpie Next.js E-commerce Sample

This is a Next.js e-commerce sample project with Magpie Node SDK for hosted checkout payments. Features working payment flows, session management, and comprehensive integration patterns ready for production use.

Demo

Try it now: https://store-demo.dev.magpie.im

Experience the complete checkout flow with Magpie payment processing!

Demo Website Screenshot

Prerequisites

Node.js 20+

This project officially support the current LTS version – 20 at the time of writing. It should work on versions 18, 20, and 22. If you're using one of those versions and encounter a problem, please report it!

Installing Node.js Follow the instructions for your operating system found here: nodejs.org/en/download

pnpm 10+

This project uses pnpm as its package manager. If you don't have it installed, follow the instructions for your operating system found here: pnpm.io/installation

Quick Start

  1. Clone and install dependencies:

    git clone https://github.com/magpieimdev/magpie-nextjs-ecommerce-sample.git
    cd magpie-nextjs-ecommerce-sample
    pnpm install
  2. Run the development server:

    pnpm dev
  3. Open in browser: Open http://localhost:3000 to view the sample store.

Features

Core E-commerce Functionality

  • ✅ Product catalog with grid display
  • ✅ Shopping cart with localStorage persistence
  • ✅ Add/remove items with quantity controls
  • ✅ Hover-to-add-to-cart on product cards
  • ✅ Sliding cart drawer
  • Fully integrated Magpie checkout flow
  • Real payment processing with multiple payment methods
  • Payment verification and session management
  • ✅ Success and cancel pages with proper handling

Built With

  • Framework: Next.js 15 with App Router
  • Runtime: React 19
  • TypeScript: Full type safety throughout
  • Payments: Magpie Node SDK
  • Styling: Tailwind CSS + shadcn/ui components
  • Icons: Lucide React, Simple Icons
  • Package Manager: pnpm

Magpie SDK Integration

This project features a complete, working integration with the Magpie Node SDK. The implementation includes:

1. Checkout Flow (src/components/CheckoutButton.tsx)

The checkout button handles the complete flow from cart to payment:

const handleCheckout = async () => {
  // Call our checkout API route
  const response = await fetch('/api/checkout', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ items: cartItems }),
  });

  const { checkoutUrl } = await response.json();
  
  // Redirect to Magpie hosted checkout
  if (checkoutUrl) {
    window.location.href = checkoutUrl;
  }
};

2. Checkout Session Creation (src/app/api/checkout/route.ts)

Creates Magpie checkout sessions with full configuration:

const checkoutSession = await magpie.checkout.sessions.create({
  line_items: items.map((item) => ({
    name: item.name,
    amount: item.price * 100, // convert to cents
    currency: item.currency,
    quantity: item.quantity,
    description: item.description,
    image: `${process.env.NEXT_PUBLIC_BASE_URL}${item.image}`,
  })),
  currency: items[0]?.currency || "PHP",
  mode: "payment",
  payment_method_types: ["card", "bpi", "gcash", "paymaya", "qrph"],
  success_url: `${process.env.NEXT_PUBLIC_BASE_URL}/order/success`,
  cancel_url: `${process.env.NEXT_PUBLIC_BASE_URL}/order/cancel`,
});

3. Payment Verification (src/app/api/checkout/verify/route.ts)

Comprehensive payment verification with business logic integration points:

const session = await magpie.checkout.sessions.retrieve(sessionId);

if (session.payment_status === "paid") {
  // ✅ Payment confirmed - implement your business logic here
  console.log("✅ Payment verified successfully for session:", sessionId);
}

4. Success/Cancel Pages

Files:

  • src/app/order/success/page.tsx - Handles successful payments
  • src/app/order/cancel/page.tsx - Handles cancelled payments

These pages provide proper user feedback after payment completion or cancellation.

Getting Started with Magpie Integration

The Magpie Node SDK is already installed and integrated! Here's how to set it up:

Step 1: Environment Configuration

Copy .env.example to .env and add your Magpie credentials:

cp .env.example .env
# Your Magpie Secret Key (get this from Magpie Dashboard)
MAGPIE_SECRET_KEY=your_actual_secret_key_here

# Your domain for redirect URLs (optional, defaults to localhost:3000)
NEXT_PUBLIC_BASE_URL=https://your-domain.com

Step 2: Test the Integration

  1. Start the development server:

    pnpm dev
  2. Add items to cart and checkout:

    • Browse products and add items to cart
    • Click "Proceed to Checkout"
    • You'll be redirected to Magpie's hosted checkout
    • Complete payment with test credentials
  3. Payment Methods Supported:

    • Credit/Debit Cards
    • GCash
    • PayMaya
    • BPI Online
    • QRPH

Step 3: Customize Business Logic

The payment verification route (src/app/api/checkout/verify/route.ts) includes comprehensive examples for:

  • Database record updates
  • Order creation
  • Email notifications
  • Inventory management
  • Customer relationship management
  • Analytics tracking

Simply uncomment and adapt the code sections you need.

Customization

Adding Products

Edit src/lib/products.ts to add your own products:

export const sampleProducts: Product[] = [
  {
    id: 'your-product-id',
    name: 'Your Product',
    description: 'Product description',
    price: 99.99,
    currency: 'PHP',
    image: 'https://your-image-url.com/image.jpg',
    inStock: true,
  },
  // ... more products
];

Styling

  • Built with Tailwind CSS for easy customization
  • Uses shadcn/ui components that can be modified
  • Color scheme can be changed in src/app/globals.css

Cart Behavior

  • Cart persists in localStorage
  • Automatically clears after successful checkout
  • Quantity controls with add/remove functionality

Testing the Payment Flow

  1. Add items to cart: Hover over products and click "Add to Cart"
  2. View cart: Click the cart button to open the sliding drawer
  3. Modify quantities: Use +/- buttons in cart
  4. Checkout flow: Click "Proceed to Checkout" → redirects to real Magpie checkout
  5. Complete payment: Use test payment methods on Magpie's hosted page
  6. Success page: Redirects to /order/success after successful payment
  7. Cancel flow: Use cancel button on checkout page to test /order/cancel

Complete Payment Flow

  1. Add to Cart → Product added to localStorage
  2. View Cart → Drawer slides from right showing items
  3. Modify Cart → Update quantities or remove items
  4. Checkout → Redirect to Magpie hosted checkout with real payment processing
  5. Payment → Customer completes payment on secure Magpie checkout page
  6. Success → Return to success page, cart cleared, payment verified
  7. Cancel → Return to cancel page, cart preserved, no payment made

Production-Ready Features

Complete SDK Integration

  • Real payment processing with Magpie Node SDK
  • Multiple payment methods: Cards, GCash, PayMaya, BPI, QRPH
  • Session management with proper verification
  • Error handling for payment failures

Type Safety

All data structures are fully typed for SDK consumption:

interface CartItem {
  productId: string;
  quantity: number;
  product: Product;
}

interface Product {
  id: string;
  name: string;
  description: string;
  price: number;
  currency: string;
  image: string;
  inStock: boolean;
}

Business Logic Ready

The verification endpoint includes comprehensive integration points for:

  • Order management
  • Customer records
  • Email notifications
  • Inventory updates
  • Analytics tracking

URL Configuration

Success and cancel URLs are automatically configured based on your domain.

Deployment

Ready to deploy to Vercel, Netlify, AWS or any platform supporting Next.js:

pnpm build
pnpm start

Important: Make sure to set your environment variables in your deployment platform:

  • MAGPIE_SECRET_KEY - Your Magpie secret key
  • NEXT_PUBLIC_BASE_URL - Your production domain (for redirect URLs)

License

This sample project is provided as-is for demonstration purposes.

Support

Need help integrating your website to Magpie SDK? Contact us at support@magpie.im

About

Sample application for accepting one-time payments with Magpie Node SDK.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published