2.0.17 • Published 4 months ago

react-native-payengine v2.0.17

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

react-native-payengine v2

React Native SDK Version 2

Overview

The new version of the PayEngine React Native SDK is designed to provide developers with a more flexible and customizable payment experience. Its primary goal is to integrate with PayEngine native SDKs for both iOS and Android. By leveraging native SDKs (xcframework for iOS and AAR for Android), the SDK ensures a more seamless user experience without requiring codebase changes from multiple repositories.

Prerequisites

Add PayEngine Registry to your project

allprojects {
  repositories {
    ...your repositories

    maven { url 'https://www.jitpack.io' }
    maven {
      name = "pe-maven"
      url = uri("https://maven.payengine.co/payengine")
      credentials {
        username = "<username>"
        password = "<password>"
      }
    }
  }
}

Please contact PayEngine support for username and password

Install Package

yarn add react-native-payengine@2

Android

To use secure fields components, you need to install and configure the Material Components theme in your app.

  1. Add the following dependency to your app/build.gradle file with the specified version:
implementation 'com.google.android.material:material:<version>'
  1. Enable Jetifier in your app's gradle.properties if you encounter duplicate class issues like:
android.useAndroidX=true
android.enableJetifier=true

Example error:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkDebugDuplicateClasses'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
   > Duplicate class android.support.v4.app.INotificationSideChannel found in modules core-1.9.0.aar -> core-1.9.0-runtime
  1. Set the appropriate style in your styles.xml file:
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <!-- ... -->
</style>
  1. To use the Fraud Monitoring feature, change your main application class to extend PEApplication as shown:
public class MainApplication extends RNPEFraudAnalyticsApplication implements ReactApplication {
    // ...
}

Usage

Wrap the Config in a Provider

import { PEProvider } from 'react-native-payengine';

const App = () => {
  return (
    <PEProvider config={PE_CONFIG}>
      <NavigationContainer>
        <CreditCardForm />
        <BankAccountForm />
        <ApplePayScreen />
      </NavigationContainer>
    </PEProvider>
  );
};

Credit Card Form

import React from 'react';
import { PECreditCardView, PEKeyboardType } from 'react-native-payengine';
import { Button, View } from 'react-native';

const additionalFields = [
  {
    name: 'address_zip',
    type: 'text',
    placeholder: 'Zip code',
    keyboardType: PEKeyboardType.alphabet,
    isRequired: true,
    pattern:
      '^(?:\\d{5}(?:-\\d{4})?|[ABCEGHJKLMNPRSTVXY]\\d[A-Z] ?\\d[A-Z]\\d)$',
  },
];

const CreditCardForm = () => {
  const formRef = React.createRef();

  const createCard = async () => {
    try {
      const result = await formRef.current?.submit({
        merchantId: '<YOUR_MECHANT_ID>', // optional
        additionalData: {
          // additional data
        }
      });
      console.log({ result });
    } catch (err) {
      console.log({ err });
    }
  };

  return (
    <View>
      <PECreditCardView ref={formRef} additionalFields={additionalFields} />
      <Button onPress={createCard} title="Create Card" />
    </View>
  );
};

Bank Account Form

import React from 'react';
import { PEBankAccountView } from 'react-native-payengine';
import { Button, View } from 'react-native';

const BankAccountForm = () => {
  const formRef = React.createRef();

  const createBankAccount = async () => {
    try {
      const result = await formRef.current?.submit({
        merchantId: '<YOUR_MECHANT_ID>', // optional
        additionalData: {
          // additional data
        }
      });
      console.log({ result });
    } catch (err) {
      console.log({ err });
    }
  };

  return (
    <View>
      <PEBankAccountView ref={formRef} />
      <Button onPress={createBankAccount} title="Create Bank Account" />
    </View>
  );
};

Apple Pay

import React from 'react';
import { View, Text, ScrollView } from 'react-native';
import {
  PEApplePayButton,
  PEPaymentRequest,
  PayEngineNative,
  PayEngineUtils,
  RNPEContactField,
  PayProvider
} from 'react-native-payengine';
import axios from 'axios';

