react-native-payengine
v2.0.18-alpha.6
Published
PayEngine SDK for React Native
Downloads
515
Maintainers
Readme
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@2Important Configuration When Developing on Android
To use secure fields components, you need to install and configure the Material Components theme in your app.
- Add the following dependency to your
app/build.gradlefile with the specified version:
implementation 'com.google.android.material:material:<version>'- Enable Jetifier in your app's
gradle.propertiesif you encounter duplicate class issues like:
android.useAndroidX=true
android.enableJetifier=trueExample 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- Set the appropriate style in your
styles.xmlfile:
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- ... -->
</style>- To use the Fraud Monitoring feature, change your main application class to extend
PEApplicationas shown:
public class MainApplication extends RNPEFraudAnalyticsApplication implements ReactApplication {
// ...
}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>
);
};Set the Fetch Access Token Callback
This is a required callback that you need to set in the SDK for the other functionalities to work properly.
Please check the documentation for setFetchAccessTokenCallback to understand the implementation details.
Examples
The following examples demonstrate how to integrate and use the components provided by the PayEngine SDK within your application. Some features require additional configuration or platform-specific setup; these examples will also outline any prerequisites to ensure a smooth implementation.
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>
);
};Google Pay
Google Pay is available on Android devices that support Google’s payment platform. After enabling Google Pay on your account, you can use the PEGooglePayButton component to initiate the Google Pay in-app payment flow.
Before implementing Google Pay through the PayEngine SDK, you must ensure that Google Pay is enabled for your PayEngine account. To do this, contact your PayEngine support representative to activate it.
For step-by-step instructions and additional details, refer to the official PayEngine documentation:
👉 https://docs.payengine.co/developer-docs/processing-payments/google-pay-tm
Once Google Pay is enabled for your account, you can proceed with the implementation example shown below.
Example Usage
import React from 'react';
import { View, Text, ScrollView } from 'react-native';
import {
PEGooglePayButton,
PEPaymentRequest,
PayEngineNative,
PayProvider
} from 'react-native-payengine';
const GooglePayScreen = () => {
const MERCHANT_ID = 'Your merchant\'s id in the PayEngine system'
const [canMakePayment, setCanMakePayment] = React.useState(false);
const [paymentResult, setPaymentResult] = React.useState(null);
// Checking if the device supports Google Pay
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('Google 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.
// Your server then forwards the token PayEngine APIs to perform a transaction.
};
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>
);
};Apple Pay
Apple Pay is available only on iOS devices, in accordance with Apple’s platform requirements. After completing the required configuration and confirming support, you can use the PEApplePayButton component to launch the Apple Pay payment sheet.
Before implementing Apple Pay through the PayEngine SDK, you must complete the necessary native iOS setup. This includes configuring merchant identifier, enabling Apple Pay capability in XCode, creating and uploading the required certificate.
For step-by-step instructions, refer to the official PayEngine documentation:
👉 https://docs.payengine.co/developer-docs/processing-payments/apple-pay/apple-pay-in-your-native-app
When the guide refers to “Integrate with Xcode”, it means opening the iOS project located in your React Native application’s ./ios directory. Once opened in Xcode, follow the steps outlined in the documentation to enable Apple Pay support for your app.
After completing the native setup, you can proceed with the implementation example shown below.
Example Usage
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 MERCHANT_ID = 'Your merchant\'s id in the PayEngine system'
const [canMakePayment, setCanMakePayment] = React.useState(false);
const [paymentResult, setPaymentResult] = React.useState(null);
// Checking if the device supports Apple Pay
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.
// Your server then forwards the token PayEngine APIs to perform a transaction.
};
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>
);
};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
}
]
}
}<PEApplePayButton
paymentRequest={paymentRequest}
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.
