Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Shopify Custom Payment Gateway for Nepal

By Kokil Thapa | Last reviewed: August 2026

Integrating a Shopify Custom Payment Gateway for Nepal remains one of the most frequent requests I handle from local merchants who have outgrown manual bank transfer workflows. While Shopify’s native provider list has expanded, direct API-level integrations for eSewa, Khalti, IME Pay, and ConnectIPS still require custom middleware or specialized app configurations to function reliably in production. If you are running a Nepali store on Shopify in 2026, you likely need a bridge between Shopify’s standardized checkout flow and the specific authentication requirements of local wallet providers.

For many business owners, the decision to move beyond standard international gateways like Stripe or PayPal comes down to customer preference; Nepali buyers overwhelmingly prefer local wallets and banking apps. If you are evaluating whether to build this yourself or hire help, my guide on Shopify vs WooCommerce for Nepali businesses covers the trade-offs in platform flexibility versus maintenance overhead. Building a custom gateway is technically feasible but demands strict adherence to security standards, as you are handling financial transaction verification directly.

How does the Shopify Custom Payment Gateway for Nepal architecture work?

Understanding the data flow is critical before writing a single line of code. Shopify does not allow you to inject arbitrary PHP or Node.js code directly into its checkout server. Instead, you must use either the Hosted Payment SDK (for legacy stores) or Checkout Extensibility (for Shopify Plus and newer plans). In both cases, your external server acts as the trusted intermediary.

Shopify Checkout(Customer Browser)Custom Middleware(Laravel / Node.js)• Signature Gen• Webhook Verify• Order MappingeSewa / Khalti(Payment Provider)ConnectIPS / Bank(Banking Network)1. Initiate2. API Call2. API Call
Secure architecture for Shopify Custom Payment Gateway for Nepal showing middleware responsibility

The diagram above illustrates why you cannot simply call the eSewa API from the Shopify frontend. Your secret keys would be exposed in client-side JavaScript, allowing anyone to forge transactions. The middleware receives a signed request from Shopify, generates the provider-specific HMAC signature server-side, redirects the user or returns a token, and then listens for the asynchronous confirmation. This separation of concerns is non-negotiable for any Shopify Custom Payment Gateway for Nepal handling real money.

What are the technical requirements for integrating eSewa and Khalti?

Both major Nepali wallets have updated their APIs significantly by 2026. Legacy XML-based eSewa implementations found in old tutorials will fail against current endpoints. You must target the REST/JSON APIs with proper HMAC-SHA256 signing.

eSewa EPAY v2/v3 Integration

eSewa now mandates signed payloads for all transaction initiations. Your middleware must construct a parameter string in a specific alphabetical order, sign it with your merchant secret key, and pass the resulting hash. Never hardcode these keys; use environment variables managed through your deployment pipeline.

<?php
// Laravel Middleware Example - eSewa Signature Generation
public function generateEsewaSignature(array $params, string $secretKey): string
{
    // Sort parameters alphabetically as per eSewa 2026 spec
    ksort($params);
    
    // Build query string without URL encoding for signature base
    $signatureString = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
    
    // HMAC-SHA256 signature
    return hash_hmac('sha256', $signatureString, $secretKey);
}

// Usage in controller
$params = [
    'amount' => $order->total_npr,
    'tax_amount' => 0,
    'total_amount' => $order->total_npr,
    'transaction_uuid' => $order->uuid,
    'product_code' => config('services.esewa.product_code'),
    'product_service_charge' => 0,
    'product_delivery_charge' => 0,
    'success_url' => route('payments.esewa.success'),
    'failure_url' => route('payments.esewa.failure'),
    'signed_field_names' => 'total_amount,transaction_uuid,product_code',
];

$params['signature'] = $this->generateEsewaSignature($params, config('services.esewa.secret_key'));

Khalti Payment Gateway Verification

Khalti’s 2026 API simplifies initiation but enforces strict server-side verification. After a customer completes payment, Khalti redirects to your success URL with a pidx (payment index). You must call the lookup endpoint server-side to confirm the amount matches exactly. Relying solely on the redirect parameters is a security vulnerability that allows customers to modify the paid amount before order confirmation.

  • Currency Handling: Always store prices in NPR as integers (paisa) in your database. Convert to decimal only at the presentation layer. Shopify’s multi-currency feature can cause rounding errors if your gateway doesn’t validate the exact NPR amount received.
  • Idempotency: Use the transaction_uuid or pidx as an idempotency key. Network timeouts between Kathmandu and cloud servers are common; your system must safely handle duplicate webhook deliveries without creating double orders.
  • Test Environment Parity: Both providers offer sandbox environments. Ensure your middleware uses configuration-driven switching so you never accidentally process live NPR during staging tests.

How do you handle webhooks and transaction verification securely?

The most common failure point in Nepal payment integrations is treating the success redirect as proof of payment. It is not. Redirects can be manipulated, skipped, or delayed. Only a verified server-to-server webhook or explicit API lookup constitutes valid proof.

ShopifyMiddlewareProvider1. Create Pending Order2. Initiate Payment3. Async Webhook (POST)Verify Signature4. Lookup Confirmation5. Return Status + Amount6. Confirm Order via Admin API
Secure verification sequence preventing fraud in Nepal payment integrations

In practice, I implement a "trust but verify" pattern. When the webhook arrives, I first validate the HMAC signature using the provider’s public key or shared secret. Then, I make an independent API call to fetch the transaction details. Only if the webhook signature is valid AND the API lookup confirms the exact expected amount do I transition the Shopify order from "Pending" to "Paid." This double-check prevents race conditions where a webhook arrives before your database has fully recorded the pending state.

For developers building this in Laravel, leverage the queue system for webhook processing. Accept the HTTP 200 response immediately to prevent the provider from retrying, then dispatch a job to perform the verification and Shopify API update. This decouples ingestion from processing and avoids timeout-related duplicate charges. My article on Laravel payment integrations details this pattern further for general PHP applications.

Should you use a custom app or an existing Nepal payment plugin?

This is the most practical decision you will face. Several third-party apps on the Shopify App Store now claim Nepal support, but their quality varies dramatically. Before committing to a monthly subscription or a custom build, evaluate these factors against your actual business needs.

CriteriaExisting Shopify AppCustom Middleware Solution
Setup TimeHours to days2–4 weeks development + testing
Monthly Cost$10–$30 USD (~NPR 1,300–4,000)Server cost only (~NPR 500–1,500/mo)
Transaction FeesOften 1–2% on top of provider feesZero additional markup
CustomizationLimited to app settingsFull control over UX, receipts, logic
Maintenance BurdenVendor handles API updatesYou own all upgrades and security patches
Data OwnershipTransaction data passes through vendorAll data stays in your infrastructure
Multi-Gateway SupportUsually single provider per appUnified interface for eSewa, Khalti, Banks

If you are a solo founder validating a product, start with an existing app even if it costs more per transaction. The time savings outweigh the fees until you hit consistent volume. However, once you process over NPR 500,000 monthly, the 1–2% app surcharge exceeds the cost of maintaining a custom solution. For established businesses, especially those needing unified reporting across multiple Nepali payment methods, custom middleware pays for itself within months.

I’ve seen merchants lose significant margins to app fees simply because they never revisited this decision after launch. Audit your payment costs quarterly. If you’re considering a full rebuild or migration, understanding the broader eCommerce development landscape in Nepal helps contextualize whether Shopify remains the right platform or if a Laravel-based store offers better long-term unit economics.

What are the common pitfalls when deploying Nepal gateways in 2026?

After debugging numerous production incidents involving Nepali payment gateways, certain patterns emerge repeatedly. Avoiding these saves days of troubleshooting and potential revenue loss.

  1. Ignoring Currency Precision: Shopify stores prices as decimals; Nepali wallets expect integer paisa. A Rs 1,000.50 order sent as "1000.5" may be rejected or truncated. Always multiply by 100 and cast to integer before API calls. Validate the returned amount matches exactly after dividing back.
  2. Missing SSL/TLS Enforcement: Both eSewa and Khalti reject webhook endpoints without valid TLS 1.2+ certificates. Let’s Encrypt works fine, but ensure your Nginx/Apache configuration disables older protocols. Test with SSL Labs before going live.
  3. Timezone Mismatches: Nepal operates on NPT (UTC+5:45). Server logs in UTC create confusion when reconciling transactions. Configure your middleware to log in Asia/Kathmandu timezone while storing timestamps in UTC. Display converted times in admin dashboards.
  4. Inadequate Error Messaging: Generic "Payment Failed" messages increase support tickets. Map provider error codes to user-friendly Nepali/English messages. "Insufficient Balance" is better than "Error Code 402." Log the raw response internally for debugging.
  5. Skipping Sandbox Load Testing: Production behavior differs under concurrent load. Simulate 50+ simultaneous webhook deliveries in staging. Verify your idempotency locks prevent duplicate processing. Redis or database advisory locks are essential here.
Payment Failed?Check Webhook LogsNo Webhook ReceivedWebhook ReceivedNetwork / DNS IssueCheck Firewall & SSLSignature MismatchVerify Secret Key & ParamsAmount MismatchCheck Decimal/Paisa ConvProvider DowntimeCheck Status Page / Retry
Troubleshooting decision tree for Nepal payment gateway failures