const ApplePayScreen = () => {
  const [canMakePayment, setCanMakePayment] = React.useState(false);
  const [paymentResult, setPaymentResult] = React.useState(null);

  React.useEffect(() => {
    const checkSupport = async () => {
      try {
        const isSupported = await PayEngineNative.userCanPay(PayProvider.applePay,
          MERCHANT_ID
        );
        console.log('isSupported', isSupported);
        setCanMakePayment(isSupported);
      } catch (e) {
        console.error('Apple Pay not supported', e);
      }
    };
    checkSupport();
  }, []);

  const paymentRequest: PEPaymentRequest = {
    merchantId: MERCHANT_ID,
    paymentAmount: 10.15,
    currencyCode: 'USD',
    paymentItems: [
      {
        amount: 10.15,
        label: 'Total Amount',
      },
    ],
    platformOptions: {
      requiredBillingContactFields: [RNPEContactField.postalAddress],
      requiredShippingContactFields: []
    }
  }

  const purchaseWithToken = async (token) => {
    // send the token to your server to make a purchase
    // ...
  };

  return (
    <View style={styles.container}>
      <Text>Apple Pay Demo</Text>
      {canMakePayment && (
        <>
          <PEApplePayButton
            paymentRequest={paymentRequest}
            onTokenDidReturn={(token) => {
              console.log('Apple Pay token', token);
              // Send token to server
              purchaseWithToken(token);
            }}
            onPaymentSheetDismissed={() => {
              console.log('Payment sheet dismissed');
            }}
            onPaymentFailed={(error) => {
              console.log('Payment failed', error);
            }}
            style={{ height: 40, margin: 20 }}
          />
          <ScrollView
            scrollEnabled
            style={{
              flex: 1,
              width: '100%',
              backgroundColor: 'lightyellow',
              padding: 10,
              marginVertical: 20,
            }}
          >
            <Text>{JSON.stringify(paymentResult, null, 4)}</Text>
          </ScrollView>
        </>
      )}
    </View>
  );
};

Google Pay

import React from 'react';
import { View, Text, ScrollView } from 'react-native';
import {
  PEGooglePayButton,
  PEPaymentRequest,
  PayEngineNative,
  PayProvider
} from 'react-native-payengine';

const GooglePayScreen = () => {
  const [canMakePayment, setCanMakePayment] = React.useState(false);
  const [paymentResult, setPaymentResult] = React.useState(null);

  React.useEffect(() => {
    const checkSupport = async () => {
      try {
        const isSupported = await PayEngineNative.userCanPay(PayProvider.googlePay,
          MERCHANT_ID
        );
        console.log('isSupported', isSupported);
        setCanMakePayment(isSupported);
      } catch (e) {
        console.error('Apple Pay not supported', e);
      }
    };
    checkSupport();
  }, []);

  const paymentRequest = {
    paymentAmount: amount,
    merchantId: MERCHANT_ID,
    platformOptions: {
      billingAddressRequired: true,
      billingAddressParameters: {
        format: 'FULL'
      },
      shippingAddressRequired: false
    }
  };

  const purchaseWithToken = async (token) => {
    // send the token to your server to make a purchase
    // ...
  };

  return (
    <View style={styles.container}>
      <Text>Google Pay Demo</Text>
      {canMakePayment && (
        <>
          <PEGooglePayButton
            paymentRequest={paymentRequest}
            onTokenDidReturn={(token) => {
              console.log('google Pay token', token);
              // Send token to server
              purchaseWithToken(token);
            }}
            onPaymentSheetDismissed={() => {
              console.log('Payment sheet dismissed');
            }}
            onPaymentFailed={(error) => {
              console.log('Payment failed', error);
            }}
            style={{ height: 40, margin: 20 }}
          />
          <ScrollView
            scrollEnabled
            style={{
              flex: 1,
              width: '100%',
              backgroundColor: 'lightyellow',
              padding: 10,
              marginVertical: 20,
            }}
          >
            <Text>{JSON.stringify(paymentResult, null, 4)}</Text>
          </ScrollView>
        </>
      )}
    </View>
  );
};

Dynamic Pricing

Note: Android doesn't support Dynamic pricing yet although it's supported on Web. Track the issue here https://issuetracker.google.com/issues/331369810?pli=1

iOS

Pass the platformOptions to the payment request:

