Skip to content

About

Gr4vy Embed SDK for React Native: a drop-in payment sheet on iOS and Android. Install from npm.

Topics

Resources

Code of conduct

Contributing

Stars

2 stars

Watchers

3 watching

Forks

Latest commit

 

History

268 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gr4vy for React Native

NPM Version GitHub license

Embed Gr4vy in your React Native app to store card details, authorize payments, and capture a transaction.

Requirements

  • React Native 0.75 or later (0.87 or later for Swift Package Manager mode)
  • iOS 15.0 or later, in the Podfile and in your app's Xcode project
  • Xcode 26 or later. With Xcode 16, CocoaPods builds fail with duplicate gr4vy_ios symbols. Apple requires Xcode 26 for App Store uploads.

Installation

yarn add @gr4vy/embed-react-native
# OR
npm install @gr4vy/embed-react-native

On iOS, link the module with CocoaPods or with React Native's Swift Package Manager (SPM) mode.

iOS: CocoaPods

Install the iOS pods:

cd ios && pod install

The iOS SDK, gr4vy-ios, comes from Swift Package Manager. React Native adds it to your Pods project during pod install. pod install prints a warning about Swift packages with static linking. You can ignore it: you don't need use_frameworks!.

If your app target has no Swift code (apps made from React Native 0.76 or earlier templates have an Objective-C AppDelegate), the link fails with Undefined symbols … __swift_FORCE_LOAD_$_swiftCompatibility56. Add an empty Swift file to the app target in Xcode, so that Xcode links the Swift libraries the SDK needs. You can skip the bridging header that Xcode offers.

On React Native 0.88, a clean build fails with module map file '…/gr4vy-embed-react-native/gr4vy_embed_react_native.modulemap' not found. React Native 0.88 builds the pod in a different folder from the one it gives your app. React Native 0.89 fixes this. Until then, add this at the end of the post_install block in your ios/Podfile, after react_native_post_install, and run pod install again:

installer.aggregate_targets.each do |aggregate_target|
  aggregate_target.xcconfigs.each do |config_name, config_file|
    %w[OTHER_CFLAGS OTHER_SWIFT_FLAGS].each do |key|
      next unless config_file.attributes[key]
      config_file.attributes[key] = config_file.attributes[key].gsub(
        '${PODS_CONFIGURATION_BUILD_DIR}/gr4vy-embed-react-native/gr4vy_embed_react_native.modulemap',
        '${PODS_CONFIGURATION_BUILD_DIR}/gr4vy_embed_react_native.modulemap'
      )
    end
    config_file.save_as(aggregate_target.xcconfig_path(config_name))
  end
end

If your app has a unit test target with inherit! :complete in the Podfile, a test build fails to link with undefined gr4vy_ios symbols. The test bundle links the pods a second time, so Xcode builds gr4vy-ios as a framework that your app does not link. Use inherit! :search_paths for the test target, and run pod install again. The tests then use the pods in the app.

iOS: Swift Package Manager

React Native 0.87 and later can build iOS apps with Swift Package Manager instead of CocoaPods. React Native marks this mode as experimental in 0.87 and 0.88, and plans to make it the default in 0.89.

@gr4vy/embed-react-native ships its own ios/Package.swift. React Native's autolinking finds it and links the module as the Gr4vyEmbedReactNative package, with gr4vy-ios 2.11.1 from GitHub. You don't need a patch or npx react-native spm scaffold for this module.

To move an app from CocoaPods to Swift Package Manager, run this once from the app's root folder:

npx react-native spm add --deintegrate

After you add or upgrade @gr4vy/embed-react-native, update the generated packages:

npx react-native spm update

Then open ios/<YourApp>.xcodeproj (not the .xcworkspace) to build the app. Keep ios/Podfile: @react-native-community/cli 20 finds the iOS project through it.

Upgrading from 2.x

Version 3 gets gr4vy-ios 2.11.1 from Swift Package Manager instead of CocoaPods, because CocoaPods trunk is read-only. Your app needs React Native 0.75 or later and an iOS deployment target of 15.0 or later. Run pod install after you upgrade.

On Android, version 3 gets the SDK from Maven Central (com.gr4vy:gr4vy-android) instead of JitPack. You can remove the JitPack repository from your app if nothing else uses it.

Usage

import EmbedReactNative, { EmbedReactNativeEventEmitter, Gr4vyEvent } from '@gr4vy/embed-react-native';

// Listen to events coming from Gr4vy Embed when launched

const onEvent = (event: Gr4vyEvent) => {
  const { name, data } = event
  console[name === 'generalError' ? 'error' : 'log'](name, data)
}

useEffect(() => {
  const onEventSubscription = EmbedReactNativeEventEmitter.addListener(
    'onEvent',
    onEvent
  )

  return () => {
    onEventSubscription.remove()
  }
}, [])

// Launch Gr4vy Embed

const handleCheckout = () => {
  EmbedReactNative.showPaymentSheet({
    gr4vyId: '[GR4VY_ID]',
    environment: 'sandbox',
    token: '[TOKEN]',
    amount: 1299,
    currency: 'USD',
    country: 'US',
    merchantAccountId: 'my-merchant-id', // optional for multi merchant instances
    ...
  })
}

<Button onClick={handleCheckout}>Pay</Button>

Note: Replace [GR4VY_ID] and [TOKEN] with the ID of your instance and JWT access token. See any of our server-side SDKs for more details.

Configuration

The options passed to showPaymentSheet via the configuration object are as follows.

Key Default value Description
gr4vyId null Required - The library automatically sets the API host to api.<gr4vyId>.gr4vy.app and Embed UI host to embed.<gr4vyId>.gr4vy.app for production, api.sandbox.<gr4vyId>.gr4vy.app and embed.sandbox.<gr4vyId>.gr4vy.app for the sandbox environment.
environment production The environment for the request. Can be sandbox or production.
token null Required - The server-side generated JWT token used to authenticate any of the API. calls.
amount null Required - The amount to authorize or capture in the specified currency.
currency null Required - A valid, active, 3-character ISO 4217 currency code to authorize or capture the amount for.
country null Required A valid ISO 3166 country code.
buyerId null An optional ID for a Gr4vy buyer. The transaction will automatically be associated to a buyer with that ID. If no buyer with this ID exists then it will be ignored.
buyerExternalIdentifier null An optional external ID for a Gr4vy buyer. The transaction will automatically be associated to a buyer with that external ID. If no buyer with this external ID exists then it will be ignored. This option is ignored if the buyerId is provided.
externalIdentifier null An optional external identifier that can be supplied. This will automatically be associated to any resource created by Gr4vy and can subsequently be used to find a resource by that ID.
store ask 'ask', 'preselect', true, false - Explicitly store the payment method, ask the buyer or preselect it by default. Requires buyerId or buyerExternalIdentifier.
display all all, addOnly, storedOnly, supportsTokenization - Filters the payment methods to show stored methods only, new payment methods only or methods that support tokenization.
intent authorize authorize, preferAuthorize, capture - Defines the intent of this API call. This determines the desired initial state of the transaction. When used, preferAuthorize automatically switches to capture if the selected payment method doesn't support delayed capture.
metadata null An optional object of key/values for transaction metadata. All values should be a string.
paymentSource null installment, moto, recurring - Can be used to signal that Embed is used to capture the first transaction for a subscription or an installment. When used, store is implied to be true and display is implied to be supportsTokenization. This means that payment options that do not support tokenization are automatically hidden.
applePayMerchantId null The Apple merchant ID to be used for Apple Pay transactions.
cartItems null An optional array of cart item objects, each object must define a name, quantity, and unitAmount. Other optional properties are discountAmount, taxAmount, externalIdentifier, sku, productUrl, imageUrl, categories, productType and sellerCountry.
theme null Theme customisation options See Theming Options. The SDK also contains an additional two properties within the colors object: headerBackground and headerText. These are used for the navigation background and foreground colors.
locale null An optional locale, this consists of a ISO 639 Language Code followed by an optional ISO 3166 Country Code, e.g. en, en-gb or pt-br.
statementDescriptor null An optional object with information about the purchase to construct the statement information the buyer will see in their bank statement. Please note support for these fields varies across payment service providers and underlying banks, so Gr4vy can only ensure a best effort approach for each supported platform.
As an example, most platforms will only support a concatenation of name and description fields, truncated to a length of 22 characters.
The object can contain name, description, phoneNumber, city and url keys, with string values. phoneNumber should be in E164 format. Gr4vy recommends avoiding characters outside the alphanumeric range and the dot (.) to ensure wide compatibility.
requireSecurityCode false An optional boolean which forces security code to be prompted for stored card payments.
shippingDetailsId null An optional unique identifier of a set of shipping details stored for the buyer.
merchantAccountId null An optional merchant account ID.
connectionOptions null An optional set of values passed to a connection when processing a transaction (see https://docs.gr4vy.com/reference/transactions/new-transaction)
buyer null An optional object to represent the buyer (personal details, billing details, and shipping information). This cannot be used in conjunction with buyerId or buyerExternalIdentifier.
installmentCount number An optional value that indicates the number of installments a buyer is required to make.
excludedMethods null An optional list of payment methods to exclude.
approvalExpiresAt null An optional datetime string (ISO 8601 format recommended) that sets the expiration date for transaction approval. If set to null, it is treated the same as if it were omitted.
debugMode false true, false - Prints useful debug information to the console.

Events

The library uses event emitters to send specific events happening in Embed back to the consumer (a React Native app). The object EmbedReactNativeEventEmitter can be imported and used to listen to such events.

useEffect(() => {
  // Add the listener
  const onEventSubscription = EmbedReactNativeEventEmitter.addListener(
    'onEvent',
    (event: Gr4vyEvent) => console.log(event)
  )

  return () => {
    // Remove the listener on cleanup
    onEventSubscription.remove()
  }
}, [])

The following events are emitted:

generalError

Returns data containing the message of an error that has occurred.

{
  "name": "generalError",
  "data": {
    "message": "Gr4vy Error: Failed to load"
  }
}

cancelled

Returned when the user cancels the SDK.

{
  "name": "cancelled",
  "data": {
    "message": "User cancelled"
  }
}

transactionCreated

Returns data about a successfully created transaction.

{
  "name": "transactionCreated",
  "data": {
    "success": true,
    "transactionId": "...",
    "status": "capture_succeeded",
    "paymentMethodId": "...",
    "approvalUrl": "https://example.com"
  }
}

transactionFailed

Returns data about a failed transaction.

{
  "name": "transactionFailed",
  "data": {
    "success": false,
    "transactionId": "...",
    "status": "authorization_failed",
    "paymentMethodId": "..."
  }
}

cardDetailsChanged

Returned when the card BIN changes in the form. It contains information on the inputted card, such as the BIN, card type and scheme.

{
  "bin": "42424242",
  "scheme": "visa",
  "cardType": "debit"
}

Apple Pay

To enable Apple Pay in your iOS project, in addition to passing the applePayMerchantId configuration option to the showPaymentSheet function, you'll also need to enable Apple Pay within the Signing & Capabilities Xcode project settings and set the Apple Pay Merchant IDs. Please ensure your provisioning profiles and signing certificates are updated to contain this valid Apple Merchant ID. The SDK will do various checks to ensure the device is capable of Apple Pay and will be enabled if both the device and merchant IDs are valid.

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

About

Gr4vy Embed SDK for React Native: a drop-in payment sheet on iOS and Android. Install from npm.

Topics

Resources

Code of conduct

Contributing

Stars

2 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages