# SDK integration

Batch Cordova is compatible with:

* cordova *9.0.0* and higher.
* cordova-android *9.0.0* and higher.
* cordova-ios *6.0.0* and higher.

Please see the native SDK documentation for minimum OS version per platform.

Ionic Cordova and Ionic Capacitor are also supported:

* Ionic *6.0* and higher.
* Ionic Capacitor (Core and CLI) *2.4.0* and higher.&#x20;
  * Capacitor *3.2.5* is not compatible with Batch: please upgrade to 3.3.0.
  * Capacitor 7.0.x is not compatible with Batch: please upgrade to 7.1 or later.

Other platforms supported by Cordova are **not supported** by Batch.

{% hint style="warning" %}
Since Batch doesn't support SPM app for Capacitor yet and Capacitor CLI 8 now creates iOS SPM projects as default, if you remove the `ios` folder, please run `npx cap add ios --packagemanager CocoaPods`.
{% endhint %}

### Setting up the SDK

{% tabs %}
{% tab title="Capacitor" %}

```bash
npm i @batch.com/cordova-plugin
npx cap sync
```

{% endtab %}

{% tab title="Ionic Cordova" %}

```bash
ionic cordova plugin add @batch.com/cordova-plugin
```

{% endtab %}

{% tab title="Cordova" %}

```bash
cordova plugin add @batch.com/cordova-plugin
```

Then, create a file named `build-extras.gradle` in your project's `platforms/android/app` folder and write the following text in it:

```
ext.postBuildExtras = {
    android {
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_17
            targetCompatibility JavaVersion.VERSION_17
        }
    }
}
```

{% endtab %}
{% endtabs %}

### Your first start

Batch exposes a global `batch` object, which is your main entry point to any API that Batch provides.

The *start* function requires you to provide a configuration object. For example, a typical implementation in the `www/js/init.js` file will be:

```javascript
// Typescript users can import the typings by uncommenting the next line
// import type {} from '@batch.com/cordova-plugin';

function onDeviceReady() {
    batch.setConfig({"androidAPIKey":"<YOUR_ANDROID_APIKEY>",
        "iOSAPIKey":"<YOUR_IOS_APIKEY>"});
    batch.start();
}

// On Ionic platforms, there might not be a onDeviceReady in your boilerplate:
//  - Ionic Angular users: in your app component and use `this.platform.ready().then(...)`
//    See https://ionicframework.com/docs/angular/platform for more info
//  - Ionic React users: Use `document.addEventListener("deviceready", callback, false);` in `index.tsx` or `capacitor.config.ts`
```

`YOUR_API_KEY` is your Batch SDK API key. You'll find it in ⚙ Settings → General.

Note that you should not use the same API key for iOS and Android. If you do not want to support one of these platforms, you are not required to provide an API Key for it.

Batch iOS API key must not be mistaken for the APNS environment Batch will output to the Xcode logs when starting. The environment depends on the app's provision, not on the Batch API Key used.

{% hint style="info" %}
Do not try to use batch in `initialize` or `bindEvents`, batch will not be loaded yet. It is guaranteed to be loaded by cordova only once the `deviceready` event has been emitted.
{% endhint %}

### Setting up push notifications

#### Android Setup

**Project setup**

Batch requires androidx to be enabled in your project.\
How to enable it depends on your environment:

* Cordova Android 9.0 has native support for androidx: add `<preference name="AndroidXEnabled" value="true" />` to your config.xml.\
  If you're using a lower Cordova Android version, please update if possible. Using Cordova Android 8 with an androidx plugin might work but is unsupported.
* Depending on your installed plugins, you might need to add an extra plugin: `ionic cordova plugin add cordova-plugin-androidx-adapter`. Ionic Cordova users are required to add this plugin.
* Ionic Capacitor users have nothing to do.

**Firebase Cloud Messaging**

On Android, Batch makes full use of Firebase Cloud Messaging (FCM).

**Cordova / Ionic Cordova**

Due to the variety of Firebase solutions in the Cordova ecosystem, Batch requires that FCM is added in your application using a separate plugin or manually.

We recommend using [`cordova-plugin-firebase-messaging`](https://github.com/chemerisuk/cordova-plugin-firebase-messaging).

One caveat is that most Cordova Firebase plugins add FCM to both Android and iOS. This might not be desired: Batch does not require Firebase on iOS, so you might not want to ship Firebase with your iOS application.

It is possible to add FCM to your project manually. Open up your `config.xml` and add these lines:

```xml
<platform name="android">
  <preference name="GradlePluginGoogleServicesEnabled" value="true" />
  <preference name="GradlePluginGoogleServicesVersion" value="4.3.3" />

  <resource-file src="build-extras.gradle" target="app/build-extras.gradle" />
</platform>
```

{% hint style="info" %}
Make sure that your `platforms/android` folder do not already have a `build-extras.gradle` file in it, as this will override it. If you do, either merge the files or remove the `resource-file` config tag.
{% endhint %}

If you're using an older Cordova version, you might need extra plugins such as `cordova-plugin-androidx` , `cordova-support-google-services` and `cordova-support-android-plugin`.

Then, at the root of your application project, create a new file called `build-extras.gradle` and add the following in it:

```groovy
repositories {
    mavenCentral()
    maven {
        url "https://maven.google.com"
    }
}

dependencies {
    implementation "androidx.appcompat:appcompat:1.2.+"
    implementation "com.google.firebase:firebase-messaging:21.0.+"
    // Uncomment this line if you want Advertising ID support
    //implementation "com.google.android.gms:play-services-ads-identifier:+"
    // Uncomment this line if you use firebase-messaging 22 or greater
    //implementation "com.google.firebase:firebase-iid:21.1.0"
}
```

{% hint style="info" %}
This documentation isn't updated with androidx.core and firebase-messaging's latest versions. Please use up to date versions of these dependencies when possible.
{% endhint %}

Once you've set up FCM, you will need to configure `google-services.json`. How to add it into your app depends on your plugin, but common steps are:

* Download `google-services.json` and save it in your app's root directory.\
  If you don't have this file yet, please follow the "Manually add Firebase" part of [this](https://firebase.google.com/docs/android/setup#manually_add_firebase) documentation until you get it.
* Tell Cordova to copy it. Your firebase plugin should come with instructions on how to do so.\
  If not, the following `config.xml` items might work:

```xml
<platform name="android">
    <resource-file src="google-services.json" target="app/google-services.json" />
</platform>
```

**Ionic Capacitor**

Open `android/variables.gradle` and add `firebaseMessagingVersion = "22.0.0"` if missing. You may want to use the latest [firebase-messaging](https://firebase.google.com/support/release-notes/android) version.

```groovy
ext {
    minSdkVersion = 21
    ...
    cordovaAndroidVersion = '9.0.0'
    firebaseMessagingVersion = '22.0.0'
}
```

Then, please follow [Capacitor's Android Push Notifications documentation](https://capacitorjs.com/docs/guides/push-notifications-firebase#android) to configure Firebase.

**Setting your small icon**

Follow the [Customizing Batch notifications](/developer/sdk/cordova/advanced/customizing-notifications.md) guide to display your notification icon correctly on Android.

#### iOS Setup

First, configure your generated Xcode project to add the push capability. Ionic should only generate the project once, but Cordova users might need to do this after regenerating the platform, or using a plugin.

* Open your project workspace in Xcode (`.xcworkspace`, or `.xcodeproj` if missing)
* Select on your main App project in the sidebar if you opened a workspace
* Select your main application target
* Click on the `Signing & Capabilities` tab. If `Push Notifications` isn't already there, click on `+ Capability` and pick `Push Notifications`.

![Xcode Capabilities](/files/YryBEN6ccJJwvNtgbSmb)

**Rich Push**

In order to enable rich content in notifications (such as images), a Notification Service extension must be added in the Xcode project.\
First, locate your Xcode project: it should be located `platforms/ios/` and be named `<yourapp>.xcworkspace`.

Then, follow the [native rich push setup documentation](/developer/sdk/ios/sdk-integration/rich-notifications-setup.md).

{% hint style="info" %}
This needs to be performed each time the `platforms/ios` directory is regenerated.
{% endhint %}

#### Common setup

```javascript
// Typescript users can import the typings by uncommenting the next line
// import type {} from '@batch.com/cordova-plugin';

function onDeviceReady() {
    batch.setConfig({"androidAPIKey":"<YOUR ANDROID APIKEY>",
        "iOSAPIKey":"<YOUR IOS APIKEY>"});
    batch.start();
    
    // Ask for the permission to display notifications
    batch.push.requestNotificationAuthorization();
    // Or use the async variant
    // const granted = await batch.push.requestNotificationAuthorizationAsync();

    // iOS ONLY:
    // Using the above method, the push token will automatically be fetched by the SDK
    // Alternatively, you can call requestNotificationAuthorization later
    // if you uncomment the following line.
    // But, you should always refresh your token on each application start
    // This will make sure that even if your user's token changes, you still get notifications.
    //batch.push.refreshToken();
}
```

### Your first notification

**1. Obtaining your device token**

You can find your device's token using the [debug tool](/developer/sdk/cordova/profile-data/debug.md) or locating the token Batch posts to the logs. Be sure to launch the app on your device linked to your computer.

Batch's logs are displayed in the logcat/Xcode console, but they are also forwarded.

Recent Android versions should show logs that happened before you opened Chrome's debugger, but older android versions and iOS do not, so you might miss the push token here. In that case, you need to take a look in the device logs *(Window -> Devices for Xcode, `adb logcat` for android)*.

The line you are looking for within the logcat/console is:

```android
Batch.Push: Registration id: X

//Where X represents the Batch Push token for your device.
```

```ios
[Batch] - Push token (Production): X
OR
[Batch] - Push token (Development): X

//Where X represents the Batch Push token for your device.
//
//The token shown in the console will be Production or Development based on 
//your Provisioning Profile. Be sure to note which token you are working with. 
//If you are having troubles finding the entry, searching for Batch will 
//find the correct entries.
```

**2. Sending a test push**

Go to ⚙ Settings → Push settings, paste your device's token and click on **Save**. On iOS, make sure you chose the right environment.

Then, all you have to do is to click on the **"Send"** button. If you sucessfuly set up the SDK, you will receive a notification on your device.

![Test push iOS](/files/q9U6zNElnyvYWXj0I4oi)

If you're having trouble sending test notifications, you can check our troubleshooting documentation:\\

* [iOS](/developer/sdk/ios/troubleshooting.md)
* [Android](/developer/sdk/android/troubleshooting.md)

#### What's next

*Congratulations on finishing the integration of Batch Push!*

Here are a couple of extra steps you can take before releasing your app:

* **Small icon / Accent color**: On Android, make sure the [small icon](/developer/sdk/cordova/advanced/customizing-notifications.md#custom-small-notification-icon) you are using is **opaque white**. We also recommend you use an accent color.
* **Custom user identifier**: Add support for [custom user identifiers](/developer/sdk/cordova/profile-data/custom-user-id.md) if you are planning to use the [Transactional](/developer/api/mep/transactional.md) or the [Custom Data](/developer/api/mep/custom-data-api.md) APIs.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.batch.com/developer/sdk/cordova/sdk-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