const paymentRequest = {
  ...requestParameters,
  platformOptions: {
    requiredBillingContactFields: [RNPEContactField.postalAddress],
    requiredShippingContactFields: [RNPEContactField.name, RNPEContactField.postalAddress],
    shippingMethods: [
      {
        identifier: 'shipping-001',
        label: 'Free shipping',
        amount: 0.00
      },
      {
        identifier: 'shipping-002',
        label: 'Standard shipping',
        amount: 1.99
      },
      {
        identifier: 'shipping-003',
        label: 'Express shipping',
        amount: 2.99
      }
    ]
  }
}

Implement the callbacks:

<PEApplePayButton
  ...buttonOptions
  ref={buttonRef}
  onPaymentMethodSelected={(event) => {
    console.log('onPaymentMethodSelected', event.nativeEvent)

    const hasCreditDiscount = event.nativeEvent.paymentMethod.type === PEApplePayPaymentMethodType.credit
    buttonRef?.current?.updatePaymentSheet([
      {
        label: 'Product price',
        amount: paymentRequest.paymentAmount
      },
      ...hasCreditDiscount ? [{
        label: 'Credit discount',
        amount: 10
      }] : [],
      {
        label: 'Total',
        amount: paymentRequest.paymentAmount - (hasCreditDiscount ? 1.00 : 0.00)
      }
    ], [], [])
  }}
  onShippingContactSelected={(event) => {
    console.log('onShippingContactSelected', event.nativeEvent)

    if (!event.nativeEvent.contact.postalCode) {
      // invalid postalCode, update with error
      buttonRef?.current?.updatePaymentSheet([], [], [{
        errorType: PEApplePaySheetErrorType.InvalidShippingAddress,
        field: PEApplePayInvalidShippingField.PostalCode,
        message: 'Please update postal code to continue'
      }])
    } else if (event.nativeEvent.contact.postalCode === '90715') {
      // update shipping methods
      buttonRef?.current?.updatePaymentSheet([], [
        {
          identifier: 'new-shipping1',
          label: 'Updated shipping 1',
          amount: 3.99
        },
        {
          identifier: 'new-shipping2',
          label: 'Updated shipping 2',
          amount: 5.99
        }
      ], [])
    } else {
      // no update
      buttonRef?.current?.updatePaymentSheet([], [], [])
    }
  }}
  onShippingMethodSelected={(event) => {
    console.log('onShippingMethodSelected', event.nativeEvent)
    buttonRef?.current?.updatePaymentSheet([
      {
        label: 'Product price',
        amount: paymentRequest.paymentAmount
      },
      ...event.nativeEvent.shippingMethod.amount > 0 ? [{
        label: 'Shipping Fee',
        amount: event.nativeEvent.shippingMethod.amount
      }] : [],
      {
        label: 'Total',
        amount: paymentRequest.paymentAmount + event.nativeEvent.shippingMethod.amount
      }
    ], [], [])
  }}
/>

Important:

If either of onPaymentMethodSelected, onShippingContactSelected or onShippingMethodSelected callbacks are registered, you must update the Apple Pay sheet in your callback using buttonRef.current?.updatePaymentSheet(...) function, otherwise the Apple Pay shset will hang and the payment flow will automatically cancel.

2.0.15

4 months ago

2.0.16

4 months ago

2.0.13

7 months ago

2.0.14

6 months ago

2.0.17

4 months ago

2.0.11

8 months ago

2.0.12

8 months ago

2.0.9

8 months ago

2.0.10

8 months ago

2.0.7

8 months ago

2.0.8

8 months ago

2.0.2

9 months ago

2.1.1

9 months ago

2.0.5

9 months ago

2.0.4

9 months ago

2.0.6

8 months ago

2.0.0-beta.2

10 months ago

2.0.0-beta.1

10 months ago

2.0.0-beta.0

10 months ago

2.1.0

9 months ago

2.0.1

9 months ago

2.0.0

9 months ago

2.0.0-beta.3

10 months ago

1.0.6

1 year ago

1.0.5

3 years ago

0.1.7

3 years ago

0.1.6

3 years ago

0.1.5

3 years ago

0.1.4

3 years ago

0.1.3

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago