npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

netopia-card

v2.1.1

Published

Improved Netopia card gateway library

Downloads

779

Readme

Netopia Card

Version 2 Update Notice: This version (v2) introduces significant changes from v1, including configuration options and methods. Please see the migration guide below for details.

Netopia Card is a lightweight NodeJS library designed to integrate the Netopia mobilPay payment gateway into your projects with ease. It allows for the construction of Netopia mobilPay requests from input data and validates Netopia mobilPay responses using the private key associated with your account.

Installation

To add Netopia Card to your project, run:

npm install netopia-card
# or, using Yarn
yarn add netopia-card

Features

  • Easy-to-use API for initiating card payments and handling callbacks
  • Robust validation of Netopia mobilPay responses for secure transaction processing

Note

Currently, split payments and setting custom parameters are not available due to the transition from v1 to v2, but these features will be available soon.

Configuration

Before using Netopia Card, set your environment variables based on the credentials provided by Netopia for your sales point.

API_BASE_URL="https://example.com/"
NETOPIA_API_KEY="Your_API_Key_Here"
NETOPIA_CONFIRM_URL="https://example.com/api/payment/notify"
NETOPIA_RETURN_URL="https://example.com/redirect"
NETOPIA_SIGNATURE="XXXX-XXXX-XXXX-XXXX-XXXX"

These credentials can be found in the NETOPIA Payments admin > Profile > Security.

Quick Start

First, import the library into your project:

const { Netopia } = require('netopia-card');

Create a new instance of Netopia by providing your API key and other configuration options:

const netopia = new Netopia({
  apiKey: process.env.NETOPIA_API_KEY,
  sandbox: true, // Use `false` for production
});

Frontend Integration

To handle the payment redirection in a React application using Next.js:

import { useRouter } from 'next/router';
import { useEffect, useRef } from 'react';

const NetopiaRedirect = ({ error, payment }) => {
  const router = useRouter();
  const ref = useRef();

  useEffect(() => {
    if (error?.code === '101' && payment?.paymentURL) {
      ref.current.click();
    }
  }, [error, payment]);

  if (!error?.code === '101' || !payment?.paymentURL) {
    return null;
  }

  return (
    <button
      className="hidden"
      onClick={() => router.push(payment.paymentURL)}
      ref={ref}
      type="button"
    />
  );
};

export default NetopiaRedirect;

Integrate the form and payment handling logic

Here's an example of how to integrate the form and payment handling logic using Formik and a simple form component:

import { useState } from 'react';
import { Formik, Form, Field } from 'formik';
import { NetopiaRedirect } from './NetopiaRedirect';
import { collectBrowserInfo } from 'netopia-card';
import { useMutation } from 'react-query';
import axios from 'axios';

const PaymentForm = () => {
  const [netopia, setNetopia] = useState({});

  const mutation = useMutation((payload) => axios.post('/api/payment/start', payload));

  const handleSubmit = async (values) => {
    const payload = {
      ...collectBrowserInfo(navigator, window),
      invoiceData: values,
    };
    try {
      const { data } = await mutation.mutateAsync(payload);
      setNetopia(data);
    } catch (error) {
      console.error('Payment initiation failed:', error);
    }
  };

  return (
    <Formik initialValues={{ firstName: '', lastName: '', email: '' }} onSubmit={handleSubmit}>
      <Form>
        <div>
          <label htmlFor="firstName">First Name</label>
          <Field id="firstName" name="firstName" placeholder="John" />
        </div>
        <div>
          <label htmlFor="lastName">Last Name</label>
          <Field id="lastName" name="lastName" placeholder="Doe" />
        </div>
        <div>
          <label htmlFor="email">Email</label>
          <Field id="email" name="email" type="email" placeholder="[email protected]" />
        </div>
        <button type="submit">Submit</button>
        <NetopiaRedirect {...netopia} />
      </Form>
    </Formik>
  );
};

export default PaymentForm;

Backend API

To start a payment, use the startPayment method with the necessary payment details:

const express = require('express');
const { Netopia } = require('netopia-card');

const router = express.Router();

router.post('/api/payment/start', async (req, res) => {
  const netopia = new Netopia({
    apiKey: process.env.NETOPIA_API_KEY,
    sandbox: true,
  });

  const requestData = {
    // Define your request data here
  };

  try {
    const response = await netopia.startPayment(requestData);
    res.status(200).json(response);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;

Handle payment notifications by creating a notification route:

const express = require('express');
const { rawTextBodyParser } = require('netopia-card');
const { confirmOrder } = require('./orderHandlers');

const app = express();

app.post('/api/payment/notify', rawTextBodyParser, async (req, res) => {
  try {
    const { order, payment } = JSON.parse(req.body);
    if (!order || !payment) {
      throw new Error('Invalid request body');
    }

    await confirmOrder({ order, payment });

    res.status(200).json({ errorCode: 0 });
  } catch (error) {
    res.status(400).json({ errorCode: 1 });
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));

Migration Guide from v1 to v2

Version 2 of Netopia Card introduces several key changes:

  • The configuration process now includes setting the API_BASE_URL in your environment variables. This URL is used to construct the full URL for the Netopia notify callback endpoint.
  • The startPayment and createNotifyRoute methods have been updated to accommodate the new configuration options.
  • Removal of redirectUrl from the Config type in favor of a server-side handling approach for payment completion redirection.

To migrate from v1 to v2:

  1. Update your environment variables to include API_BASE_URL.
  2. Adjust your Netopia instantiation to include the new apiBaseUrl option if you were previously passing redirectUrl and notifyUrl directly to the startPayment method.
  3. Update any calls to startPayment to match the new method signature.

Further Resources

For detailed information on the API and configuration options, please refer to the NETOPIA Payments - merchant API.

Contributing

We welcome contributions to improve Netopia Card. Please feel free to submit pull requests or report issues via the GitHub repository.

License

Netopia Card is licensed under the MIT License. See the LICENSE file for more details.