One subtle issue specific to Nepal infrastructure is intermittent connectivity between cloud servers (AWS/GCP/DigitalOcean) and local payment providers. If your middleware is hosted overseas, latency spikes can cause webhook timeouts. Consider hosting your payment middleware on a reliable VPS with good South Asia peering, or implement aggressive retry logic with exponential backoff. For high-volume stores, a dual-region setup with automatic failover provides resilience against regional network issues.

Next Steps for Implementation

Building a Shopify Custom Payment Gateway for Nepal is a serious engineering undertaking that directly impacts your revenue stream. Start by mapping your exact payment flows, including edge cases like partial refunds, cancellations, and multi-item orders with mixed tax rates. Set up isolated staging environments for both Shopify and your middleware before touching production credentials.

If you are managing this internally, prioritize automated testing for signature generation and webhook verification — these are the most fragile components. If you need expert guidance or prefer to delegate the implementation, contact me to discuss your specific requirements. I’ve built and maintained Nepal payment integrations across Shopify, WooCommerce, and custom Laravel platforms, and can help you avoid the costly mistakes that come from learning through production failures.

Frequently Asked Questions

No, Shopify does not list eSewa, Khalti, IME Pay, or ConnectIPS as native providers. You must use the Custom Payment app or build a private app using the Payments Extension API to integrate these local services.

Custom gateway development typically costs Rs 80,000–150,000 (USD 600–1,125) depending on complexity. This covers API integration, webhook handling, testing, and deployment but excludes ongoing maintenance or Shopify Plus fees if required for advanced checkout customization.

Yes, enable Bank Deposit or Cash on Delivery in Settings > Payments. This avoids development costs entirely but requires manual reconciliation and lacks automated order confirmation, making it unsuitable for high-volume stores needing real-time payment verification.

The Custom Payment app is a no-code solution for manual methods like bank transfers. The Payments Extension API allows programmatic integration with providers like eSewa or Khalti, enabling automatic callbacks, refund processing, and real-time transaction status updates within Shopify checkout.

Not necessarily. Standard Shopify plans support third-party payment providers via the Payments Extension API. However, Shopify Plus offers Checkout Extensibility for deeper UI customization and post-purchase flows that may improve conversion rates for Nepal-specific payment workflows.

Your custom app must expose an HTTPS endpoint receiving POST requests from eSewa or Khalti after payment completion. Validate the signature, match the transaction ID to the Shopify order, then call the Admin API to mark the order as paid. Always implement idempotency to prevent duplicate processing.

No, because card data never touches your server. These gateways handle sensitive information directly. Your responsibility is securing API keys, validating webhook signatures, and ensuring your callback endpoint uses TLS 1.2+. Never store raw credentials in code repositories or environment files accessible publicly.

This usually indicates failed webhook delivery or incorrect order matching. Check your app logs for HTTP 4xx/5xx responses from Shopify, verify the transaction reference format matches exactly, and confirm your webhook URL is whitelisted in the gateway dashboard. Test with sandbox credentials first.

Most Nepali gateways only process NPR transactions. For USD payments, you need a separate international provider like Stripe or PayPal alongside your local integration. Configure currency routing in Shopify Markets so customers see appropriate options based on their location and selected currency.

Merchant account approval typically takes 3–7 business days after submitting KYC documents and business registration. Technical integration testing can proceed in parallel using sandbox credentials. Factor this timeline into project planning, especially during Dashain/Tihar seasons when processing delays are common.

Implement graceful degradation by catching timeout exceptions and displaying a user-friendly message suggesting alternative payment methods. Log failures for monitoring, and consider a circuit breaker pattern to prevent cascading failures. Never expose raw API errors to customers, as this leaks infrastructure details and damages trust.

Development is one-time, but budget Rs 5,000–15,000 monthly (USD 37–112) for monitoring, security patches, and API version updates. Gateways occasionally change endpoints or authentication methods. Without proactive maintenance, integrations break silently, causing lost sales and customer support overhead during peak seasons.

Both providers offer sandbox environments with test credentials and simulated transactions. Use these extensively before going live. Verify successful payments, failed attempts, refunds, and webhook deliveries. Never test with production keys, even for small amounts, as accidental charges create reconciliation headaches and customer disputes.

Yes, if you architect your integration with a payment provider abstraction layer. Each gateway implements a common interface for authorization, capture, and refund operations. Adding new providers becomes configuration rather than rewriting core logic. This pattern pays dividends as Nepal's payment landscape continues evolving rapidly.

Require Content-Security-Policy, X-Content-Type-Options: nosniff, and Strict-Transport-Security headers. Validate Origin and Referer against expected values. Rate-limit requests per IP to prevent abuse. Log all incoming webhooks with timestamps and IPs for forensic analysis. These measures protect against replay attacks and unauthorized transaction manipulation.

Share this article

Quick Contact Options
Choose how you want to connect me: