Skip to content

magpieimdev/magpie-node-samples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Magpie Node.js SDK - Sample Applications

🚀 Complete examples demonstrating the Magpie Node.js SDK for payment processing

This repository contains sample applications that shows how to use Magpie Node.js SDK into your applications. Whether you're building a simple payment system or a complex e-commerce platform, these examples will help you get started quickly.

📋 Table of Contents

🚀 Quick Start

  1. Clone and install dependencies:

    git clone https://github.com/magpieim/magpie-node-samples.git
    cd magpie-node-samples
    npm install
  2. Configure your API key:

    cp .env.example .env
    # Edit .env and add your Magpie API key
  3. Run a basic example:

    npm run basic

That's it! You'll see an interactive demo of the Magpie SDK in action.

📚 Examples Overview

Example Description Technologies
Basic Customer management, simple payments, and charges JavaScript, Node.js
Advanced Checkout sessions, payment links, and refunds JavaScript, Express.js
TypeScript Integration Type-safe implementation with advanced patterns TypeScript, Modern JS

💻 Installation

Prerequisites

  • Node.js: Version 18.0.0 or higher
  • npm: Version 8.0.0 or higher (or yarn/pnpm)
  • Magpie API Key: Get yours from the Magpie Dashboard

Install Dependencies

# Using npm
npm install

# Using yarn
yarn install

# Using pnpm
pnpm install

⚙️ Configuration

Environment Variables

Copy .env.example to .env and configure the following:

# Required: Your Magpie API key
MAGPIE_SECRET_KEY=sk_test_your_test_key_here

# Optional: Environment (test or live)
MAGPIE_ENVIRONMENT=test

# Optional: API Configuration
MAGPIE_TIMEOUT=10000
MAGPIE_MAX_RETRIES=3
MAGPIE_DEBUG=true

# Optional: Sample Data
[email protected]
SAMPLE_CUSTOMER_NAME=John Doe
SAMPLE_CUSTOMER_PHONE=+63917123456

Getting Your API Key

  1. Sign up at Magpie Dashboard
  2. Navigate to API Keys in your dashboard
  3. Copy your Test key for development
  4. Use your Live key only in production

🏃‍♂️ Running Examples

Interactive Mode

Most examples support interactive mode where you can choose what to demonstrate:

# Basic integration with interactive menu
npm run basic

# Advanced payment flows with interactive menu
npm run advanced

# TypeScript example with full type safety
npm run typescript

Direct Execution

You can also run specific parts of the examples directly:

# Customer management only
npm run basic:customer

# Charge processing only
npm run basic:charge

# Checkout sessions only
npm run advanced:checkout

# Payment links only
npm run advanced:payment-links

Command Line Options

Many examples support command-line options:

# Run full basic demo non-interactively
node examples/basic/index.js --full

# Run specific advanced demo
npm run advanced -- --checkout
npm run advanced -- --refunds
npm run advanced -- --all

📖 Example Details

1. Basic (examples/basic/)

  • Initialize the Magpie SDK
  • Create and manage customers
  • Process simple charges
  • Handle payment sources
  • Implement error handling

Key files:

  • index.js - Main demo with interactive menu
  • customer-example.js - Customer management deep dive

Run it:

npm run basic

Sample output:

🎯 Welcome to Magpie SDK Basic Integration Demo!

✅ Customer created successfully!
{
  "id": "cus_1234567890",
  "name": "John Doe 1635789012345",
  "email": "[email protected]"
}

✅ Payment source created successfully!
{
  "id": "src_0987654321",
  "type": "card",
  "last4": "4242"
}

✅ Charge processed successfully!
{
  "id": "ch_abcdef123456",
  "amount": "₱500.00",
  "status": "succeeded"
}

2. Advanced Payment Flow (examples/advanced-flow/)

  • Create checkout sessions for hosted payments
  • Generate payment links for invoices
  • Process refunds (full and partial)
  • Handle complex payment scenarios
  • Implement payment intents

Key files:

  • index.js - Comprehensive advanced demo
  • checkout-example.js - Hosted checkout focus
  • payment-links-example.js - Invoice payment links

Run it:

npm run advanced

Features:

  • 🛒 Checkout Sessions: Hosted payment pages
  • 🔗 Payment Links: Send payment links to customers
  • 💰 Refund Processing: Full and partial refunds
  • 🏢 Complex Orders: Multi-item orders with metadata

3. TypeScript Integration (examples/typescript/)

  • Full TypeScript integration with Magpie SDK
  • Custom business type definitions
  • Type-safe error handling
  • Advanced TypeScript patterns (generics, utility types, etc.)
  • Dependency injection patterns

Key files:

  • index.ts - Main TypeScript demo
  • tsconfig.json - TypeScript configuration

Run it:

npm run typescript

🔧 API Reference

Core SDK Usage

const Magpie = require('@magpieim/magpie-node');

const magpie = new Magpie('sk_test_...', {
  timeout: 10000,
  maxNetworkRetries: 3,
  debug: true
});

Customer Management

// Create customer
const customer = await magpie.customers.create({
  name: 'John Doe',
  email: '[email protected]',
  phone: '+63917123456'
});

// Retrieve customer
const customer = await magpie.customers.retrieve('cus_123');

Payment Processing

// Create payment source
const source = await magpie.sources.create({
  type: 'card',
  card: {
    number: '4242424242424242',
    exp_month: 12,
    exp_year: 2026,
    cvc: '123'
  },
  customer: 'cus_123'
});

// Process charge
const charge = await magpie.charges.create({
  amount: 50000, // ₱500.00 in centavos
  currency: 'php',
  customer: 'cus_123',
  source: 'src_123',
  description: 'Payment for order #1234'
});

Checkout Sessions

// Create checkout session
const session = await magpie.checkout.sessions.create({
  line_items: [
    {
      name: 'Product Name',
      amount: 50000,
      currency: 'php',
      quantity: 1
    }
  ],
  success_url: 'https://example.com/success',
  cancel_url: 'https://example.com/cancel'
});

Error Handling

try {
  const charge = await magpie.charges.create({...});
} catch (error) {
  if (error instanceof Magpie.AuthenticationError) {
    console.log('Invalid API key');
  } else if (error instanceof Magpie.ValidationError) {
    console.log('Invalid parameters:', error.errors);
  }
}

🚦 Common Issues

API Key Issues

Problem: Authentication failed - check your API key

Solution:

  • Ensure your .env file exists and has the correct API key
  • Verify the key starts with sk_test_ for test mode
  • Check that the key is valid in your Magpie Dashboard

Network Issues

Problem: Network error - check your connection

Solution:

  • Check your internet connection
  • Verify Magpie API status
  • Try increasing the timeout in your configuration

TypeScript Issues

Problem: TypeScript compilation errors

Solution:

# Make sure TypeScript is installed
npm install -g typescript

# Compile the TypeScript example
npm run typescript:build

# Check for type errors
npx tsc --noEmit examples/typescript/index.ts

📞 Support

Getting Help

📜 License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Accept payments on your Node.js/Express-based website with cards, BPI, GCash, Maya, or QRPh

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published