MzuniPay

HomeFeaturesDevelopersLogin

Handling onSuccess and onError Callbacks with MzuniPay SDK

Overview

The onSuccess and onError callbacks in the MzuniPay SDK are designed to provide real-time feedback for payment processing. This document provides real-world examples of how to implement these callbacks effectively to handle both successful transactions and errors.


Example 1: Storing Payment Records in a Database

When a payment is successful, you may want to save the transaction details in your database.

Implementation

import MzuniPay from "mzunipay-sdk";

const mzuniPay = new MzuniPay("your-api-key-here");

mzuniPay.renderForm({
  containerId: "payment-form-container",
  onSuccess: async (response) => {
    console.log("Payment Successful!", response);

    try {
      // Save transaction to the database
      const res = await fetch("/api/save-transaction", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          transactionId: response.transactionId,
          amount: response.amount,
          customerEmail: response.customer_email,
          status: response.status,
        }),
      });

      if (!res.ok) {
        throw new Error("Failed to save transaction");
      }

      console.log("Transaction saved successfully!");
    } catch (error) {
      console.error("Error saving transaction:", error);
    }
  },
  onError: (error) => {
    console.error("Payment Failed!", error);
  },
  styled: true,
  buttonText: "Pay Now",
  defaultValues: {
    amount: 150.0,
    description: "Order #1234",
  },
});

Example 2: Showing User-Friendly Feedback to Customers

In a production environment, providing feedback to customers is crucial for good UX. Use the callbacks to display status messages dynamically.

Implementation

import MzuniPay from "mzunipay-sdk";

const mzuniPay = new MzuniPay("your-api-key-here");

mzuniPay.renderForm({
  containerId: "payment-form-container",
  onSuccess: (response) => {
    console.log("Payment Successful!", response);

    // Display a success message to the customer
    const statusDiv = document.getElementById("payment-status");
    statusDiv.innerHTML = '<p style="color: green; font-weight: bold;">Payment successful! Thank you for your purchase.</p>';
  },
  onError: (error) => {
    console.error("Payment Failed!", error);

    // Display an error message to the customer
    const statusDiv = document.getElementById("payment-status");
    statusDiv.innerHTML = `<p style="color: red; font-weight: bold;">Payment failed. Please try again or contact support.</p>`;
  },
  styled: true,
  buttonText: "Submit Payment",
  defaultValues: {
    amount: 200.0,
    description: "Subscription Payment",
  },
});

HTML Structure

<div id="payment-form-container"></div>
<div id="payment-status"></div>

Example 3: Logging Transactions for Analytics

You can log all transactions to a third-party analytics service for better insights.

Implementation

import MzuniPay from "mzunipay-sdk";

const mzuniPay = new MzuniPay("your-api-key-here");

mzuniPay.renderForm({
  containerId: "payment-form-container",
  onSuccess: (response) => {
    console.log("Payment Successful!", response);

    // Send transaction data to an analytics service
    fetch("https://analytics.example.com/log", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        event: "payment_success",
        transactionId: response.transactionId,
        amount: response.amount,
        customerEmail: response.customer_email,
      }),
    });
  },
  onError: (error) => {
    console.error("Payment Failed!", error);

    // Log errors to an error-tracking service
    fetch("https://analytics.example.com/log", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        event: "payment_error",
        error: error.message,
      }),
    });
  },
  styled: true,
  buttonText: "Pay Now",
  defaultValues: {
    amount: 100.0,
    description: "Service Fee",
  },
});

Example 4: Redirecting Users After Payment

Sometimes you may want to redirect users to a specific page after a successful or failed transaction.

Implementation

import MzuniPay from "mzunipay-sdk";

const mzuniPay = new MzuniPay("your-api-key-here");

mzuniPay.renderForm({
  containerId: "payment-form-container",
  onSuccess: (response) => {
    console.log("Payment Successful!", response);

    // Redirect to a thank-you page
    window.location.href = `/thank-you?transactionId=${response.transactionId}`;
  },
  onError: (error) => {
    console.error("Payment Failed!", error);

    // Redirect to an error page
    window.location.href = `/error?message=${encodeURIComponent(error.message)}`;
  },
  styled: true,
  buttonText: "Complete Payment",
  defaultValues: {
    amount: 250.0,
    description: "Event Ticket Purchase",
  },
});

Notes

  1. Always validate responses on your server before performing sensitive operations like saving records or redirecting users.
  2. Test the behavior of both onSuccess and onError callbacks under different scenarios.
  3. Customize the error messages and feedback to align with your application’s tone and branding.