# @olo/pay-react-native

## Table Of Contents

- [About Olo Pay](#about-olo-pay)
- [About the React Native SDK](#about-the-react-native-sdk)
- [Installation](#installation)
- [Getting Started](#getting-started)
- [Handling Promise Rejections](#handling-promise-rejections)
- [Events](#events)
- [Components](#components)
  - [PaymentCardDetailsView](#paymentcarddetailsview)
  - [PaymentCardDetailsForm](#paymentcarddetailsform)
  - [PaymentCardCvvView](#paymentcardcvvview)
- [OloPaySDK Module](#olopaysdk-module)

## About Olo Pay

[Olo Pay](https://www.olo.com/solutions/pay/) is an E-commerce payment solution designed to help restaurants grow, protect, and support their digital ordering and delivery business. Olo Pay is specifically designed for digital restaurant ordering to address the challenges and concerns that weʼve heard from thousands of merchants.

## About the React Native SDK

The Olo Pay React Native SDK allows partners to easily add PCI-compliant Apple Pay and Google Pay functionality to their checkout flow and seamlessly integrate with the Olo Ordering API.

Use of the plugin is subject to the terms of the [Olo Pay SDK License](#License).

For more information about integrating Olo Pay into your payment solutions, refer to our [Olo Pay Dev Portal Documentation](https://developer.olo.com/docs/load/olopay) _(Note: requires an Olo Developer account)_.

## Installation

### **_Important_:** If using [Expo](https://expo.dev/), be sure to [eject](https://docs.expo.dev/archive/glossary/#eject) or run [`npx expo prebuild`](https://docs.expo.dev/workflow/prebuild/) prior to installation

Run the following command from a terminal in your app's root project directory

```sh
npm install @olo/pay-react-native
```

### Android-Specific Install Steps

#### Supported Versions

- _Minimum SDK Version:_
  - The minimum supported Android SDK is [API 23](https://developer.android.com/tools/releases/platforms#6.0)
  - The Android project's `minSdkVersion` must be set to `23` or higher
- _Compile SDK Version:_
  - The Olo Pay SDK is compiled against [API 33](https://developer.android.com/tools/releases/platforms#13)
  - It is recommended to set the Android project's `compileSdkVersion` to `33` or higher
- _Gradle:_
  - The SDK is built with Gradle `v7.4` and Android Gradle Plugin `v7.3.1`
  - If the Android project does not compile, the Android Gradle Plugin and/or Gradle versions may need to be updated

#### Components

In order to use the `PaymentCardFormView` you need to install and configure [Material Components theme](https://github.com/material-components/material-components-android/blob/master/docs/getting-started.md#4-change-your-app-theme-to-inherit-from-a-material-components-theme) in your app.

1. In your `app/build.gradle` add the dependency with a specific version

```groovy
implementation 'com.google.android.material:material:<version>'
```

1. Set the appropriate style in your `styles.xml` file

```xml
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight">
    <!-- ... -->
</style>
```

### iOS-Specific Install Steps

#### Supported Versions

- _Minimum iOS Version:_
  - The minimum supported version is [iOS 14](https://support.apple.com/en-us/118390#14)

In you app's Podfile:

- Add the following lines at the top:

```Podspec
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/ololabs/podspecs.git'
```

- Ensure that `ios.developmentTarget` is set to at least `14.0`

Open a terminal, navigate to your app's iOS folder (usually `<projectName>/ios`), and run the following command:

```sh
pod install
```

## Updating From a Previous Version

Run the following command from a terminal in your app's root project directory

```sh
npm install @olo/pay-react-native@latest
```

### iOS-Specific Update Steps

Open a terminal, navigate to your app's iOS folder (usually `<projectName>/ios`), and run the following commands:

```sh
rm -rf Pods
pod update
```

> **Note:** If you run into errors after updating, delete both your `Pods` folder and `Podfile.lock` file and then run `pod install`.

### Known Issues

##### Versions 2.0.0 Through 3.0.2

- [PaymentCardDetailsView](#paymentcarddetailsview): The following properties must be provided to prevent a crash: `cardStyles.errorTextColor`, `cardStyles.textColor`, and `cardStyles.placeholderColor`
- [PaymentCardCvvView](#paymentcardcvvview): The following properties must be provided to prevent a crash: `cvvStyles.errorTextColor`, `cvvStyles.textColor`, and `cvvStyles.placeholderColor`

[[Back to Top]](#table-of-contents)

## Getting Started

A basic high-level overview of the steps needed to integrate the React Native SDK into your hybrid app is as follows:

#### Payment Methods (new cards & digital wallets)

This approach is used for cards that have not previously been saved on file with Olo. This includes new credit cards and digital wallets. With this approach both card input components and digital wallets return a [PaymentMethod](#paymentmethod) instance that is then used to submit a basket with Olo's Ordering API. Specific details can be found below.

1. Initialize Olo Pay (see [`initialize(...)`](#initialize)).
1. Create the [PaymentMethod](#paymentmethod).
   - Digital Wallets
     1. _[Android Only]_ Initialize Google Pay (see [`initializeGooglePay(...)`](#initializegooglepay)).
     1. Wait for [`DigitalWalletReadyEvent`](#digitalwalletreadyevent) to indicate digital wallet payments can be processed.
     1. Create a payment method (see [`getDigitalWalletPaymentMethod(...)`](#getdigitalwalletpaymentmethod)).
   - Credit Card Components
     1. Add a component to the App's UI (See [PaymentCardDetailsView](#paymentcarddetailsview) and [PaymentCardDetailsForm](#paymentcarddetailsform))
     1. Use the `createPaymentMethod()` function on the component to get a [PaymentMethod](#paymentmethod) instance
1. Submit the order to [Olo's Ordering API](https://developer.olo.com/docs/load/olopay#section/Submitting-a-Basket-via-the-Ordering-API) using the [PaymentMethod](#paymentmethod) details.

#### CVV Tokens (previously saved cards)

This approach is used for cards that have previously been saved on file with Olo, and you want to reverify the CVV of the saved card prior to submitting a basket and processing a payment. The [PaymentCardCvvView](#paymentcardcvvview) component will provide a [CvvUpdateToken](#cvvupdatetoken) instance that is then used to submit a basket with Olo's Ordering API. Specific details can be found below.

1. Initialize Olo Pay (see [`initialize(...)`](#initialize)).
1. Create the [CvvUpdateToken](#cvvupdatetoken).
   1. Add the [PaymentCardCvvView](#paymentcardcvvview) component to the App's UI.
   1. Use the `createCvvUpdateToken()` function on the component to get a [CvvUpdateToken](#cvvupdatetoken) instance
1. Submit the order to [Olo's Ordering API](https://developer.olo.com/docs/load/olopay#section/Submitting-a-Basket-via-the-Ordering-API) using the [CvvUpdateToken](#cvvupdatetoken) details.

[[Back to Top]](#table-of-contents)

## Handling Promise Rejections

When calling functions on the Olo Pay React Native SDK, there is a chance that the call will fail with the promise being rejected. When this happens
the returned error object will always contain `code` and `message` properties indicating why the method call was rejected.

For convenience, the SDK exports a [`PromiseRejectionCode`](#promiserejectioncode) enum and a [`PromiseRejection`](#promiserejection) type for
handling promise rejection errors.

### Example

```typescript
try {
  const paymentMethodData = await getDigitalWalletPaymentMethod({ amount: 2.34 }});
  //Handle payment method data
} catch (error) {
  let rejection = error as PromiseRejection;
  if (rejection) {
    switch(rejection.code) {
      case PromiseRejectionCode.missingParameter: {
          // Handle missing parameter scenario
          break;
      }
      case PromiseRejectionCode.sdkUninitialized: {
          // Handle sdk not initialized scenario
          break;
      }
    }
  } else {
    // Some other error not related to a promise rejection
  }
}
```

[[Back to Top]](#table-of-contents)

## Events

Events are used to send notifications regarding state changes that can't be completely handled by asynchronous method calls that return a promise. Details about each type of event can be found below.

#### DigitalWalletReadyEvent

You can subscribe to this event to know when digital wallets are ready to process payments. It can be referenced using the exported `DigitalWalletReadyEvent` constant or as a string with `"digitalWalletReadyEvent"`. The event returns a [`DigitalWalletStatus`](#digitalwalletstatus) object.

On iOS, if a device supports digital wallets, it will be ready (and this event will be emitted) as soon as the SDK is initialized.

On Android, this is emitted asynchronously after a call to `initializeGooglePay()`. Also note that this will be emitted whenever the status changes. Certain method calls,
such as `changeGooglePayVendor()`, will cause this event to be emitted that changes the ready status to `false` and then asynchronously follow-up with another
event that changes the status to `true` when the new vendor is ready to be used.

Example Code:

```typescript
import { OloPayEvents, DigitalWalletReadyEvent } from '@olo/pay-react-native';

let subscription = OloPayEvents.addListener(
  DigitalWalletReadyEvent,
  (event: DigitalWalletStatus) => {
    // Handle event...
  }
);

// Don't forget to unsubscribe when you no longer need to listen to the event
subscription.remove();
```

[[Back to Top]](#table-of-contents)

## Components

Components are used to display credit card input fields in an app. Credit card details are not accessible by the developer, helping reduce the effort needed to maintain PCI compliance. Details about each component can be found below.

---

### PaymentCardDetailsView

The `PaymentCardDetailsView` component displays all credit card input details in a single input field and is the most compressed way to display a credit card input view. It is composed of a root `<View>` component with two direct children, the credit card input view and a `<Text>` view for displaying error messages. Each piece of the component can be individually styled via `componentStyles`, `cardStyles`, and `errorStyles` _(See [PaymentCardDetailsViewProps](#paymentcarddetailsviewprops))_

#### PaymentCardDetailsViewProps

`PaymentCardDetailsViewProps` provides customization for the card component.

| Property                          | Description                                                                                                                             |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `componentStyles`                 | Options for styling the root `<View>` component                                                                                         |
| `errorStyles`                     | Options for styling the error `<Text>` component. _Default style is `{ minHeight: 20 }`_                                                |
| `cardStyles`                      | Options for styling credit card input portion of the component. _(See [PaymentCardDetailsViewStyles](#paymentcarddetailsviewstyles))_   |
| `viewProps`                       | React Native view properties for the root `<View>` component                                                                            |
| `customErrorMessages`             | Options for defining custom error messages in place of defaults _(See [CustomErrorMessages](#customerrormessages))_                     |
| `postalCodeEnabled`               | Whether or not the postal code should be displayed                                                                                      |
| `isEnabled`                       | Whether or not the component is enabled and can receive touch and input events                                                          |
| `displayErrorMessages`            | Whether or not the component should display error messages. Set to `false` if you have a custom mechanism for displaying error messages |
| `placeholders`                    | Options for specifying placeholder text. _(See [PaymentCardDetailsPlaceholders](#paymentcarddetailsplaceholders))_                      |
| `onCardChange(card: CardDetails)` | Card change event handler. Called when input events occur. _(See [CardDetails](#carddetails))_                                          |
| `onFocus()`                       | Focus event handler. Called when the component receives input focus                                                                     |
| `onBlur()`                        | Blur event handler. Called when the component loses input focus                                                                         |
| `onFocusField(field: CardField)`  | Focus field event handler. Called each time focus moves to a new card input field within the component. _(See [CardField](#cardfield))_ |

<code>{
componentStyles?: StyleProp\<ViewStyle>;
errorStyles?: StyleProp\<TextStyle>;
cardStyles?: [PaymentCardDetailsViewStyles](#paymentcarddetailsviewstyles);
viewProps?: ViewProps;
postalCodeEnabled?: boolean;
isEnabled?: boolean;
displayErrorMessages?: boolean;
placeholders?: [PaymentCardDetailsPlaceholders](#paymentcarddetailsplaceholders);
onCardChange?(card: [CardDetails](#carddetails)): void;
onFocus?(): void;
onBlur?(): void;
onFocusField?(field: [CardField](#cardfield)): void;
customErrorMessages?: [CustomErrorMessages](#customerrormessages);
}</code>

> **_Important_:** Card field text and error message text have separate styling mechanisms. If the default error colors are changed, it is important to change both of them. An example is provided below:
>
> ```typescript
> <PaymentCardDetailsView
>   cardStyles={{ errorTextColor: "#00ff00" }}
>   errorStyles={{ color: "#00ff00" }}
> />
> ```

#### PaymentCardDetailsViewMethods

`PaymentCardDetailsViewMethods` defines the native methods that can be called on the `PaymentCardDetailsView` component. These methods can be accessed by passing a `ref` prop of this type into the component, and then calling them on the `ref`. See the `PaymentCardDetailsView` [example](#paymentcarddetailsview-example) code below for details.

**focus()**

```typescript
focus() => Promise<void>
```

Puts focus on the `PaymentCardDetailsView` component and displays the keyboard. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**blur()**

```typescript
blur() => Promise<void>
```

Clears focus on the `PaymentCardDetailsView` component and hides the keyboard. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**clear()**

```typescript
clear() => Promise<void>
```

Clears all card details entered in the `PaymentCardDetailsView` component. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**createPaymentMethod()**

```typescript
createPaymentMethod() => Promise<PaymentMethod>
```

Attempts to create a payment method based on the entered card details. If successful, returns a [PaymentMethod](#paymentmethod) instance.

If the promise is rejected, possible values of the `code` property on the returned error will be one of:

- [PromiseRejectionCode.viewNotFound](#promiserejectioncode)
- [PromiseRejectionCode.invalidNumber](#promiserejectioncode)
- [PromiseRejectionCode.invalidExpiration](#promiserejectioncode)
- [PromiseRejectionCode.invalidCvv](#promiserejectioncode)
- [PromiseRejectionCode.invalidPostalCode](#promiserejectioncode)
- [PromiseRejectionCode.expiredCard](#promiserejectioncode)
- [PromiseRejectionCode.cardDeclined](#promiserejectioncode)
- [PromiseRejectionCode.unknownCardError](#promiserejectioncode)
- [PromiseRejectionCode.processingError](#promiserejectioncode)
- [PromiseRejectionCode.connectionError](#promiserejectioncode)
- [PromiseRejectionCode.invalidRequest](#promiserejectioncode)
- [PromiseRejectionCode.apiError](#promiserejectioncode)
- [PromiseRejectionCode.cancellationError](#promiserejectioncode)
- [PromiseRejectionCode.authenticationError](#promiserejectioncode)
- [PromiseRejectionCode.generalError](#promiserejectioncode)

#### PaymentCardDetailsView Example

```typescript
import {
  PaymentCardDetailsView,
  PaymentCardDetailsViewMethods,
} from '@olo/pay-react-native';
import { View, Button } from 'react-native';
import { useRef } from 'react';

export default function MyComponent() {
  const cardRef = useRef<PaymentCardDetailsViewMethods>(null);

  const createPaymentMethod = async () => {
    try {
      if (!cardRef.current) {
        return;
      }

      let paymentMethod = await cardRef.current.createPaymentMethod();
      // Use the payment method to submit a basket using Olo's ordering API
    } catch (error) {
      // Handle the promise rejection
    }
  };

  // Styling omitted for sake of example simplicity
  return (
    <View>
      <PaymentCardDetailsView displayErrorMessages={true} ref={cardRef} />
      <Button title="Submit Payment" onPress={createPaymentMethod} />
    </View>
  );
}
```

### PaymentCardDetailsForm

The `PaymentCardDetailsForm` component displays all credit card input details in a multi-line form and is the most visible way to display a credit card input view. It is composed of a root `<View>` component with a single nested child, the credit card input form. Each piece of the component can be individually styled via `componentStyles` and `cardStyles` _(See [PaymentCardDetailsFormProps](#paymentcarddetailsformprops))_

#### PaymentCardDetailsFormProps

`PaymentCardDetailsFormProps` provides additional properties defined in the following table

| Property           | Description                                                                                                                           |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `componentStyles`  | Options for styling the root `<View>`                                                                                                 |
| `cardStyles`       | Options for styling credit card input portion of the component. _(See [PaymentCardDetailsFormStyles](#paymentcarddetailsformstyles))_ |
| `isEnabled`        | Whether or not the component is enabled and can receive touch and input events                                                        |
| `onFormComplete()` | Card form complete event handler. Called when form complete events occur. _(See [CardValidationStatus](#cardvalidationstatus))_       |
| `viewProps`        | React Native view properties for the root `<View>` component                                                                          |
| `placeholders`     | Options for specifying placeholder text. _(See [PaymentCardDetailsPlaceholders](#paymentcarddetailsplaceholders))_                    |

<code>{
cardStyles?: [PaymentCardDetailsFormStyles](#paymentcarddetailsformstyles);
componentStyles?: StyleProp\<ViewStyle>;
isEnabled?: boolean;
onFormComplete?(cardValidationStatus: [CardValidationStatus](#cardvalidationstatus)): void;
viewProps?: ViewProps;
placeholders?: [PaymentCardDetailsPlaceholders](#paymentcarddetailsplaceholders);
}</code>

#### PaymentCardDetailsFormMethods

`PaymentCardDetailsFormMethods` defines the native methods that can be called on the `PaymentCardDetailsForm` component. These methods can be accessed by passing a `ref` prop of this type into the component, and then calling them on the `ref`. See the `PaymentCardDetailsForm` [example](#paymentcarddetailsform-example) code below for details.

**focus()** _(iOS Only)_

```typescript
focus() => Promise<void>
```

Puts focus on the `PaymentCardDetailsForm` component and displays the keyboard. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**blur()**

```typescript
blur() => Promise<void>
```

Clears focus on the `PaymentCardDetailsForm` component and hides the keyboard. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**clear()** _(Android Only)_

```typescript
clear() => Promise<void>
```

Clears all card details entered in the `PaymentCardDetailsForm` component. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**createPaymentMethod()**

```typescript
createPaymentMethod() => Promise<PaymentMethod>
```

Attempts to create a payment method based on the entered card details. If successful, returns a [PaymentMethod](#paymentmethod) instance.

If the promise is rejected, possible values of the `code` property on the returned error will be one of:

- [PromiseRejectionCode.viewNotFound](#promiserejectioncode)
- [PromiseRejectionCode.isValid](#promiserejectioncode)
- [PromiseRejectionCode.invalidNumber](#promiserejectioncode)
- [PromiseRejectionCode.invalidExpMonth](#promiserejectioncode)
- [PromiseRejectionCode.invalidExpYear](#promiserejectioncode)
- [PromiseRejectionCode.invalidCvv](#promiserejectioncode)
- [PromiseRejectionCode.invalidPostalCode](#promiserejectioncode)
- [PromiseRejectionCode.expiredCard](#promiserejectioncode)
- [PromiseRejectionCode.cardDeclined](#promiserejectioncode)
- [PromiseRejectionCode.unknownCardError](#promiserejectioncode)
- [PromiseRejectionCode.processingError](#promiserejectioncode)
- [PromiseRejectionCode.connectionError](#promiserejectioncode)
- [PromiseRejectionCode.invalidRequestError](#promiserejectioncode)
- [PromiseRejectionCode.apiError](#promiserejectioncode)
- [PromiseRejectionCode.cancellationError](#promiserejectioncode)
- [PromiseRejectionCode.authenticationError](#promiserejectioncode)
- [PromiseRejectionCode.invalidCardDetails](#promiserejectioncode)
- [PromiseRejectionCode.generalError](#promiserejectioncode)

#### PaymentCardDetailsForm Example

```typescript
import { PaymentCardDetailsForm, PaymentCardDetailsFormMethods } from "@olo/pay-react-native";
import { View, Button } from "react-native";
import { useRef } from "react";

export default function MyComponent() {
  const cardRef = useRef<PaymentCardDetailsFormMethods>(null);

  const createPaymentMethod = async() => {
    try {
      if (!cardRef.current) {
        return;
      }

      let paymentMethod = await cardRef.current.createPaymentMethod();
      // Use the payment method to submit a basket using Olo's ordering API
    } catch (error) {
      // Handle the promise rejection
    }
  };

  // Styling omitted for sake of example simplicity
  return (
    <View>
      <PaymentCardDetailsForm
        ref={cardRef} />
      <Button
        title="Submit Payment"
        onPress={createPaymentMethod} />
    </View>
  );
};
```

### PaymentCardCvvView

The `PaymentCardCvvView` component displays a single input for a credit card's Card Verification Value (CVV). This is useful to reverify a credit card that has previously been saved with Olo. It is composed of a root `<View>` component with two nested children, the CVV code input and a `<Text>` component for displaying error messages. Each piece of the component can be individually styled via `componentStyles` and `cvvStyles` _(See [PaymentCardCvvViewProps](#paymentcardcvvviewprops))_

#### PaymentCardCvvViewProps

| Property                              | Description                                                                                                                             |
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `componentStyles`                     | Options for styling the root `<View>` component                                                                                         |
| `customErrorMessages`                 | Option for defining custom error messages in place of defaults _(See [CustomFieldError](#customfielderror))_                            |
| `cvvStyles`                           | Options for styling security code input portion of the component. _(See [PaymentCardCvvViewStyles](#paymentcardcvvviewstyles))_         |
| `displayErrorMessages`                | Whether or not the component should display error messages. Set to `false` if you have a custom mechanism for displaying error messages |
| `errorStyles`                         | Options for styling the error `<Text>` component. _Default style is `{ minHeight: 20 }`_                                                |
| `isEnabled`                           | Whether or not the component is enabled and can receive touch and input events                                                          |
| `onBlur(cvvDetails: CvvDetails)`      | Blur event handler. Called when the component loses input focus _(See [CvvDetails](#cvvdetails))_                                       |
| `onCvvChange(cvvDetails: CvvDetails)` | Card change event handler. Called when input events occur. _(See [CvvDetails](#cvvdetails))_                                            |
| `onFocus(cvvDetails: CvvDetails)`     | Focus event handler. Called when the component receives input focus _(See [CvvDetails](#cvvdetails))_                                   |
| `placeholder`                         | Option for specifying placeholder text. _(See [PaymentCardCvvPlaceholder](#paymentcardcvvplaceholder))_                                 |
| `viewProps`                           | React Native view properties for the root `<View>` component                                                                            |

<code>{
componentStyles?: StyleProp/<ViewStyle>;  
 customErrorMessages?: [CustomFieldError](#customfielderror);  
 cvvStyles?: StyleProp/<ViewStyle>;  
 displayErrorMessages?: boolean;  
 errorStyles?: StyleProp/<ViewStyle>;  
 isEnabled?: boolean:
onBlur(details: [CvvDetails](#cvvdetails))?: void;
onCvvChange(details: [CvvDetails](#cvvdetails))?: void;
onFocus(details: [CvvDetails](#cvvdetails))?: void;
placeholder?: string;
viewProps?: ViewProps;  
}

> **_Important_:** CVV field text and error message text have separate styling mechanisms. If the default error colors are changed, it is important to change both of them. An example is provided below:
>
> ```typescript
> <PaymentCardCvvView
>   cvvStyles={{ errorTextColor: "#00ff00" }}
>   errorStyles={{ color: "#00ff00" }}
> />
> ```

#### PaymentCardCvvViewMethods

`PaymentCardCvvViewMethods` defines the native methods that can be called on the `PaymentCardCvvView` component. These methods can be accessed by adding a `ref` prop of this type
into the component, and then calling them on the `ref`. See the `PaymentCardCvvView` [example](#paymentcardcvvview-example) code below for details.

**focus()**

```typescript
focus() => Promise<void>
```

Puts focus on the `PaymentCardCvvView` component and displays the keyboard. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**blur()**

```typescript
blur() => Promise<void>
```

Clears focus on the `PaymentCardCvvView` component and hides the keyboard. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**clear()**

```typescript
clear() => Promise<void>
```

Clears all security code details entered in the `PaymentCardCvvView` component. If the promise is rejected, the `code` property on the returned error will be [PromiseRejectionCode.viewNotFound](#promiserejectioncode)

**createCvvUpdateToken()**

```typescript
createCvvUpdateToken() => Promise<CvvUpdateToken>
```

Attempts to create a CVV update token based on the entered security code details. If successful, returns a [CvvUpdateToken](#cvvupdatetoken) instance.

If the promise is rejected, possible values of the `code` property on the returned error will be one of:

- [PromiseRejectionCode.viewNotFound](#promiserejectioncode)
- [PromiseRejectionCode.invalidCvv](#promiserejectioncode)
- [PromiseRejectionCode.processingError](#promiserejectioncode)
- [PromiseRejectionCode.connectionError](#promiserejectioncode)
- [PromiseRejectionCode.invalidRequest](#promiserejectioncode)
- [PromiseRejectionCode.apiError](#promiserejectioncode)
- [PromiseRejectionCode.cancellationError](#promiserejectioncode)
- [PromiseRejectionCode.authenticationError](#promiserejectioncode)
- [PromiseRejectionCode.generalError](#promiserejectioncode)

#### PaymentCardCvvView Example

```typescript
import {
  PaymentCardCvvView,
  PaymentCardCvvViewMethods,
} from '@olo/pay-react-native';
import { View, Button } from 'react-native';
import { useRef } from 'react';

export default function MyComponent() {
  const cvvRef = useRef<PaymentCardCvvViewMethods>(null);

  const createCvvUpdateToken = async () => {
    try {
      if (!cvvRef.current) {
        return;
      }

      let cvvUpdateToken = await cvvRef.current.createCvvUpdateToken();
      // Use the CVV update token for revalidating a stored credit card
    } catch (error) {
      // Handle the promise rejection
    }
  };

  // Styling omitted for sake of example simplicity
  return (
    <View>
      <PaymentCardCvvView displayErrorMessages={true} ref={cvvRef} />
      <Button title="Submit CVV" onPress={createCvvUpdateToken} />
    </View>
  );
}
```

[[Back to Top]](#table-of-contents)

## OloPaySDK Module

Native SDK methods can be called on the imported `OloPaySDK` object. This module is responsible for initializing the Olo Pay SDK and processing digital wallet payments.

```typescript
import { OloPaySDK } from '@olo/pay-react-native';
```

<docgen-index>

* [`initialize(...)`](#initialize)
* [`initializeGooglePay(...)`](#initializegooglepay)
* [`changeGooglePayVendor(...)`](#changegooglepayvendor)
* [`getDigitalWalletPaymentMethod(...)`](#getdigitalwalletpaymentmethod)
* [`isInitialized()`](#isinitialized)
* [`isDigitalWalletInitialized()`](#isdigitalwalletinitialized)
* [`isDigitalWalletReady()`](#isdigitalwalletready)
* [Type Aliases](#type-aliases)
* [Enums](#enums)

</docgen-index>

## Methods

<docgen-api>
<!--Update the source file JSDoc comments and rerun docgen to update the docs below-->

### initialize(...)

```typescript
initialize(options: AndroidInitializationOptions | iOSInitializationOptions) => Promise<void>
```

Initialize the Olo Pay SDK. The SDK must be initialized prior to calling other methods.

This promise will only be rejected on iOS. If it is rejected the `code` property on the returned
error will be [`PromiseRejectionCode.missingParameter`](#promiserejectioncode)

_**NOTE:**_ On iOS, this method will also initialize Apple Pay and a [DigitalWalletReadyEvent](#digitalwalletreadyevent)
will be emitted when it is ready to process payments. On Android, a separate initialization
call to `initializeGooglePay()` is required.

| Param         | Type                                                                                                                                                  | Description            |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- |
| **`options`** | <code><a href="#olopayinitializationconfig">OloPayInitializationConfig</a> \| <a href="#iosinitializationoptions">iOSInitializationOptions</a></code> | Initialization options |

--------------------


### initializeGooglePay(...)

```typescript
initializeGooglePay(options: GooglePayInitializationOptions) => Promise<void>
```

_**ANDROID ONLY:** If this method is called on iOS the promise will be rejected_

Initialize digital wallets. This must be called after initializing the SDK. When digital wallets
are ready, a [DigitalWalletReadyEvent](#digitalwalletreadyevent) will be emitted.

If the promise is rejected, possible values of the `code` property on the returned error will be one of:
- [PromiseRejectionCode.unimplemented (iOS)](#promiserejectioncode)
- [PromiseRejectionCode.missingParameter](#promiserejectioncode)
- [PromiseRejectionCode.sdkUninitialized](#promiserejectioncode)

| Param         | Type                                                                                      | Description                                                                                        |
| ------------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| **`options`** | <code><a href="#googlepayinitializationoptions">GooglePayInitializationOptions</a></code> | Options for initializing digital wallets. _`countryCode` and `merchantName` are required options._ |

--------------------


### changeGooglePayVendor(...)

```typescript
changeGooglePayVendor(options: ChangeGooglePayVendorOptions) => Promise<void>
```

_**ANDROID ONLY:** If this method is called on iOS the promise will be rejected_

Call this to change the country and merchant name used for processing Google Pay payments. This will immediately
trigger a [DigitalWalletReadyEvent](#digitalwalletreadyevent) indicating digital wallets are not ready. When Google Pay
has been reinitialized and is ready to be used with the new parameters, another event will be
emitted.

_**NOTE:** If other options need to be changed besides country code and merchant name you can call
           `initializeGooglePay()` instead, but it is more expensive than calling this method._

If the promise is rejected, possible values of the `code` property on the returned error will be one of:
- [PromiseRejectionCode.unimplemented (iOS)](#promiserejectioncode)
- [PromiseRejectionCode.missingParameter](#promiserejectioncode)
- [PromiseRejectionCode.sdkUninitialized](#promiserejectioncode)
- [PromiseRejectionCode.googlePayUninitialized](#promiserejectioncode)

| Param         | Type                                                                                  | Description                                                                                                  |
| ------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| **`options`** | <code><a href="#changegooglepayvendoroptions">ChangeGooglePayVendorOptions</a></code> | Options for changing the country and merchant name. _`countryCode` and `merchantName` are required options._ |

--------------------


### getDigitalWalletPaymentMethod(...)

```typescript
getDigitalWalletPaymentMethod(options: DigitalWalletPaymentRequestOptions) => Promise<DigitalWalletPaymentMethodResult | undefined>
```

Launch the digital wallet flow and generate a payment method to be used with Olo's Ordering API.

If the promise is rejected, the `code` property of the returned error object will be one of:
- [PromiseRejectionCode.sdkUninitialized](#promiserejectioncode)
- [PromiseRejectionCode.invalidParameter](#promiserejectioncode)
- [PromiseRejectionCode.missingParameter](#promiserejectioncode)
- [PromiseRejectionCode.applePayUnsupported (iOS)](#promiserejectioncode)
- [PromiseRejectionCode.googlePayNotReady (Android)](#promiserejectioncode)
- [PromiseRejectionCode.googlePayUninitialized (Android)](#promiserejectioncode)
- [PromiseRejectionCode.generalError](#promiserejectioncode)

| Param         | Type                                                                                              | Description                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| **`options`** | <code><a href="#digitalwalletpaymentrequestoptions">DigitalWalletPaymentRequestOptions</a></code> | Options for processing a digital wallet payment. _`amount` is a required option_ |

**Returns:** <code>Promise&lt;<a href="#digitalwalletpaymentmethodresult">DigitalWalletPaymentMethodResult</a>&gt;</code>

--------------------


### isInitialized()

```typescript
isInitialized() => Promise<InitializationStatus>
```

Check if the Olo Pay SDK has been initialized

**Returns:** <code>Promise&lt;<a href="#initializationstatus">InitializationStatus</a>&gt;</code>

--------------------


### isDigitalWalletInitialized()

```typescript
isDigitalWalletInitialized() => Promise<InitializationStatus>
```

Check if digital wallets have been initialized. On iOS, digital wallets are initialized when the SDK is initialized, so this method
will behave the same as `isInitialized()`. On Android, a separate call to `initializeGooglePay()` is required to initialize digital wallets.

**Returns:** <code>Promise&lt;<a href="#initializationstatus">InitializationStatus</a>&gt;</code>

--------------------


### isDigitalWalletReady()

```typescript
isDigitalWalletReady() => Promise<DigitalWalletStatus>
```

Check if digital wallets are ready to be used. Events are emitted whenever the digital wallet status
changes, so listenting to that event can be used instead of calling this method, if desired.

**Returns:** <code>Promise&lt;<a href="#digitalwalletstatus">DigitalWalletStatus</a>&gt;</code>

--------------------


### Type Aliases


#### AndroidInitializationOptions

Options for initializing the Android Olo Pay SDK. This is a type alias for code readability.

<code><a href="#olopayinitializationconfig">OloPayInitializationConfig</a></code>


#### OloPayInitializationConfig

Options for initializing the Olo Pay SDK
| Property | Description | Default |
| -------- | ----------- | ------- |
| `productionEnvironment` | `true` to use the production environment, `false` for the test environment. | `true` |
| `freshInstall` | **_DEPRECATED:_** This property is deprecated and is ignored if used |

<code>{ productionEnvironment?: boolean; freshInstall?: boolean; }</code>


#### iOSInitializationOptions

Options for initializing the iOS Olo Pay SDK. This is a type alias for code readability

<code><a href="#olopayinitializationconfig">OloPayInitializationConfig</a> & <a href="#applepayinitializationconfig">ApplePayInitializationConfig</a></code>


#### ApplePayInitializationConfig

Options for initializing Apple Pay
| Property | Description |
| -------- | ----------- |
| `applePayMerchantId` | The merchant id registered with Apple for Apple Pay |
| `applePayCompanyLabel` | The company name that will be displayed on the Apple Pay payment sheet |

<code>{ applePayMerchantId: string; applePayCompanyLabel: string; }</code>


#### GooglePayInitializationOptions

Options for intializing Google Pay
| Property | Description | Default |
| -------- | ----------- | ------- |
| `googlePayProductionEnvironment` | `true` to use the production environment, `false` for the test environment | `true` |
| `countryCode` | A two character country code for the vendor that will be processing the payment | - |
| `merchantName` | The merchant/vendor display name | - |
| `fullAddressFormat` | Determines what address fields are required to complete a Google Pay transaction. `true` includes name, street address, locality, region, country code, and postal code. `false` only includes name, country code, and postal code | `false` |
| `existingPaymentMethodRequired` | Whether an existing saved payment method is required for Google Pay to be considered ready | `true` |
| `emailRequired` | Whether Google Pay collects an email when processing payments | `false` |
| `phoenNumberRequired` | Whether Google Pay collects a phone number when processing payments | `false` |

<code>{ googlePayProductionEnvironment?: boolean; countryCode: string; merchantName: string; fullAddressFormat?: boolean; existingPaymentMethodRequired?: boolean; emailRequired?: boolean; phoneNumberRequired?: boolean; }</code>


#### ChangeGooglePayVendorOptions

Options for changing the country code or merchant name for Google Pay transactions
| Property | Description |
| -------- | ----------- |
| `countryCode` | A two character country code for the vendor that will be processing the payment |
| `merchantName` | The merchant/vendor display name |

<code>{ countryCode: string; merchantName: string; }</code>


#### DigitalWalletPaymentMethodResult

Type alias representing a digital wallet payment method result.  The
object will either contain payment method data or error data.

<code>{ paymentMethod: <a href="#paymentmethod">PaymentMethod</a>; error?: undefined } | { paymentMethod?: undefined; error: <a href="#digitalwalleterror">DigitalWalletError</a> }</code>


#### PaymentMethod

Payment method used for submitting payments to Olo's Ordering API
| Property | Description |
| -------- | ----------- |
| `id` | The payment method id. This should be set to the token field when submitting a basket |
| `last4` | The last four digits of the card |
| `cardType` | The issuer of the card |
| `expMonth` | Two-digit number representing the card's expiration month |
| `expYear` | Four-digit number representing the card's expiration year |
| `postalCode` | Zip or postal code |
| `countryCode` | Two character country code |
| `isDigitalWallet` | `true` if this payment method was created by digital wallets (e.g. Apple Pay or Google Pay), `false` otherwise |

<code>{ id?: string; last4?: string; cardType?: <a href="#cardtype">CardType</a>; expMonth?: number; expYear?: number; postalCode?: string; countryCode?: string; isDigitalWallet: boolean; }</code>


#### DigitalWalletError

Type representing a digital wallet error
| Property | Description |
| -------- | ----------- |
| `errorMessage` | Error message indicating what went wrong |
| `digitalWalletType` | Enum value indicating Apple Pay or Google Pay. If this is a Google Pay error, there are additional properties indicating the type of error that occurred. See <a href="#googlepayerror">`GooglePayError`</a> |

<code>{ errorMessage: string; digitalWalletType: <a href="#digitalwallettype">DigitalWalletType</a>; } & (<a href="#googlepayerror">GooglePayError</a> | null)</code>


#### GooglePayError

Type representing specific error types that can occur while processing a Google Pay transaction
| Property | Description |
| -------- | ----------- |
| `googlePayErrorType` | The type of error that occurred. See <a href="#googlepayerrortype">`GooglePayErrorType`</a> |

<code>{ googlePayErrorType: <a href="#googlepayerrortype">GooglePayErrorType</a>; }</code>


#### DigitalWalletPaymentRequestOptions

Type alias representing options for a digital wallet payment method request

<code><a href="#googlepaypaymentrequestoptions">GooglePayPaymentRequestOptions</a> | <a href="#applepaypaymentrequestoptions">ApplePayPaymentRequestOptions</a></code>


#### GooglePayPaymentRequestOptions

Options for requesting a payment method via Google Pay
| Property | Description | Default |
| -------- | ----------- | ------- |
| `amount` | The amount to be charged | - |
| `currencyCode` | A three character currency code for the transaction | 'USD' |
| `currencyMulitplier` | Multiplier to convert the amount to the currency's smallest currency unit (e.g. $2.34 * 100 = 234 cents) | 100 |

**_Important_:** The amount charged will be equivalent to `amount * currencyCode` so ensure these are set properly

<code>{ amount: number; currencyCode?: string; currencyMultiplier?: number; }</code>


#### ApplePayPaymentRequestOptions

Options for requesting a payment method via Apple Pay
| Property | Description | Default |
| -------- | ----------- | ------- |
| `amount` | The amount to be charged | - |
| `currencyCode` | A three character currency code for the transaction | 'USD' |
| `countryCode` | A two character country code | 'US' |

<code>{ amount: number; countryCode?: string; currencyCode?: string; }</code>


#### InitializationStatus

Represents the status for SDK initialization
| Property | Description |
| -------- | ----------- |
| `isInitialized` | `true` if the SDK is initialized, `false` otherwise |

<code>{ isInitialized: boolean; }</code>


#### DigitalWalletStatus

Represents the status of digital wallets.
| Property | Description |
| -------- | ----------- |
| `isReady` | `true` if digital wallets are ready to be used, `false` otherwise |

<code>{ isReady: boolean; }</code>


### Enums


#### CardType

| Members           | Value                      | Description                                                                                                       |
| ----------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| **`visa`**        | <code>'Visa'</code>        | Visa credit card type. Pass the string value of this into the Olo Ordering API when submitting orders             |
| **`amex`**        | <code>'Amex'</code>        | American Express credit card type. Pass the string value of this into the Olo Ordering API when submitting orders |
| **`mastercard`**  | <code>'Mastercard'</code>  | Mastercard credit card type. Pass the string value of this into the Olo Ordering API when submitting orders       |
| **`discover`**    | <code>'Discover'</code>    | Discover credit card type. Pass the string value of this into the Olo Ordering API when submitting orders         |
| **`unsupported`** | <code>'Unsupported'</code> | Unsupported credit card type. Passing this to the Olo Ordering API will result in an error                        |
| **`unknown`**     | <code>'Unknown'</code>     | Unknown credit card type. Passing this to the Olo Ordering API will result in an error                            |


#### DigitalWalletType

| Members         | Value                    |
| --------------- | ------------------------ |
| **`applePay`**  | <code>'applePay'</code>  |
| **`googlePay`** | <code>'googlePay'</code> |


#### GooglePayErrorType

| Members              | Value                         | Description                                        |
| -------------------- | ----------------------------- | -------------------------------------------------- |
| **`networkError`**   | <code>'NetworkError'</code>   | Google Pay didn't succeed due to a network error   |
| **`developerError`** | <code>'DeveloperError'</code> | Google Pay didn't succeed due to developer error   |
| **`internalError`**  | <code>'InternalError'</code>  | Google Pay didn't succeed due to an internal error |

</docgen-api>

<!--
Everything below here is manually added. PromiseRejectionCode and PromiseRejection are exported by our SDK,
but due to a limitation with the capacitor docgen tool, they don't get added to the documentation because
they aren't referenced by anything in the SDK definitions file.
==========================================================================================================
-->

<!-- NOTE: The following enums are part of the auto-generated Enums section above -->

#### PromiseRejectionCode

Describes all the reasons why a method could be rejected. Individual methods document which promise rejection codes are possible, and it's up to the developer to handle them.

| Members                  | Value                    | Description                                                      |
| ------------------------ | ------------------------ | ---------------------------------------------------------------- |
| `invalidParameter`       | 'InvalidParameter'       | Promise rejected due to an invalid parameter                     |
| `missingParameter`       | 'MissingParameter'       | A required parameter is missing                                  |
| `sdkUninitialized`       | 'SdkUninitialized'       | The SDK isn't initialized yet                                    |
| `applePayUnsupported`    | 'ApplePayUnsupported'    | The device doesn't support Apple Pay _(iOS Only)_                |
| `googlePayUninitialized` | 'GooglePayUninitialized' | Google Pay hasn't been initialized yet _(Android Only)_          |
| `googlePayNotReady`      | 'GooglePayNotReady'      | Google Pay isn't ready yet _(Android Only)_                      |
| `unimplemented`          | 'UNIMPLEMENTED'          | The method isn't implemented for the current platform            |
| `viewNotFound`           | 'ViewNotFound'           | The native view associated with the component could not be found |
| `apiError`               | 'ApiError'               | A general-purpose API error occurred                             |
| `invalidRequest`         | 'InvalidRequest'         | A request to servers has invalid parameters                      |
| `connectionError`        | 'ConnectionError'        | An issue occurred connecting to the server                       |
| `cancellationError`      | 'CancellationError'      | The operation was cancelled by the server                        |
| `authenticationError`    | 'AuthenticationError'    | An authentication issue with the server                          |
| `invalidCardDetails`     | 'InvalidCardDetails'     | The card details are invalid                                     |
| `invalidNumber`          | 'InvalidNumber'          | The card's number is invalid                                     |
| `invalidExpiration`      | 'InvalidExpiration'      | The card's expiration date is invalid                            |
| `invalidCvv`             | 'InvalidCVV'             | The card security code is invalid or incomplete                  |
| `invalidPostalCode`      | 'InvalidPostalCode'      | The card's zip code is invalid or incorrect                      |
| `expiredCard`            | 'ExpiredCard'            | The card is expired                                              |
| `cardDeclined`           | 'CardDeclined'           | The card was declined                                            |
| `unknownCardError`       | 'UnknownCardError'       | An unknown or unaccounted-for card error occurred                |
| `processingError`        | 'ProcessingError'        | An error occurred while processing the card info                 |
| `generalError`           | 'generalError'           | A general-purpose error occurred                                 |

#### CardField

Represents the different input fields of the [`PaymentCardDetailsView`](#paymentcarddetailsview) component

| Property     | Value        | Description                     |
| ------------ | ------------ | ------------------------------- |
| `number`     | 'number'     | Credit card number field        |
| `expiration` | 'expiration' | Credit card expiration field    |
| `cvv`        | 'cvv'        | Credit card security code field |
| `postalCode` | 'postalCode' | Credit card postal code field   |

#### FontWeight

Options for determining the weight of the font.

| Property     | Description                                                                             |
| ------------ | --------------------------------------------------------------------------------------- |
| `ultraLight` | Ultra light font weight. Corresponds to a value of `100`                                |
| `thin`       | Thin font weight. Corresponds to a value of `200`                                       |
| `light`      | Light font weight. Corresponds to a value of `300`                                      |
| `regular`    | Regular font weight. This is the default in most cases. Corresponds to a value of `400` |
| `medium`     | Medium font weight. Corresponds to a value of `500`                                     |
| `semiBold`   | Semi Bold font weight. Corresponds to a value of `600`                                  |
| `bold`       | Bold font weight. Corresponds to a value of `700`                                       |
| `extraBold`  | Extra bold font weight. Corresponds to a value of `800`                                 |
| `black`      | Heaviest font weight. Corresponds to a value of `900`                                   |

### Additional Type Aliases

#### PromiseRejection

When a promise is rejected, the error object returned is guaranteed to have
these properties to understand what went wrong. There may be additional properties
on the object, but `code` and `message` will always be available.

| Property  | Description                                                                                                                                                        |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `code`    | The code to indicate why the promise was rejected                                                                                                                  |
| `message` | A message providing more context about why the promise was rejected. e.g. If the `code` is `missingParameter` the message will indicate which parameter is missing |

#### PaymentCardDetailsPlaceholders

Options for specifying placeholder values for each credit card input field

| Property     | Description                                                 |
| ------------ | ----------------------------------------------------------- |
| `number`     | The placeholder value for the credit card number field      |
| `expiration` | The placeholder value for the credit card expiration field  |
| `cvv`        | The placeholder value for the credit card cvv field         |
| `postalCode` | The placeholder value for the credit card postal code field |

<code>{ number?: string; expiration?: string; cvv?: string; postalCode?: string }</code>

#### PaymentCardDetailsViewStyles

Options for styling the [PaymentCardDetailsView](#paymentcarddetailsview) component. All colors should be specified in hex format.

| Property           | Description                                                                                                                                                                                                                   |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `styles`           | React Native styles for this view. Default is `{ minHeight: 50 }`                                                                                                                                                             |
| `borderWidth`      | The width of the card view's border                                                                                                                                                                                           |
| `borderColor`      | The color of the card view's border                                                                                                                                                                                           |
| `cornerRadius`     | The corner radius of the card view's border                                                                                                                                                                                   |
| `backgroundColor`  | The background color for the card view _(Android Only: Requires API 27+)_                                                                                                                                                     |
| `textColor`        | The text color for user-entered text _(Android Only: Requires API 27+)_                                                                                                                                                       |
| `fontSize`         | The font size for all text input                                                                                                                                                                                              |
| `fontFamily`       | The font family used for text                                                                                                                                                                                                 |
| `placeholderColor` | The color for placeholder text _(Android Only: Requires API 27+)_                                                                                                                                                             |
| `cursorColor`      | The color for the cursor _(Android Only: Requires API 29+)_                                                                                                                                                                   |
| `errorTextColor`   | The color of the text inside the input fields if they are in an error state. Consider changing [`errorStyles.color`](#paymentcarddetailsviewprops) when changing this property _(Android Only: Requires API 27+)_             |
| `fontWeight`       | The stroke weight of the font in each of the fields. API 28+ can support all font weights. Lower API versions interpret a [FontWeight](#fontweight) of `700` or above as `bold` and below `700` as `regular` _(Android Only)_ |
| `italic`           | Determins if the font inside the fields should be italic style _(Android Only)_                                                                                                                                               |
| `textPaddingLeft`  | Padding (in pixels) for the left of the card input area. _(Android Only)_                                                                                                                                                     |
| `textPaddingRight` | Padding (in pixels) for the right of the card input area. _(Android Only)_                                                                                                                                                    |

<code>{
styles?: StyleProp\<ViewStyle>;
borderWidth?: number;
borderColor?: string;
cornerRadius?: number;
backgroundColor?: string;
textColor?: string;
fontSize?: number;
fontFamily?: string;
placeholderColor?: string;
cursorColor?: string;
errorTextColor?: string;
fontWeight?: [FontWeight](#fontweight);
italic?: boolean;
textPaddingLeft?: number;
textPaddingRight?: number;
}</code>

#### PaymentCardDetailsFormStyles

Options for styling the [PaymentCardDetailsForm](#paymentcarddetailsform) component. All colors should be specified in hex format.
| Property | Description |
| -------- | ----------- |
| `styles` | React Native styles for this view. _Default style in iOS is `{ minHeight: 190 }` and in Android it is `{ minHeight: 310 }`_ |
| `backgroundColor` | The background color of the form |
| `cursorColor` | The color of the cursor within the form |
| `borderWidth` | The width of the card view's border _(Android Only)_ |
| `borderColor` | The color of the card view's border _(Android Only)_ |
| `cornerRadius` | The corner radius of the card view's border _(Android Only)_ |
| `textColor` | The text color for user-entered text _(Android Only: Requires API 27+)_ |
| `fontSize` | The font size for all text input _(Android Only)_ |
| `fontFamily` | The font family used for text _(Android Only)_ |
| `placeholderColor` | The color for placeholder text _(Android Only: Requires API 27+)_ |
| `focusedPlaceholderColor` | The color for placeholder text _(Android Only: Requires API 27+)_ |
| `fontWeight` | The stroke weight of the font in each of the fields. API 28+ can support all font weights. Lower API versions interpret a [FontWeight](#fontweight) of `700` or above as `bold` and below `700` as `regular` _(Android Only)_ |
| `cardElevation` | The depth of the form view's shadow _(Android Only)_ |
| `dividerWidth` | The width of the form view's border _(Android Only)_ |
| `dividerColor` | The color of the form view's dividers _(Android Only)_ |
| `italic` | Determins if the font inside the fields should be italic style _(Android Only)_ |
| `textPaddingLeft` | Padding (in pixels) for the left of the form input area. _(Android Only)_ |
| `textPaddingRight` | Padding (in pixels) for the right of the form input area. _(Android Only)_ |

<code>{
styles?: StyleProp<ViewStyle>;
backgroundColor?: string;
cursorColor?: string;
borderColor?: string;
borderWidth?: number;
cornerRadius?: number;
textPaddingLeft?: number;
textPaddingRight?: number;
fieldDividerWidth?: number;
fieldDividerColor?: string;
cardElevation?: number;
textColor?: string;
placeholderColor?: string;
focusedPlaceholderColor?: string;
fontSize?: number;
fontFamily?: string;
fontWeight?: [FontWeight](#fontweight);
italic?: boolean;
};</code>

#### CardValidationStatus

Represents the validation state of a credit card component. This is used in the [`PaymentCardDetailsForm`](#paymentcarddetailsform) `onFormComplete` property and is extended in [`CardDetails`](#carddetails) to be used in the [`PaymentCardDetailsView`](#paymentcarddetailsview) `onCardChange` property.

| Property  | Description                                 |
| --------- | ------------------------------------------- |
| `isValid` | Whether or not the card is in a valid state |

<code>
{
  isValid: boolean;
}
</code>

#### PaymentCardCvvViewStyles

Options for styling the [PaymentCardCvvView](#paymentcardcvvview) component. All colors should be specified in hex format.

| Property           | Description                                                                                                                                                                                                                   |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `styles`           | React Native styles for this view. Default style is `{ minHeight: 45 }`                                                                                                                                                       |
| `borderWidth`      | The width of the input view's border                                                                                                                                                                                          |
| `borderColor`      | The color of the input view's border                                                                                                                                                                                          |
| `cornerRadius`     | The corner radius of the input view's border                                                                                                                                                                                  |
| `backgroundColor`  | The background color for the input view _(Android Only: Requires API 27+)_                                                                                                                                                    |
| `textColor`        | The text color for user-entered text _(Android Only: Requires API 27+)_                                                                                                                                                       |
| `fontSize`         | The font size for all text                                                                                                                                                                                                    |
| `fontFamily`       | The font family used for text                                                                                                                                                                                                 |
| `placeholderColor` | The color for placeholder text _(Android Only: Requires API 27+)_                                                                                                                                                             |
| `cursorColor`      | The color for the cursor _(Android Only: Requires API 29+)_                                                                                                                                                                   |
| `errorTextColor`   | The color of the text inside the input field if they are in an error state. Consider changing [`errorStyles.color`](#paymentcardcvvviewprops) when changing this property _(Android Only: Requires API 27+)_                  |
| `fontWeight`       | The stroke weight of the font in each of the fields. API 28+ can support all font weights. Lower API versions interpret a [FontWeight](#fontweight) of `700` or above as `bold` and below `700` as `regular` _(Android Only)_ |
| `italic`           | Determins if the font inside the field should be italic style _(Android Only)_                                                                                                                                                |
| `textPaddingLeft`  | Padding (in pixels) for the left of the card input area                                                                                                                                                                       |
| `textPaddingRight` | Padding (in pixels) for the right of the card input area                                                                                                                                                                      |
| `textAlign`        | The alignment of the text within the view. The value can be one of `left`, `center`, or `right`                                                                                                                               |

<code>{
styles?: StyleProp\<ViewStyle>;
borderWidth?: number;
borderColor?: string;
cornerRadius?: number;
backgroundColor?: string;
textColor?: string;
fontSize?: number;
fontFamily?: string;
placeholderColor?: string;
cursorColor?: string;
errorTextColor?: string;
fontWeight?: [FontWeight](#fontweight);
italic?: boolean;
textPaddingLeft?: number;
textPaddingRight?: number;
textAlign?: "left" | "center" | "right";
}</code>

#### CardDetails

Extends [`CardValidationStatus`](#cardvalidationstatus) and represents the state of the credit card component. This is used in the [`PaymentCardDetailsView`](#paymentcarddetailsview) `onCardChange` property.

| Property                   | Description                                                                                                                 |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `isValid`                  | Whether or not the card is in a valid state _(See [CardValidationStatus](#cardvalidationstatus))_                           |
| `cardType`                 | The detected card type, based on user input _(See [CardType](#cardtype))_                                                   |
| `invalidFields`            | An array of fields that are in an invalid state _(See [CardField](#cardfield))_                                             |
| `emptyFields`              | An array of fields that are empty _(See [CardField](#cardfield))_                                                           |
| `errors.editedFieldsError` | An error message that is calculated by only looking at the state of fields that have been edited (received and lost focus). |
| `errors.allFieldsError`    | An error message that is calculated by looking at the state of all fields, regardless of whether they have been edited.     |

<code>
{
  isValid: boolean;
  cardType: CardType;
  invalidFields?: CardField[];
  emptyFields?: CardField[];
  errors?: {
    editedFieldsError?: string;
    allFieldsError?: string;
  }
}
</code>

#### CvvDetails

Represents the state of the CVV component. This is used in the [`PaymentCardCvvView`](#paymentcardcvvview) `onBlur`, `onCvvChange`, and `onFocus` properties.

| Property                    | Description                                                                                                                    |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `state`                     | Provides full insight into the current state of the CVV security code input _(See [FieldState](#fieldstate))_                  |
| `errors.editedFieldError`   | An error message that is calculated by only looking at the state of the field if it has been edited (received and lost focus). |
| `errors.uneditedFieldError` | An error message that is calculated by looking at the state of the field, regardless of whether it has been edited.            |

<code>{
state: [FieldState](#fieldstate);
errors?: {
editedFieldError?: string;
uneditedFieldError?: string:
}
}
</code>

#### CvvUpdateToken

CVV Update Token used for revalidating a stored credit card

| Property                | Description                                                                     |
| ----------------------- | ------------------------------------------------------------------------------- |
| `id`                    | The CVV update token id                                                         |
| `productionEnvironment` | Boolean value indicating if the token was generated in a production environment |

<code>{
id?: string;
productionEnvironment?: boolean;
}
</code>

#### FieldState

Represents the entire state of a field

| Property     | Description                                                                             |
| ------------ | --------------------------------------------------------------------------------------- |
| `isValid`    | Whether or not the field is in a valid format                                           |
| `isFocused`  | Whether or not the field is currently being focused                                     |
| `isEmpty`    | Whether or not the field is empty                                                       |
| `wasEdited`  | Whether or not the field was edited at any point in time, even if it is currently empty |
| `wasFocused` | Whether or not the field was focused at any point                                       |

<code>{
isValid: boolean;
isFocused: boolean;
isEmpty: boolean;
wasEdited: boolean;
wasFocused: boolean;
}
</code>

#### CustomErrorMessages

Optional custom defined error messages to that can be displayed in place of default error messages. Any properties not defined will fall back to the default error messages.

| Property               | Description                                                                                                                               |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `number`               | An optional collection of custom error messages for when there is an error with the card number field _(See [CardField](#cardfield))_     |
| `expiration`           | An optional collection of custom error messages for when there is an error with the card expiration field _(See [CardField](#cardfield))_ |
| `cvv`                  | An optional collection of custom error messages for when there is an error with the card CVV field _(See [CardField](#cardfield))_        |
| `postalCode`           | An optional collection of custom error messages for when there is an error with the postal code field _(See [CardField](#cardfield))_     |
| `unsupportedCardError` | An optional custom error message for when the card type is unsupported by Olo.                                                            |

<code>
{
  number?: CustomFieldError;
  expiration?: CustomFieldError;
  cvv?: CustomFieldError;
  postalCode?: CustomFieldError;
  unsupportedCardError?: string;
}
</code>

#### CustomFieldError

Options for defining custom error messages for different error conditions.

| Property       | Description                                     |
| -------------- | ----------------------------------------------- |
| `emptyError`   | An error message for when the field is empty.   |
| `invalidError` | An error message for when the field is invalid. |

<code>
{
  emptyError?: string;
  invalidError?: string;
}
</code>

[[Back to Top]](#table-of-contents)

---

<!--
CHANGELOG SECTION
-->

## Changelog

### v4.0.1 (Mar 21, 2025)

**Updates**

- Fixed bug causing Olo Pay React Native to always pull down the latest Olo Pay iOS SDK dependency instead of the version
  that Olo Pay React Native was designed to work with, sometimes resulting in compiler and/or runtime errors.
  

### v4.0.0 (Dec 11, 2024)

**Breaking Changes**

- Removed `generalCardError` as an option when setting `CustomErrorMessages`

**Updates**

- Deprecated `OloPayInitializationConfig.freshInstall` parameter used when initializing the SDK
- [PaymentCardDetailsForm](#paymentcarddetailsform) was updated to allow for greater custom styling on Android - see [PaymentCardDetailsFormStyles](#paymentcarddetailsformstyles) for full list

**Bug Fixes**

- [PaymentCardDetailsView](#paymentcarddetailsview) - Fix bug that caused app chashes when `cardStyles.errorTextColor`, `cardStyles.textColor`, and `cardStyles.placeholderColor` were not set
- [PaymentCardCvvView](#paymentcardcvvview) - Fix bug that caused app chashes when `cvvStyles.errorTextColor`, `cvvStyles.textColor`, and `cvvStyles.placeholderColor` were not set
- Fixed a bug preventing Olo Pay SDK initialization without Apple Pay parameters
- Fixed a bug so that DP units are converted to PX units for more consistent UI across both platforms 
- Fixed bug to make custom error messages behave more consistently across both platforms

**Dependency Updates**

- Update to [Olo Pay Android SDK v3.1.2](https://github.com/ololabs/olo-pay-android-sdk-releases/releases/tag/3.1.2)
- Update to [Olo Pay iOS SDK v4.1.0](https://github.com/ololabs/olo-pay-ios-sdk-releases/releases/tag/4.1.0)

### v3.0.2 (June 28, 2024)

**Bug Fixes**

- Fix Google Pay crash bug when Google Pay initialization is interrupted by configuration changes

### v3.0.1 (June 4, 2024)

**Bug Fixes**

- Fix Google Pay crash bug when [`initialize(...)`](#initialize) is called multiple times

### v3.0.0 (Oct 31, 2023)

**Dependency Updates**

- Update to [Olo Pay Android SDK v3.0.0](https://github.com/ololabs/olo-pay-android-sdk-releases/releases/tag/v3.0.0-full)
- Update to [Olo Pay iOS SDK v4.0.0](https://github.com/ololabs/olo-pay-ios-sdk-releases/releases/tag/v4.0.0)

**Breaking Changes**

- All references to "CVC" have been replaced with "CVV"
- Removed `paddingTop` and `paddingBottom` from [PaymentCardDetailsViewStyles](#paymentcarddetailsviewstyles)
- Renamed `paddingLeft` to `textPaddingLeft` in [PaymentCardDetailsViewStyles](#paymentcarddetailsviewstyles)
- Renamed `paddingRight` to `textPaddingRight` in [PaymentCardDetailsViewStyles](#paymentcarddetailsviewstyles)
- Removed [PromiseRejectionCode](#promiserejectioncode) `incorrectNumber` and merged its use case with `invalidNumber`
- Removed [PromiseRejectionCode](#promiserejectioncode) `incorrectZip` and merged its use case with `invalidPostalCode`
- Removed [PromiseRejectionCode](#promiserejectioncode) `incorrectCvv` and merged its use case with `invalidCvv`

**Updates**

- Introduce [PaymentCardCvvView](#paymentcardcvvview) component to support Card Verification Value (CVV) tokenization
- Added `productionEnvironment` property to [PaymentMethod](#paymentmethod)
- Improved logic used to determine when to display errors on the [PaymentCardDetailsView](#paymentcarddetailsview) component
- Improved logic used to determine when to display errors on the [PaymentCardDetailsForm](#paymentcarddetailsform) component
- iOS-specific improvements to the sizing of the [PaymentCardDetailsView](#paymentcarddetailsview) component
- iOS-specific improvements to the sizing of the [PaymentCardDetailsForm](#paymentcarddetailsform) component
- Improved [PaymentCardDetailsView](#paymentcarddetailsview) error message when attempting to create a [PaymentMethod](#paymentmethod) when the component is empty

**Bugfixes**

- Fixed a bug preventing `onFocus` and `onBlur` from firing properly for [PaymentCardDetailsView](#paymentcarddetailsview) on Android
- Fixed bug with error message displaying when calling `clear()` on the [PaymentCardDetailsView](#paymentcarddetailsview)
- Fixed bug preventing `fontFamily` from being set properly on the [PaymentCardDetailsView](#paymentcarddetailsview) on Android.

### v2.0.1 (July 18, 2023)

**Dependency Updates**

- Update to [Olo Pay Android SDK v2.0.1](https://github.com/ololabs/olo-pay-android-sdk-releases/releases/tag/v2.0.1-full)

### v2.0.0 (July 14, 2023)

**Breaking Changes**

- Update to [Olo Pay Android SDK v2.0.0](https://github.com/ololabs/olo-pay-android-sdk-releases/releases/tag/v2.0.0-full)
- Update to [Olo Pay iOS SDK v3.0.0](https://github.com/ololabs/olo-pay-ios-sdk-releases/releases/tag/v3.0.0)

**Updates**

- Introduce [PaymentCardDetailsView](#paymentcarddetailsview) component to support manual credit card input
- Introduce [PaymentCardDetailsForm](#paymentcarddetailsform) component to support manual credit card input

### v1.0.2 (May 22, 2023)

**Bugfixes**

- Fix crash if negative amount is passed in to `getDigitalWalletPaymentMethod()`

### v1.0.1 (Mar 9, 2023)

**Bugfixes**

- Fix iOS installation issue
  **Updates**
- Added iOS setup documentation

### v1.0.0 (Feb 22, 2023)

- Initial release
- Uses [Olo Pay Android SDK v1.3.0](https://github.com/ololabs/olo-pay-android-sdk-releases/releases/tag/v1.3.0-full)
- Uses [Olo Pay iOS SDK v2.1.5](https://github.com/ololabs/olo-pay-ios-sdk-releases/releases/tag/v2.1.5)

[[Back to Top]](#table-of-contents)

---

<!--
# LICENSE SECTION
-->

## License

**Olo Pay Software Development Kit License Agreement**

Copyright © 2022 Olo Inc. All rights reserved.

Subject to the terms and conditions of the license, you are hereby granted a non-exclusive, worldwide, royalty-free license to (a) copy and modify the software in source code or binary form for your use in connection with the software services and interfaces provided by Olo, and (b) redistribute unmodified copies of the software to third parties. The above copyright notice and this license shall be included in or with all copies or substantial portions of the software.

Your use of this software is subject to the Olo APIs Terms of Use, available at https://www.olo.com/api-usage-terms. This license does not grant you permission to use the trade names, trademarks, service marks, or product names of Olo, except as required for reasonable and customary use in describing the origin of the software and reproducing the content of this license.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
