# Monnify SDK for React Native CLI and Expo

`@adsesugh/monnify-react-native` is a React Native package that simplifies the integration of the Monnify payment gateway into React Native applications. This package is compatible with both React Native CLI and Expo projects.

## Features

- Easy integration of the Monnify payment gateway.
- Supports payment in Nigerian Naira (NGN).
- Handles payment completion and closure callbacks.
- Compatible with both React Native CLI and Expo.

## Installation

### For React Native CLI:

1. Install the package via npm or yarn:

   ```bash
   npm install @adsesugh/monnify-react-native
   # or
   yarn add @adsesugh/monnify-react-native
   ```

2. Install react-native-webview if haven't already:
   ```bash
    npm install react-native-webview
    npm install axios
    npm install react-native-safe-area-context
    # or
    yarn add react-native-webview
    yarn add axios
    yarn add react-native-safe-area-context
   ```

### For Expo:
1. Install the package via npm or yarn:
    ```bash
    npx expo install @adsesugh/monnify-react-native
   ```

2. Install react-native-webview using Expo:
    ```bash
    npx expo install react-native-webview
    npx expo install react-native-safe-area-context
    npm install axios
   ```
   
## Basic Example

```typescript
import React, { useState } from 'react';
import { StyleSheet, View, Text, Modal, Pressable } from 'react-native';
import { Monnify, MonnifyModal } from '@adsesugh/monnify-react-native'

// Initialize Monnify
const monnify = new Monnify({
  apiKey: "<api-key>",
  secretKey: "<secret-key>",
  contractCode: "<contract-code>",
  isTestMode: true,  // Set to false for production
});

export default function App() {
  const [checkoutUrl, setCheckoutUrl] = useState("");
  const [paymentRef, setPaymentRef] = useState("");
  const [visible, setVisible] = useState(false);

  const payNow = async () => {
    try {
      const paymentReference = `ref-${Date.now()}`;
      const res = await monnify.initializePayment({
        amount: 200,
        customerName: "John Doe",
        customerEmail: "johndoe@gmail.com",
        paymentReference,
        paymentDescription: "Test Payment",
        redirectUrl: "https://webhook.site/payment-complete",
      });

      setCheckoutUrl(res.checkoutUrl);
      setPaymentRef(paymentReference);
      setVisible(true);
    } catch (error: any) {
      Alert.alert("Payment Error", error.message)
    }
  };
 
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <<View style={{backgroundColor: 'green', padding: 2}}>
        <Button color={'white'} title="Pay with Monnify" onPress={payNow} />
      </View>
      <MonnifyModal
        visible={visible}
        checkoutUrl={checkoutUrl}
        transactionReference={paymentRef}
        monnifyInstance={monnify}
        onClose={(response) => {
          setVisible(false);
          if (response) {
            console.log('Payment completed with response:', response);
          }
        }}
        onPaymentComplete={(verifiedResponse) => {
          setVisible(false);

          if (verifiedResponse.success) {
            Alert.alert(
              "Payment Successful",
              `Amount: ₦${verifiedResponse.amountPaid}\nMethod: ${verifiedResponse.paymentMethod}\nRef: ${verifiedResponse.paymentReference}`
            );
          } else {
            console.log('Payment failed:', verifiedResponse);
            Alert.alert("Payment Failed", verifiedResponse.error || "Payment could not be verified");
          }
        }}
      />
    </View>
  );
}
```

### Props

| Prop                 | Type                      | Required | Description                                                                                            |
|----------------------|---------------------------|----------|--------------------------------------------------------------------------------------------------------|
| `visible`             | `boolean`                  | Yes      | Controls modal visibility.                                                                                 |
| `checkoutUrl`           | `string`                  | Yes      | The Payment checkout URL from initializePayment.                                              |
| `transactionReference`          | `string`                  | Yes      | Payment reference for verification.                                                        |
`apiKey`             | `string`                  | Yes      | The API key provided by Monnify.                                                                       |
| `contractCode`       | `string`                  | Yes      | The contract code provided by Monnify.                                                                 |
| `secretKey`       | `string`                  | Yes      | The secret key provided by Monnify.                                                                 |
`onPaymentComplete`          | `(response: any) => void` | No       | Callback function that is invoked when the transaction is completed successfully or error occurence.                      |
| `onClose`          | `() => void`              | No       | Callback function that is invoked when the payment modal is closed.                                    |

### Example with Income Split Configuration
 ```typescript
import Monnify from '@adsesugh/monnify-react-native';
import React, { useState } from 'react';
import { StyleSheet, View, Text, Modal, Pressable } from 'react-native';


export default function App() {
  const [checkoutUrl, setCheckoutUrl] = useState("");
  const [paymentRef, setPaymentRef] = useState("");
  const [visible, setVisible] = useState(false);

  const payNow = async () => {
    try {
      const paymentReference = `ref-${Date.now()}`;
      const res = await monnify.initializePayment({
        amount: 200,
        customerName: "John Doe",
        customerEmail: "johndoe@gmail.com",
        paymentReference,
        paymentDescription: "Test Payment",
        metadata: {name: "Damilare", age: 45},
        incomeSplitConfig: [
            {
            subAccountCode: "MFY_SUB_342113621921",
            feePercentage: 50,
            splitAmount: 1900,
            feeBearer: true,
            },
            {
            subAccountCode: "MFY_SUB_342113621922",
            feePercentage: 50,
            splitAmount: 2100,
            feeBearer: true,
            },
        ],
        redirectUrl: "https://webhook.site/payment-complete",
      });

      setCheckoutUrl(res.checkoutUrl);
      setPaymentRef(paymentReference);
      setVisible(true);
    } catch (error: any) {
      Alert.alert("Payment Error", error.message)
    }
  };
 
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <<View style={{backgroundColor: 'green', padding: 2}}>
        <Button color={'white'} title="Pay with Monnify" onPress={payNow} />
      </View>
      <MonnifyModal
        visible={visible}
        checkoutUrl={checkoutUrl}
        transactionReference={paymentRef}
        monnifyInstance={monnify}
        onClose={(response) => {
          setVisible(false);
          if (response) {
            console.log('Payment completed with response:', response);
          }
        }}
        onPaymentComplete={(verifiedResponse) => {
          setVisible(false);

          if (verifiedResponse.success) {
            Alert.alert(
              "Payment Successful",
              `Amount: ₦${verifiedResponse.amountPaid}\nMethod: ${verifiedResponse.paymentMethod}\nRef: ${verifiedResponse.paymentReference}`
            );
          } else {
            console.log('Payment failed:', verifiedResponse);
            Alert.alert("Payment Failed", verifiedResponse.error || "Payment could not be verified");
          }
        }}
      />
    </View>
  );
}
```

## License

MIT