Source: https://developers.woosmap.com/products/geofencing-sdk/integration/braze/

> For clean Markdown of any page, append `.md` to the page URL.

> For a complete documentation index, see https://developers.woosmap.com/llms.txt

# Braze integration



Woosmap Geofencing SDK can send events to [Braze](https://www.braze.com/) from different context types:
Geofences, POI, Visits and ZOI.

Whenever location events trigger, you can send custom events with associated properties to your App via a listener
method. 

## Braze Integration

### Requirements

- **Braze SDK**: Download the latest stable SDK from
   [appropriate platform page](https://www.braze.com/docs).

### Configuration

To configure your app with the Braze SDK follow the instructions on <https://www.braze.com/docs/developer_guide/home>.

## Send Braze Custom events
Custom events let you track user activities and key conversions in your mobile app, and tie them back to corresponding push messaging campaigns.

**iOS Example**

```swift
import WoosmapGeofencing

public class DataRegion: RegionsServiceDelegate {

    // the didEnterPOIRegion() is called when a user enters in the geofence 
    public func didEnterPOIRegion(POIregion: Region) {
        
        // check first if the POIregion.origin is equal to "POI" 
        if POIregion.origin == "POI"
        {
            if let POI = POIs.getPOIbyIdStore(idstore: POIregion.identifier ?? "") as POI? {
                AppDelegate.braze?.logCustomEvent(
                  name: "woos_geofence_entered_event",
                  properties: [
                    "identifier": POI.idstore,
                    "name": POI.name
                  ]
                )
            }
            else {
                // error: Related POI doesn't exist
            }
        }
    }
```

**Android Example**

```java

import com.braze.Braze;
import com.braze.models.outgoing.BrazeProperties;

public class WoosRegionLogReadyListener implements Woosmap.RegionLogReadyListener {
    public void RegionLogReadyCallback(RegionLog regionLog) {

        POI poi = WoosmapDb.getInstance(getApplicationContext()).getPOIsDAO().getPOIbyStoreId(regionLog.idStore);

        String eventName = "woos_geofence_exited_event";

        if(regionLog.didEnter) {
            eventName = "woos_geofence_entered_event";
        }

        Braze.getInstance(getApplicationContext()).logCustomEvent("eventName",
            new BrazeProperties(new JSONObject()
                .put("identifier", poi.idStore)
                .put("name", poi.name);
        ));
    }
}
```

### Geofences Events

- Enter eventName: `woos_geofence_entered_event`
- Exit eventName: `woos_geofence_exited_event`

**Event data specification**

| Field name                         | Type     | Only if the region is a POI |
| ---------------------------------- |:---------|:---------------------------:|
| `date`                             | Datetime |                             |
| `id`                               | String   |                             |
| `latitude`                         | Double   |                             |
| `longitude`                        | Double   |                             |
| `radius`                           | Double   |                             |
| `name`                             | String   |              •              |
| `idStore`                          | String   |              •              |
| `city`                             | String   |              •              |
| `zipCode`                          | String   |              •              |
| `distance`                         | String   |              •              |
| `country_code`                     | String   |              •              |
| `address`                          | String   |              •              |
| `tags`                             | String   |              •              |
| `types`                            | String   |              •              |
| `user_properties.[field_name]`     | String   |              •              |

## React Native Integration: Send Braze Custom events from `react-native-plugin-geofencing`

[React Example project](/assets/archive/connector_braze_react.zip)

#### Braze Integration

Follow the [Braze Implementation](https://www.braze.com/docs/developer_guide/platform_integration_guides/react_native/react_sdk_setup) guide in order to add Braze plugin to your project.

#### Receiving Woosmap Geofencing Region events using iOS Notification

Follow the steps below in order to capture events of geofence SDK

***&#x31;.*** Add a new Swift class file, `GeofencingEventsReceiver.swift`, in the iOS folder and include it in your iOS workspace with the following code in it.

``` swift
import Foundation
import WoosmapGeofencing
import react_native_plugin_geofencing

extension Notification.Name {
  static let updateRegions = Notification.Name("updateRegions")
  static let didEventPOIRegion = Notification.Name("didEventPOIRegion")
}

@objc(GeofencingEventsReceiver)
class GeofencingEventsReceiver: NSObject {
  @objc public func startReceivingEvent() {
    NotificationCenter.default.addObserver(self, selector: #selector(POIRegionReceivedNotification),
                                           name: .didEventPOIRegion,
                                           object: nil)
  }
  @objc func POIRegionReceivedNotification(notification: Notification) {
    if let POIregion = notification.userInfo?["Region"] as? Region{
      // YOUR CODE HERE
      if POIregion.didEnter {
        NSLog("didEnter")
        
        // check first if the POIregion.origin is equal to "POI"
        if POIregion.origin == "POI"
        {
          if let POI = POIs.getPOIbyIdStore(idstore: POIregion.identifier) as POI? {            
            AppDelegate.braze?.logCustomEvent(
              name: "woos_geofence_entered_event",
              properties: [
                "identifier": POI.idstore,
                "name": POI.name
              ]
            )
          }
          else {
            // error: Related POI doesn't exist
          }
        }
      }
    }
  }
  // Stop receiving notification
  @objc public func stopReceivingEvent() {
    NotificationCenter.default.removeObserver(self, name: .didEventPOIRegion, object: nil)
  }
  
}
```

***&#x32;.*** Update `AppDelegate.h` and `AppDelegate.mm` and  as following

``` java
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UNUserNotificationCenter.h>
#import <BrazeKit/BrazeKit-Swift.h>
#import "BrazeReactBridge.h"

@interface AppDelegate : RCTAppDelegate<UNUserNotificationCenterDelegate>
@property (class, nonatomic, strong) Braze *braze;
@end
```

``` java
#import "Your namespace-Swift.h"

GeofencingEventsReceiver * objWoosmapReceiver;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"MarketingConnector";
  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};

  // Setup Braze
  BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:@"{BRAZE_API_KEY}"
                                                                      endpoint:@"{BRAZE_ENDPOINT}"];
  // Enable logging and customize the configuration here.
  configuration.logger.level = BRZLoggerLevelInfo;
  Braze *braze = [BrazeReactBridge initBraze:configuration];
  AppDelegate.braze = braze;

  // Setup Woosmap geofence
  objWoosmapReceiver = [GeofencingEventsReceiver new];
  [objWoosmapReceiver startReceivingEvent];
  
  
  ....
  ....
  ....
  
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
```

***&#x33;.*** Update Bridging header file to access `Appdelegate` class in `GeofencingEventsReceiver.swift` file

``` objective-c
//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "AppDelegate.h"
```

#### Receiving Woosmap Geofencing Region events using Android Broadcasts

Geofencing SDK triggers an action `com.woosmap.action.GEOFENCE_TRIGGERED` and broadcasts `regionLog` in the intent extra. The format of the data will always be as follows:

``` json
{
  "longitude": -0.1337,
  "latitude": 51.50998,
  "date": 1700824501480,
  "didenter": true,
  "identifier": "custom-region1",
  "radius": 100,
  "frompositiondetection": false,
  "eventname": "woos_geofence_exited_event",
  "spenttime": 75
}
```

Follow the steps below in order to listen to the broadcasts sent by the Woosmap Geofencing Plugin

***&#x31;.***  Add following dependencies in the `build.gradle` file of your main project.

  {% tabs react_native android/build.gradle %}

  {:title="Config" }
  ``` java
  repositories {
          ...
          ....
          maven { url 'https://jitpack.io' }
      }
  ```

  {% endtabs %}

***&#x32;.*** Add following dependencies in the `app/build.gradle` file of your main project.

  {% tabs react_native android/app/build.gradle %}

  {:title="Config" }

  ```java
    dependencies {
        ...
        ...
        implementation "androidx.room:room-runtime:2.+"
        implementation "woosmap:geofencing-core-android-sdk:core_geofence_2.+"
        implementation "com.webgeoservices.woosmapgeofencing:woosmap-mobile-sdk:4.+"
    }
  ```
  {% endtabs %}

***&#x33;.*** Add a new class GeofencingEventsReceiver.kt/java and add following code in it.

  {% tabs react_native GeofencingEventsReceiver.kt/java %}

  ``` kotlin
  
  import android.content.BroadcastReceiver
  import android.content.Context
  import android.content.Intent
  import android.util.Log
  import com.webgeoservices.woosmapgeofencingcore.database.WoosmapDb
  import org.json.JSONObject
  import java.util.concurrent.ExecutorService
  import java.util.concurrent.Executors
  import com.braze.Braze;
  import com.braze.models.outgoing.BrazeProperties;

  class GeofencingBroadcastReceiver: BroadcastReceiver() {
      val TAG: String = "GeofencingReceiver"
      private val executorService: ExecutorService = Executors.newSingleThreadExecutor()

      override fun onReceive(context: Context?, intent: Intent?) {
          Log.d(TAG, "Received broadcast")
          executorService.execute {
              try {
                  // Get region data from the intent
                  val regionData = intent?.getStringExtra("regionLog")?.let { JSONObject(it) }
                  // Fetch the POI from the db based on the identifier
                  val poi = WoosmapDb.getInstance(context).poIsDAO.getPOIbyStoreId(regionData!!.getString("identifier"))

                  if (poi != null) { //poi could be null if the entered/exited region is a custom region.
                    Braze.getInstance(context).logCustomEvent(regionData.getString("eventname"),
                        BrazeProperties(JSONObject()
                            .put("identifier", poi.idStore)
                            .put("name", poi.name)
                    ))
                  }
              } catch (ex: Exception) {
                  Log.e(TAG, ex.toString())
              }
          }
      }
  }
  ```

  ```java
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.util.Log;

  import com.webgeoservices.woosmapgeofencingcore.database.POI;
  import com.webgeoservices.woosmapgeofencingcore.database.WoosmapDb;

  import com.braze.Braze;
  import com.braze.models.outgoing.BrazeProperties;

  import org.json.JSONObject;

  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;

  public class GeofencingEventsReceiver extends BroadcastReceiver {
      private static final String TAG = "GeofencingReceiver";
      private final ExecutorService executorService = Executors.newSingleThreadExecutor();
      @Override
      public void onReceive(Context context, Intent intent) {
          Log.d(TAG, "Received broadcast");
          executorService.execute(() -> {
              try{
                  // Get region data from the intent
                  JSONObject regionData = new JSONObject(intent.getStringExtra("regionLog"));
                  // Fetch the POI from the db based on the identifier
                  POI poi;
                  poi = WoosmapDb.getInstance(context).getPOIsDAO().getPOIbyStoreId(regionData.getString("identifier"));
                  if (poi != null){ //poi could be null if the entered/exited region is a custom region.
                    Braze.getInstance(context).logCustomEvent(regionData.getString("eventname"),
                        new BrazeProperties(new JSONObject()
                            .put("identifier", poi.idStore)
                            .put("name", poi.name)
                    ));
                  }
              }
              catch (Exception ex){
                  Log.e(TAG, ex.toString());
              }
          });
      }
  }

  ```

  {% endtabs %}

***&#x34;.*** Register the newly created Broadcast Receiver from Application class.

  {% tabs react_native android/app/src/main/java/Your App Namespace/MainApplication.kt/java %}
  
  ``` kotlin
  class MainApplication : Application(), ReactApplication {
    lateinit var geofencingEventsReceiver: GeofencingEventsReceiver
    
    override fun onCreate() {
      super.onCreate()
      ...
      ...

      // Register the receiver with the filter
      geofencingEventsReceiver = GeofencingEventsReceiver()
      val filter = IntentFilter("com.woosmap.action.GEOFENCE_TRIGGERED")
      registerReceiver(geofencingEventsReceiver, filter, RECEIVER_EXPORTED)
    }
  }
  ```

  ``` java
  public class MainApplication extends Application implements ReactApplication {
    private GeofencingEventsReceiver geofencingEventsReceiver;

    @Override
    public void onCreate() {
      super.onCreate();
      ...
      ...
      // Register the receiver with the filter
      geofencingEventsReceiver = new GeofencingEventsReceiver();
      IntentFilter filter = new IntentFilter("com.woosmap.action.GEOFENCE_TRIGGERED");
      registerReceiver(geofencingEventsReceiver, filter, RECEIVER_EXPORTED);
    }
  }
  ```

  {% endtabs %}

## Flutter Integration: Send Braze Custom events from `geofencing_flutter_plugin`

[Flutter Example project](/assets/archive/connector_braze_flutter.zip)

#### Braze Integration

Follow the [Flutter Braze Implementation](https://www.braze.com/docs/developer_guide/platform_integration_guides/flutter/flutter_sdk_integration) guide to add the Braze plugin to your project.

#### Receiving Woosmap Geofencing Region events using iOS Notification

Follow the steps below to capture events of geofence SDK

***&#x31;.*** Add a new Swift class file, GeofencingEventsReceiver.swift, in the iOS folder and include it in your iOS workspace with the following code in it.

  {% tabs flutter ios/Runner/GeofencingEventsReceiver.swift %}

  ``` swift
  import Foundation
  import WoosmapGeofencing

  extension Notification.Name {
    static let updateRegions = Notification.Name("updateRegions")
    static let didEventPOIRegion = Notification.Name("didEventPOIRegion")
  }

  @objc(GeofencingEventsReceiver)
  class GeofencingEventsReceiver: NSObject {
    @objc public func startReceivingEvent() {
      NotificationCenter.default.addObserver(self, selector: #selector(POIRegionReceivedNotification),
                                            name: .didEventPOIRegion,
                                            object: nil)
    }
    @objc func POIRegionReceivedNotification(notification: Notification) {
      if let POIregion = notification.userInfo?["Region"] as? Region{
        // YOUR CODE HERE
        if POIregion.didEnter {
          NSLog("didEnter")
          
          // check first if the POIregion.origin is equal to "POI"
          if POIregion.origin == "POI"
          {
            if let POI = POIs.getPOIbyIdStore(idstore: POIregion.identifier) as POI? {
              AppDelegate.braze?.logCustomEvent(
                name: "woos_geofence_entered_event",
                properties: [
                  "identifier": POI.idstore,
                  "name": POI.name
                ]
              )
            }
            else {
              // error: Related POI doesn't exist
            }
          }
        }
      }
    }
    // Stop receiving notification
    @objc public func stopReceivingEvent() {
      NotificationCenter.default.removeObserver(self, name: .didEventPOIRegion, object: nil)
    }
    
  }
  ```

  {% endtabs %}

***&#x32;.*** Integrate `AppDelegate.swift` to receive SDK events

  {% tabs flutter ios/Runner/AppDelegate.swift %}
  
  ``` swift
  import BrazeKit
  import braze_plugin

  @objc class AppDelegate: FlutterAppDelegate {
      let objreciver:GeofencingEventsReceiver = GeofencingEventsReceiver()
      static var braze: Braze? = nil
    override func application(
      _ application: UIApplication,
      didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {

      // Setup Braze
      let configuration = Braze.Configuration(
        apiKey: "<BRAZE_API_KEY>",
        endpoint: "<BRAZE_ENDPOINT>"
      )
        // - Enable logging or customize configuration here
      configuration.logger.level = .info
      let braze = BrazePlugin.initBraze(configuration)
      AppDelegate.braze = braze

      GeneratedPluginRegistrant.register(with: self)
      ...
      ...
    }
  }
  ```

  {% endtabs %}

#### Receiving Woosmap Geofencing Region events using Android Broadcasts

Geofencing SDK triggers an action `com.woosmap.action.GEOFENCE_TRIGGERED` and broadcasts `regionLog` in the intent extra.

Follow the steps below in order to listen to the broadcasts sent by the Woosmap Geofencing Plugin.

***&#x31;.*** Add the following dependencies in the `build.gradle` file of your main project.
   
  {% tabs flutter android/build.gradle %}

  ``` java
    repositories {
            ...
            ....
            maven { url 'https://jitpack.io' }
        }
  ```

  {% endtabs %}

***&#x32;.*** Add the following dependencies in the `app/build.gradle` file of your main project.

  {% tabs flutter android/app/build.gradle %}

  ``` java
    dependencies {
        ...
        ...
        implementation "woosmap:geofencing-core-android-sdk:core_geofence_2.+"
        implementation "com.webgeoservices.woosmapgeofencing:woosmap-mobile-sdk:4.+"
    }
  ```

  {% endtabs %}

***&#x33;.*** Add a new class GeofencingEventsReceiver.java/kt, and include the following code in it.

  {% tabs flutter GeofencingEventsReceiver.java/kt %}

  ``` kotlin
  import android.content.BroadcastReceiver
  import android.content.Context
  import android.content.Intent
  import android.util.Log
  import com.webgeoservices.woosmapgeofencingcore.database.WoosmapDb
  import org.json.JSONObject
  import java.util.concurrent.ExecutorService
  import java.util.concurrent.Executors
  import com.braze.Braze;
  import com.braze.models.outgoing.BrazeProperties;

  class GeofencingBroadcastReceiver: BroadcastReceiver() {
      val TAG: String = "GeofencingReceiver"
      private val executorService: ExecutorService = Executors.newSingleThreadExecutor()

      override fun onReceive(context: Context?, intent: Intent?) {
          Log.d(TAG, "Received broadcast")
          executorService.execute {
              try {
                  // Get region data from the intent
                  val regionData = intent?.getStringExtra("regionLog")?.let { JSONObject(it) }
                  // Fetch the POI from the db based on the identifier
                  val poi = WoosmapDb.getInstance(context).poIsDAO.getPOIbyStoreId(regionData!!.getString("identifier"))

                  if (poi != null) { //poi could be null if the entered/exited region is a custom region.
                    Braze.getInstance(context).logCustomEvent(regionData.getString("eventname"),
                        BrazeProperties(JSONObject()
                            .put("identifier", poi.idStore)
                            .put("name", poi.name)
                    ))
                  }
              } catch (ex: Exception) {
                  Log.e(TAG, ex.toString())
              }
          }
      }
  }
  ```

  ```java
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.util.Log;

  import com.webgeoservices.woosmapgeofencingcore.database.POI;
  import com.webgeoservices.woosmapgeofencingcore.database.WoosmapDb;

  import org.json.JSONObject;

  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;

  import com.braze.Braze;
  import com.braze.models.outgoing.BrazeProperties;

  public class GeofencingEventsReceiver extends BroadcastReceiver {
      private static final String TAG = "GeofencingReceiver";
      private final ExecutorService executorService = Executors.newSingleThreadExecutor();
      @Override
      public void onReceive(Context context, Intent intent) {
          Log.d(TAG, "Received broadcast");
          executorService.execute(() -> {
              try{
                  // Get region data from the intent
                  JSONObject regionData = new JSONObject(intent.getStringExtra("regionLog"));
                  // Fetch the POI from the db based on the identifier
                  POI poi;
                  poi = WoosmapDb.getInstance(context).getPOIsDAO().getPOIbyStoreId(regionData.getString("identifier"));
                  if (poi != null){ //poi could be null if the entered/exited region is a custom region.
                    Braze.getInstance(context).logCustomEvent(regionData.getString("eventname"),
                        new BrazeProperties(new JSONObject()
                            .put("identifier", poi.idStore)
                            .put("name", poi.name)
                    ));
                  }
              }
              catch (Exception ex){
                  Log.e(TAG, ex.toString());
              }
          });
      }
  }
  ```

  {% endtabs %}

***&#x34;.*** If you already have a custom `android.app.Application` subclass registered, you can skip this step.
  
  Open your project's Android folder in Android Studio. Create a new class that subclasses `android.app.Application`. It can be named however you want, but we will call it `MainApplication` for the sake of this example.Place it in your root package.
  
  Then, add an onCreate() override. The class should look like this:

 ``` kotlin
  import android.app.Application
  class MainApplication: Application() {
      override fun onCreate() {
          super.onCreate()
      }
  }
  ```

  ``` java
  import android.app.Application;
  public class MainApplication extends Application {
      @Override
      public void onCreate() {
          super.onCreate();
      }
  }
  ```

***&#x35;.*** Register the newly created Broadcast Receiver in Application class.

  {% tabs flutter android/app/src/main/java/Your App Namespace/MainApplication.java/kt %}

  ``` kotlin
    class MainApplication : Application() {
      lateinit var geofencingEventsReceiver: GeofencingEventsReceiver
      
      override fun onCreate() {
        super.onCreate()
          // Register the receiver with the filter
          geofencingEventsReceiver = GeofencingEventsReceiver()
          val filter = IntentFilter("com.woosmap.action.GEOFENCE_TRIGGERED")
          registerReceiver(geofencingEventsReceiver, filter, RECEIVER_EXPORTED)
      }
    }
  ```

  ``` java
    public class MainApplication extends Application {
        private GeofencingEventsReceiver geofencingEventsReceiver;

        @Override
        public void onCreate() {
            super.onCreate();
            // Register the receiver with the filter
            geofencingEventsReceiver = new GeofencingEventsReceiver();
            IntentFilter filter = new IntentFilter("com.woosmap.action.GEOFENCE_TRIGGERED");
            registerReceiver(geofencingEventsReceiver, filter, RECEIVER_EXPORTED);
        }
    }
  ```

  {% endtabs %}
