Skip to content

Braze SDKの統合

Braze SDKをモバイルアプリに統合する方法を学習。各SDKは、独自のGitHub公開リポジトリでホストされており、Brazeの機能をテストしたり、独自のアプリケーションと一緒に実装するために使用できる、完全にビルド可能なサンプルアプリが含まれている。詳しくは、学習、リポジトリ、サンプルアプリを参照のこと。SDKに関する一般的な情報については、はじめにを参照のこと:統合の概要

Integrating the Android SDK

Step 1: Update your build.gradle

In your build.gradle, add mavenCentral() to your list of repositories.

1
2
3
repositories {
  mavenCentral()
}

Next, add Braze to your dependencies.

If you don’t plan on using Braze UI components, add the following code to your build.gradle. Replace SDK_VERSION with the current version of your Android Braze SDK. For the full list of versions, see Changelogs.

1
2
3
4
dependencies {
    implementation 'com.braze:android-sdk-base:SDK_VERSION' // (Required) Adds dependencies for the base Braze SDK.
    implementation 'com.braze:android-sdk-location:SDK_VERSION' // (Optional) Adds dependencies for Braze location services.
}

If you plan on using Braze UI components later, add the following code to your build.gradle. Replace SDK_VERSION with the current version of your Android Braze SDK. For the full list of versions, see Changelogs.

1
2
3
4
dependencies {
    implementation 'com.braze:android-sdk-ui:SDK_VERSION' // (Required) Adds dependencies for the Braze SDK and Braze UI components. 
    implementation 'com.braze:android-sdk-location:SDK_VERSION' // (Optional) Adds dependencies for Braze location services.
}

Step 2: Configure your braze.xml

Create a braze.xml file in your project’s res/values folder. If you are on a specific data cluster or have a pre-existing custom endpoint, you need to specify the endpoint in your braze.xml file as well.

The contents of that file should resemble the following code snippet. Make sure to substitute YOUR_APP_IDENTIFIER_API_KEY with the identifier found in the Manage Settings page of the Braze dashboard. Log in at dashboard.braze.com to find your cluster address.

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="com_braze_api_key">YOUR_APP_IDENTIFIER_API_KEY</string>
<string translatable="false" name="com_braze_custom_endpoint">YOUR_CUSTOM_ENDPOINT_OR_CLUSTER</string>
</resources>

Step 3: Add permissions to AndroidManifest.xml

Next, add the following permissions to your AndroidManifest.xml:

1
2
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step 4: Enable user session tracking

When you enable user session tracking, calls to openSession(), closeSession(),ensureSubscribedToInAppMessageEvents(), and InAppMessageManager registration can be handled automatically.

To register activity lifecycle callbacks, add the following code to the onCreate() method of your Application class.

1
2
3
4
5
6
7
public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(new BrazeActivityLifecycleCallbackListener());
  }
}
1
2
3
4
5
6
class MyApplication : Application() {
  override fun onCreate() {
    super.onCreate()
    registerActivityLifecycleCallbacks(BrazeActivityLifecycleCallbackListener())
  }
}

For the list of available parameters, see BrazeActivityLifecycleCallbackListener.

Testing session tracking

If you experience issues while testing, enable verbose logging, then use logcat to detect missing openSession and closeSession calls in your activities.

  1. In Braze, go to Overview, select your app, then in the Display Data For dropdown choose Today. The "Overview" page in Braze, with the "Display Data For" field set to "Today".
  2. Open your app, then refresh the Braze dashboard. Verify that your metrics have increased by 1.
  3. Navigate through your app and verify that only one session has been logged to Braze.
  4. Send the app to the background for at least 10 seconds, then bring it to the foreground. Verify that a new session was logged.

Optional configurations

Runtime configuration

To set your Braze options in code rather than your braze.xml file, use runtime configuration. If a value exists in both places, the runtime value will be used instead. After all required settings are supplied at runtime, you can delete your braze.xml file.

In the following example, a builder object is created and then passed to Braze.configure(). Note that only some of the available runtime options are shown—refer to our KDoc for the full list.

1
2
3
4
5
6
7
8
BrazeConfig brazeConfig = new BrazeConfig.Builder()
        .setApiKey("api-key-here")
        .setCustomEndpoint("YOUR_CUSTOM_ENDPOINT_OR_CLUSTER")
        .setSessionTimeout(60)
        .setHandlePushDeepLinksAutomatically(true)
        .setGreatNetworkDataFlushInterval(10)
        .build();
Braze.configure(this, brazeConfig);
1
2
3
4
5
6
7
8
val brazeConfig = BrazeConfig.Builder()
        .setApiKey("api-key-here")
        .setCustomEndpoint("YOUR_CUSTOM_ENDPOINT_OR_CLUSTER")
        .setSessionTimeout(60)
        .setHandlePushDeepLinksAutomatically(true)
        .setGreatNetworkDataFlushInterval(10)
        .build()
Braze.configure(this, brazeConfig)

Google Advertising ID

The Google Advertising ID (GAID) is an optional user-specific, anonymous, unique, and resettable ID for advertising, provided by Google Play services. GAID gives users the power to reset their identifier, opt-out of interest-based ads within Google Play apps, and provides developers with a simple, standard system to continue to monetize their apps.

The Google Advertising ID is not automatically collected by the Braze SDK and must be set manually via the Braze.setGoogleAdvertisingId() method.

1
2
3
4
5
6
7
8
9
10
11
new Thread(new Runnable() {
  @Override
  public void run() {
    try {
      AdvertisingIdClient.Info idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
      Braze.getInstance(getApplicationContext()).setGoogleAdvertisingId(idInfo.getId(), idInfo.isLimitAdTrackingEnabled());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}).start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
suspend fun fetchAndSetAdvertisingId(
  context: Context,
  scope: CoroutineScope = GlobalScope
) {
  scope.launch(Dispatchers.IO) {
    try {
      val idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context)
      Braze.getInstance(context).setGoogleAdvertisingId(
        idInfo.id,
        idInfo.isLimitAdTrackingEnabled
      )
    } catch (e: Exception) {
      e.printStackTrace()
    }
  }
}

Location tracking

To enable Braze location collection, set com_braze_enable_location_collection to true in your braze.xml file:

1
<bool name="com_braze_enable_location_collection">true</bool>

Logging

By default, the Braze Android SDK log level is set to INFO. You can suppress these logs or set a different log level, such as VERBOSE, DEBUG, or WARN.

Enabling logs

To help troubleshoot issues in your app, or reduce turnaround times with Braze Support, you’ll want to enable verbose logs for the SDK. When you send verbose logs to Braze Support, ensure they begin as soon as you launch your application and end far after your issue occurs.

Keep in mind, verbose logs are only intended for your development environment, so you’ll want to disable them before releasing your app.

To enable logs directly in your app, add the following to your application’s onCreate() method before any other methods.

1
BrazeLogger.setLogLevel(Log.MIN_LOG_LEVEL);
1
BrazeLogger.logLevel = Log.MIN_LOG_LEVEL

Replace MIN_LOG_LEVEL with the Constant of the log level you’d like to set as your minimum log level. Any logs at a level >= to your set MIN_LOG_LEVEL will be forwarded to Android’s default Log method. Any logs < your set MIN_LOG_LEVEL will be discarded.

For example, the following code will forward log levels 2, 3, 4, 5, 6, and 7 to the Log method.

1
BrazeLogger.setLogLevel(Log.VERBOSE);
1
BrazeLogger.logLevel = Log.VERBOSE

To enable logs in the braze.xml, add the following to your file:

1
<integer name="com_braze_logger_initial_log_level">MIN_LOG_LEVEL</integer>

Replace MIN_LOG_LEVEL with the Value of the log level you’d like to set as your minimum log level. Any logs at a level >= to your set MIN_LOG_LEVEL will be forwarded to Android’s default Log method. Any logs < your set MIN_LOG_LEVEL will be discarded.

For example, the following code will forward log levels 2, 3, 4, 5, 6, and 7 to the Log method.

1
<integer name="com_braze_logger_initial_log_level">2</integer>

Verifying verbose logs

To verify that your logs are set to VERBOSE, check if V/Braze occurs somewhere in your logs. If it does, then verbose logs have been successfully enabled. For example:

1
2077-11-19 16:22:49.591 ? V/Braze v9.0.01 .bo.app.d3: Request started

Suppressing logs

To suppress all logs for the Braze Android SDK, set the log level to BrazeLogger.SUPPRESS in your application’s onCreate() method before any other methods.

1
BrazeLogger.setLogLevel(BrazeLogger.SUPPRESS);
1
BrazeLogger.setLogLevel(BrazeLogger.SUPPRESS)

Multiple API keys

The most common use case for multiple API keys is separating API keys for debug and release build variants.

To easily switch between multiple API keys in your builds, we recommend creating a separate braze.xml file for each relevant build variant. A build variant is a combination of build type and product flavor. By default, new Android projects are configured with debug and release build types and no product flavors.

For each relevant build variant, create a new braze.xml in the src/<build variant name>/res/values/ directory. When the build variant is compiled, it will use the new API key.

1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="com_braze_api_key">REPLACE_WITH_YOUR_BUILD_VARIANT_API_KEY</string>
</resources>

Exclusive in-app message TalkBack

In adherence to the Android accessibility guidelines, the Braze Android SDK offers Android Talkback by default. To ensure that only the contents of in-app messages are read out loud—without including other screen elements like the app title bar or navigation—you can enable exclusive mode for TalkBack.

To enable exclusive mode for in-app messages:

1
<bool name="com_braze_device_in_app_message_accessibility_exclusive_mode_enabled">true</bool>
1
2
3
val brazeConfigBuilder = BrazeConfig.Builder()
brazeConfigBuilder.setIsInAppMessageAccessibilityExclusiveModeEnabled(true)
Braze.configure(this, brazeConfigBuilder.build())
1
2
3
BrazeConfig.Builder brazeConfigBuilder = new BrazeConfig.Builder()
brazeConfigBuilder.setIsInAppMessageAccessibilityExclusiveModeEnabled(true);
Braze.configure(this, brazeConfigBuilder.build());

R8 and ProGuard

Code shrinking configuration is automatically included with your Braze integration.

Client apps that obfuscate Braze code must store release mapping files for Braze to interpret stack traces. If you want to continue to keep all Braze code, add the following to your ProGuard file:

1
2
-keep class bo.app.** { *; }
-keep class com.braze.** { *; }

Integrating the Swift SDK

You can integrate and customize the Braze Swift SDK using the Swift Package Manager (SPM), CocoaPods, or manual integration methods. For more information about the various SDK symbols, see Braze Swift reference documentation.

Prerequisites

Before you start, verify your environment is supported by the latest Braze Swift SDK version.

Step 1: Install the Braze Swift SDK

We recommend using the Swift Package Manager (SwiftPM) or CocoaPods to install the Braze Swift SDK. Alternatively, you can install the SDK manually.

Step 1.1: Import SDK version

Open your project and navigate to your project’s settings. Select the Swift Packages tab and click on the add button below the packages list.

Enter the URL of our iOS Swift SDK repository https://github.com/braze-inc/braze-swift-sdk in the text field. Under the Dependency Rule section, select the SDK version. Finally, click Add Package.

Step 1.2: Select your packages

The Braze Swift SDK separates features into standalone libraries to provide developers with more control over which features to import into their projects.

Package Details
BrazeKit Main SDK library providing support for analytics and push notifications.
BrazeLocation Location library providing support for location analytics and geofence monitoring.
BrazeUI Braze-provided user interface library for in-app messages, Content Cards, and Banners. Import this library if you intend to use the default UI components.
About Extension libraries
Package Details
BrazeNotificationService Notification service extension library providing support for rich push notifications.
BrazePushStory Notification content extension library providing support for Push Stories.

Select the package that best suits your needs and click Add Package. Make sure you select BrazeKit at a minimum.

Step 1.1: Install CocoaPods

For a full walkthrough, see CocoaPods’ Getting Started Guide. Otherwise, you can run the following command to get started quickly:

1
$ sudo gem install cocoapods

If you get stuck, checkout CocoaPods’ Troubleshooting Guide.

Step 1.2: Constructing the Podfile

Next, create a file in your Xcode project directory named Podfile.

Add the following line to your Podfile:

1
2
3
target 'YourAppTarget' do
  pod 'BrazeKit'
end

BrazeKit contains the main SDK library, providing support for analytics and push notifications.

We suggest you version Braze so pod updates automatically grab anything smaller than a minor version update. This looks like pod 'BrazeKit' ~> Major.Minor.Build. If you want to automatically integrate the latest Braze SDK version, even with major changes, you can use pod 'BrazeKit' in your Podfile.

About additional libraries

The Braze Swift SDK separates features into standalone libraries to provide developers with more control over which features to import into their projects. In addition to BrazeKit, you may add the following libraries to your Podfile:

Library Details
pod 'BrazeLocation' Location library providing support for location analytics and geofence monitoring.
pod 'BrazeUI' Braze-provided user interface library for in-app messages, Content Cards, and Banners. Import this library if you intend to use the default UI components.
Extension libraries

BrazeNotificationService and BrazePushStory are extension modules that provide additional functionality and should not be added directly to your main application target. Instead, you will need to create separate extension targets for each of these modules and import the Braze modules into their corresponding targets.

Library Details
pod 'BrazeNotificationService' Notification service extension library providing support for rich push notifications.
pod 'BrazePushStory' Notification content extension library providing support for Push Stories.

Step 1.3: Install the SDK

To install the Braze SDK CocoaPod, navigate to the directory of your Xcode app project within your terminal and run the following command:

1
pod install

At this point, you should be able to open the new Xcode project workspace created by CocoaPods. Make sure to use this Xcode workspace instead of your Xcode project.

A Braze Example folder expanded to show the new `BrazeExample.workspace`.

Updating the SDK using CocoaPods

To update a CocoaPod, simply run the following command within your project directory:

1
pod update

Step 1.1: Download the Braze SDK

Go to the Braze SDK release page on GitHub, then download braze-swift-sdk-prebuilt.zip.

"The Braze SDK release page on GitHub."

Step 1.2: Choose your frameworks

The Braze Swift SDK contains a variety of standalone XCFrameworks, which gives you the freedom to integrate the features you want—without needing to integrate them all. Reference the following table to choose your XCFrameworks:

Package Required? Description
BrazeKit Yes Main SDK library that provides support for analytics and push notifications.
BrazeLocation No Location library that provides support for location analytics and geofence monitoring.
BrazeUI No Braze-provided user interface library for in-app messages, Content Cards, and Banners. Import this library if you intend to use the default UI components.
BrazeNotificationService No Notification service extension library that provides support for rich push notifications. Do not add this library directly to your main application target, instead add the BrazeNotificationService library separately.
BrazePushStory No Notification content extension library that provides support for Push Stories. Do not add this library directly to your main application target, instead add the BrazePushStory library separately.
BrazeKitCompat No Compatibility library containing all the Appboy and ABK* classes and methods that were available in the Appboy-iOS-SDK version 4.X.X. For usage details, refer to the minimal migration scenario in the migration guide.
BrazeUICompat No Compatibility library containing all the ABK* classes and methods that were available in the AppboyUI library from Appboy-iOS-SDK version 4.X.X. For usage details, refer to the minimal migration scenario in the migration guide.
SDWebImage No Dependency used only by BrazeUICompat in the minimal migration scenario.

Decide whether you want to use Static or Dynamic XCFrameworks, then prepare your files:

  1. Create a temporary directory for your XCFrameworks.
  2. In braze-swift-sdk-prebuilt, open the dynamic directory and move BrazeKit.xcframework into your directory. Your directory should be similar to the following:
    1
    2
    
     temp_dir
     └── BrazeKit.xcframework
    
  3. Move each of your chosen XCFrameworks into your temporary directory. Your directory should be similar to the following:
    1
    2
    3
    4
    5
    
     temp_dir
     ├── BrazeKit.xcframework
     ├── BrazeKitCompat.xcframework
     ├── BrazeLocation.xcframework
     └── SDWebImage.xcframework
    

Step 1.4: Integrate your frameworks

Next, integrate the Dynamic or Static XCFrameworks you prepared previously:

In your Xcode project, select your build target, then General. Under Frameworks, Libraries, and Embedded Content, drag and drop the files you prepared previously.

"An example Xcode project with each Braze library set to 'Embed & Sign.'"

Common errors for Objective-C projects

If your Xcode project only contains Objective-C files, you may get “missing symbol” errors when you try to build your project. To fix these errors, open your project and add an empty Swift file to your file tree. This will force your build toolchain to embed Swift Runtime and link to the appropriate frameworks during build time.

1
FILE_NAME.swift

Replace FILE_NAME with any non-spaced string. Your file should look similar to the following:

1
empty_swift_file.swift

Step 2: Set up delayed initialization (optional)

You can choose to delay when the Braze Swift SDK is initialized, which is useful if your app needs to load config or wait for user consent before starting the SDK. Delayed initialization ensures Braze push notifications are queued until the SDK is ready.

To enable this, call Braze.prepareForDelayedInitialization() as early as possible—ideally inside or before your application(_:didFinishLaunchingWithOptions:).

1
2
3
4
5
6
7
8
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // Prepare the SDK for delayed initialization
  Braze.prepareForDelayedInitialization()

  // ... Additional non-Braze setup code

  return true
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@main
struct MyApp: App {
  @UIApplicationDelegateAdaptor var appDelegate: AppDelegate

  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    // Prepare the SDK for delayed initialization
    Braze.prepareForDelayedInitialization()

    // ... Additional non-Braze setup code

    return true
  }
}
1
2
3
4
5
6
7
8
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Prepare the SDK for delayed initialization
  [Braze prepareForDelayedInitialization];
  
  // ... Additional non-Braze setup code

  return YES;
}

Step 3: Update your app delegate

Add the following line of code to your AppDelegate.swift file to import the features included in the Braze Swift SDK:

1
import BrazeKit

Next, add a static property to your AppDelegate class to keep a strong reference to the Braze instance throughout your application’s lifetime:

1
2
3
class AppDelegate: UIResponder, UIApplicationDelegate {
  static var braze: Braze? = nil
}

Finally, in AppDelegate.swift, add the following snippet to your application:didFinishLaunchingWithOptions: method:

1
2
3
4
5
6
let configuration = Braze.Configuration(
    apiKey: "YOUR-APP-IDENTIFIER-API-KEY",
    endpoint: "YOUR-BRAZE-ENDPOINT"
)
let braze = Braze(configuration: configuration)
AppDelegate.braze = braze

Update YOUR-APP-IDENTIFIER-API-KEY and YOUR-BRAZE-ENDPOINT with the correct value from your App Settings page. Check out our API identifier types for more information on where to find your app identifier API key.

Add the following line of code to your AppDelegate.m file:

1
@import BrazeKit;

Next, add a static variable to your AppDelegate.m file to keep a reference to the Braze instance throughout your application’s lifetime:

1
2
3
4
5
6
7
8
9
10
11
static Braze *_braze;

@implementation AppDelegate
+ (Braze *)braze {
  return _braze;
}

+ (void)setBraze:(Braze *)braze {
  _braze = braze;
}
@end

Finally, within your AppDelegate.m file, add the following snippet within your application:didFinishLaunchingWithOptions: method:

1
2
3
4
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:"YOUR-APP-IDENTIFIER-API-KEY"
                                                                  endpoint:"YOUR-BRAZE-ENDPOINT"];
Braze *braze = [[Braze alloc] initWithConfiguration:configuration];
AppDelegate.braze = braze;

Update YOUR-APP-IDENTIFIER-API-KEY and YOUR-BRAZE-ENDPOINT with the correct value from your Manage Settings page. Check out our API documentation for more information on where to find your app identifier API key.

Optional configurations

Logging

Log levels

The default log level for the Braze Swift SDK is .error—it’s also the minimum supported level when logs are enabled. These are the full list of log levels:

Swift Objective-C Description
.debug BRZLoggerLevelDebug (Default) Log debugging information + .info + .error.
.info BRZLoggerLevelInfo Log general SDK information (user changes, etc.) + .error.
.error BRZLoggerLevelError Log errors.
.disabled BRZLoggerLevelDisabled No logging occurs.

You can assign the log level at runtime in your Braze.Configuration object. For complete usage details, see Braze.Configuration.Logger.

1
2
3
4
5
6
7
let configuration = Braze.Configuration(
  apiKey: "<BRAZE_API_KEY>",
  endpoint: "<BRAZE_ENDPOINT>"
)
// Enable logging of general SDK information (such as user changes, etc.)
configuration.logger.level = .info
let braze = Braze(configuration: configuration)
1
2
3
4
5
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:self.APIKey
                                                                  endpoint:self.apiEndpoint];
// Enable logging of general SDK information (such as user changes, etc.)
[configuration.logger setLevel:BRZLoggerLevelInfo];
Braze *braze = [[Braze alloc] initWithConfiguration:configuration];

Web Braze SDKについて

Web Braze SDKを使用すると、分析を収集し、リッチなアプリ内メッセージ、プッシュ、コンテンツカードメッセージをWebユーザーに表示することができます。詳しくは、Braze JavaScript reference参照のこと。

Web SDKを統合する

ステップ1:Brazeライブラリをインストールする

Brazeライブラリは、以下のいずれかの方法でインストールできます。ウェブサイトがContent-Security-Policy を使用している場合、ライブラリをインストールする前に、コンテンツ・セキュリティ・ポリシー・ヘッダ・ガイドを参照してください。

あなたのサイトがNPMまたはYarnパッケージマネージャを使用している場合、依存関係としてBraze NPMパッケージを追加することができます。

v3.0.0 からタイプスクリプトの定義が含まれるようになりました。2.x から 3.x へのアップグレードに関する注意事項については、changelog を参照してください。

1
2
3
npm install --save @braze/web-sdk
# or, using yarn:
# yarn add @braze/web-sdk

インストール後は、通常の方法でライブラリを import または require できます。

1
2
3
import * as braze from "@braze/web-sdk";
// or, using `require`
const braze = require("@braze/web-sdk");

Braze Web SDK は、Google Tag Manager テンプレートライブラリからインストールできます。2つのタグがサポートされています:

  1. 初期化タグ:Web SDKをウェブサイトにロードし、オプションで外部ユーザーIDを設定します。
  2. アクションタグ: カスタムイベント、購入、ユーザー ID の変更、または SDK トラッキングの切り替えをトリガーするために使用されます。

詳しくは Google Tag Manager 統合ガイドを参照してください。

Braze Web SDKをHTMLに直接追加するには、当社のCDNホストスクリプトを参照し、ライブラリを非同期で読み込みます。

ステップ2: SDKを初期化する(オプション)

タグマネージャーでBrazeの初期化オプションを設定している場合は、このステップを省略できます。

そうでない場合は、Braze Web SDKをWebサイトに追加した後、Brazeダッシュボード内の設定>アプリ設定にあるAPIキーとSDKエンドポイントURLでライブラリを初期化する。他のJavaScriptメソッドと共に、braze.initialize() のオプションの完全なリストについては、Braze JavaScriptドキュメントを参照のこと。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// initialize the SDK
braze.initialize('YOUR-API-KEY-HERE', {
    baseUrl: "YOUR-SDK-ENDPOINT-HERE"
});

// optionally show all in-app messages without custom handling
braze.automaticallyShowInAppMessages();

// if you use Content Cards
braze.subscribeToContentCardsUpdates(function(cards){
    // cards have been updated
});

// optionally set the current user's external ID before starting a new session
// you can also call `changeUser` later in the session after the user logs in
if (isLoggedIn){
    braze.changeUser(userIdentifier);
}

// `openSession` should be called last - after `changeUser` and `automaticallyShowInAppMessages`
braze.openSession();

オプション構成

ロギング

ロギングをすばやく有効にするには、?brazeLogging=true をパラメーターとして Web サイト URL に追加します。あるいは、基本ロギングまたはカスタム・ロギングを有効にすることもできます。

基本的なロギング

enableLogging 、SDKが初期化される前にJavaScriptコンソールに基本的なデバッグメッセージを記録する。

1
enableLogging: true

メソッドは次のようになるはずです。

1
2
3
4
5
braze.initialize('API-KEY', {
    baseUrl: 'API-ENDPOINT',
    enableLogging: true
});
braze.openSession();

SDKが初期化された後、JavaScriptコンソールに基本的なデバッグメッセージを記録するには、braze.toggleLogging() を使用する。メソッドは次のようになるはずです。

1
2
3
4
5
6
braze.initialize('API-KEY', {
    baseUrl: 'API-ENDPOINT',
});
braze.openSession();
...
braze.toggleLogging();

カスタムロギング

setLogger を使って、カスタムデバッグメッセージをJavaScriptコンソールに記録する。基本ログとは異なり、これらのログはユーザーには見えません。

1
setLogger(loggerFunction: (message: STRING) => void): void

STRING を1つの文字列パラメーターとしてメッセージに置き換えます。メソッドは次のようになるはずです。

1
2
3
4
5
braze.initialize('API-KEY');
braze.setLogger(function(message) {
    console.log("Braze Custom Logger: " + message);
});
braze.openSession();

SDKをアップグレードする

Braze Web SDKを当社のコンテンツデリバリーネットワーク、例えばhttps://js.appboycdn.com/web-sdk/a.a/braze.min.js (当社のデフォルトの統合手順で推奨されている)から参照すると、ユーザーがサイトを更新したときに、マイナーアップデート(バグフィックスと下位互換機能、上記の例ではバージョンa.a.aa.a.z )を自動的に受け取ることができます。

ただし、当社が大きな変更をリリースする場合は、Braze Web SDK を手動でアップグレードして、統合に重大な変更の影響がないようにする必要があります。さらに、当社のSDKをダウンロードして自分でホスティングする場合、バージョン・アップデートを自動的に受け取ることはできないので、最新の機能やバグ修正を受け取るには手動でアップグレードする必要があります。

RSS Reader または任意のサービスを使用して、リリースフィードに従って最新のリリースを取得できます。また、Web SDK のリリース履歴の詳細については、変更ログを参照してください。Braze Web SDKをアップグレードします:

  • バージョン番号 https://js.appboycdn.com/web-sdk/[OLD VERSION NUMBER]/braze.min.js を変更するか、パッケージマネージャーの依存関係で、Braze ライブラリのバージョンを更新します。
  • Web プッシュが統合されている場合は、サイトのサービスワーカーファイルを更新します。デフォルトでは、このファイルはサイトのルートディレクトリの/service-worker.js にありますが、統合によっては場所がカスタマイズされている場合があります。サービスワーカーファイルをホストするには、ルートディレクトリにアクセスしなければなりません。

これら2つのファイルを適切に機能させるには、相互に連携して更新する必要があります。

Googleタグマネージャー

Google Tag Manager (GTM)を使えば、プロダクションコードのリリースや開発リソースを必要とせずに、Webサイトのタグをリモートで追加、削除、編集できる。Brazeは以下のGTMテンプレートを提供している:

どちらのタグも、Googleのコミュニティ・ギャラリーから、またはコミュニティ・テンプレートから新しいタグを追加する際にBrazeを検索することで、ワークスペースに追加することができる。

ギャラリー検索の画像

グーグルのEUユーザー同意ポリシーの更新

Google のEU ユーザー同意ポリシーの一部として、次のブール値カスタム属性をユーザープロファイルに記録する必要があります。

  • $google_ad_user_data
  • $google_ad_personalization

GTM 統合を使用してこれらを設定する場合、カスタム属性でカスタム HTML タグを作成する必要があります。以下は、これらの値を(文字列としてではなく)ブールデータ型としてログに記録する方法の例です。

1
2
3
<script>
window.braze.getUser().setCustomUserAttribute("$google_ad_personalization", true);
</script>

詳細については、オーディエンスを Google に同期するを参照してください。

その他の統合方法

アクセラレイテッド・モバイル・ページ(AMP)

もっと見る

ステップ1:AMP Web プッシュスクリプトを含める

次の非同期スクリプトタグをヘッドに追加します:

1
<script async custom-element="amp-web-push" src="https://cdn.ampproject.org/v0/amp-web-push-0.1.js"></script>

ステップ2:サブスクリプション・ウィジェットを追加する

HTMLの本文にウィジェットを追加し、ユーザーがプッシュ配信の登録と配信停止を行えるようにする。

1
2
3
4
5
6
7
8
9
<!-- A subscription widget -->
<amp-web-push-widget visibility="unsubscribed" layout="fixed" width="250" height="80">
  <button on="tap:amp-web-push.subscribe">Subscribe to Notifications</button>
</amp-web-push-widget>

<!-- An unsubscription widget -->
<amp-web-push-widget visibility="subscribed" layout="fixed" width="250" height="80">
  <button on="tap:amp-web-push.unsubscribe">Unsubscribe from Notifications</button>
</amp-web-push-widget>

ステップ 3:helper-iframe を追加する。 permission-dialog

AMP Web Pushコンポーネントは、サブスクリプションを処理するためのポップアップを作成するので、この機能をイネーブルメントするためには、プロジェクトに以下のヘルパーファイルを追加する必要がある:

ステップ 4:サービスワーカーファイルを作成する

Webサイトのルート・ディレクトリにservice-worker.js ファイルを作成し、以下のスニペットを追加する:

ステップ 5: AMP Web プッシュ HTML 要素を構成する

以下のamp-web-push HTML要素をHTML本文に追加する。service-worker-URL にクエリーパラメーターとしてapiKeybaseUrlを追加する必要があることに留意してほしい。

1
2
3
4
5
6
7
<amp-web-push
layout="nodisplay"
id="amp-web-push"
helper-iframe-url="FILE_PATH_TO_YOUR_HELPER_IFRAME"
permission-dialog-url="FILE_PATH_TO_YOUR_PERMISSION_DIALOG"
service-worker-url="FILE_PATH_TO_YOUR_SERVICE_WORKER?apiKey={YOUR_API_KEY}&baseUrl={YOUR_BASE_URL}"
>

AMDだ:サポートを無効にする

あなたのサイトがRequireJSまたは他のAMDモジュールローダーを使用しているが、このリストの他のオプションのいずれかを使用してBraze Web SDKを読み込むことを好む場合、AMDサポートを含まないバージョンのライブラリを読み込むことができる。このバージョンのライブラリーは、以下のCDNの場所からロードできます:

AMDだ:モジュールローダー

RequireJS または他の AMD モジュールローダーを使用する場合は、ライブラリのコピーをセルフホスティングし、他のリソースと同様に参照することをお勧めします。

1
2
3
4
5
require(['path/to/braze.min.js'], function(braze) {
  braze.initialize('YOUR-API-KEY-HERE', { baseUrl: 'YOUR-SDK-ENDPOINT' });
  braze.automaticallyShowInAppMessages();
  braze.openSession();
});

エレクトロン

Electron は公式には Web プッシュ通知をサポートしていません (参照: この GitHub issue)。Brazeがテストしていないオープンソースの回避策を試すこともできます。

Jestフレームワーク

Jestを使用している場合、SyntaxError: Unexpected token 'export' のようなエラーが表示されることがあります。これを修正するには、Braze SDK を無視するように package.json の設定を調整します。

1
2
3
4
5
"jest": {
  "transformIgnorePatterns": [
    "/node_modules/(?!@braze)"
  ]
}

SSRフレームワーク

Next.js のようなサーバーサイド・レンダリング(SSR)フレームワークを使用している場合、SDKはブラウザ環境で実行されることを意図しているため、エラーが発生する可能性がある。これらの問題は、SDKを動的にインポートすることで解決できます。

必要な SDK の部分を別のファイルにエクスポートし、そのファイルをコンポーネントに動的にインポートすることで、ツリーシェイクの利点を維持できます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// MyComponent/braze-exports.js
// export the parts of the SDK you need here
export { initialize, openSession } from "@braze/web-sdk";

// MyComponent/MyComponent.js
// import the functions you need from the braze exports file
useEffect(() => {
    import("./braze-exports.js").then(({ initialize, openSession }) => {
        initialize("YOUR-API-KEY-HERE", {
            baseUrl: "YOUR-SDK-ENDPOINT",
            enableLogging: true,
        });
        openSession();
    });
}, []);

あるいは、アプリのバンドルにwebpackを使用している場合、そのマジックコメントを利用して、必要なSDKの部分だけを動的にインポートすることもできます。

1
2
3
4
5
6
7
8
9
10
11
12
13
// MyComponent.js
useEffect(() => {
    import(
        /* webpackExports: ["initialize", "openSession"] */
        "@braze/web-sdk"
    ).then(({ initialize, openSession }) => {
        initialize("YOUR-API-KEY-HERE", {
            baseUrl: "YOUR-SDK-ENDPOINT",
            enableLogging: true,
        });
        openSession();
    });
}, []);

Tealium iQ

Tealium iQは、基本的なターンキー Braze 統合を提供します。統合を構成するには、Tealium Tag Management インターフェイスで Braze を検索し、ダッシュボードから Web SDK API キーを指定します。

詳細または Tealium 構成サポートに関する詳細については、統合ドキュメントを確認するか、Tealium アカウントマネージャーにお問い合わせください。

ヴァイト

Viteを使用していて、循環依存関係やUncaught TypeError: Class extends value undefined is not a constructor or null に関する警告が表示される場合は、Braze SDKを依存関係の発見から除外する必要があるかもしれません:

1
2
3
optimizeDeps: {
    exclude: ['@braze/web-sdk']
},

その他のタグ・マネージャー

Brazeは、カスタムHTMLタグの中で当社の統合指示に従うことにより、他のタグ管理ソリューションと互換性を持つこともできます。これらのソリューションの評価についてサポートが必要な場合は、Brazeの担当者にご連絡ください。

Integrating the Cordova SDK

Prerequisites

Before you start, verify your environment is supported by the latest Braze Cordova SDK version.

Step 1: Add the SDK to your project

If you’re on Cordova 6 or later, you can add the SDK directly from GitHub. Alternatively, you can download a ZIP of the GitHub repository and add the SDK manually.

If you don’t plan on using location collection and geofences, use the master branch from GitHub.

1
cordova plugin add https://github.com/braze-inc/braze-cordova-sdk#master

If you plan on using location collection and geofences, use the geofence-branch from GitHub.

1
cordova plugin add https://github.com/braze-inc/braze-cordova-sdk#geofence-branch

Step 2: Configure your project

Next, adding the following preferences to the platform element in your project’s config.xml file.

1
2
<preference name="com.braze.ios_api_key" value="BRAZE_API_KEY" />
<preference name="com.braze.ios_api_endpoint" value="CUSTOM_API_ENDPOINT" />
1
2
<preference name="com.braze.android_api_key" value="BRAZE_API_KEY" />
<preference name="com.braze.android_api_endpoint" value="CUSTOM_API_ENDPOINT" />

Replace the following:

The platform element in your config.xml file should be similar to the following:

1
2
3
4
<platform name="ios">
    <preference name="com.braze.ios_api_key" value="BRAZE_API_KEY" />
    <preference name="com.braze.ios_api_endpoint" value="sdk.fra-01.braze.eu" />
</platform>
1
2
3
4
<platform name="android">
    <preference name="com.braze.android_api_key" value="BRAZE_API_KEY" />
    <preference name="com.braze.android_api_endpoint" value="sdk.fra-01.braze.eu" />
</platform>

Platform-specific syntax

The following section covers the platform-specific syntax when using Cordova with iOS or Android.

Integers

Integer preferences are read as string representations, like in the following example:

1
2
3
4
<platform name="ios">
    <preference name="com.braze.ios_flush_interval_seconds" value="10" />
    <preference name="com.braze.ios_session_timeout" value="5" />
</platform>

Due to how the Cordova 8.0.0+ framework handles preferences, integer-only preferences (such as sender IDs) must be set to strings prepended with str_, like in the following example:

1
2
3
4
<platform name="android">
    <preference name="com.braze.android_fcm_sender_id" value="str_64422926741" />
    <preference name="com.braze.android_default_session_timeout" value="str_10" />
</platform>

Booleans

Boolean preferences are read by the SDK using YES and NO keywords as a string representation, like in the following example:

1
2
3
4
<platform name="ios">
    <preference name="com.braze.should_opt_in_when_push_authorized" value="YES" />
    <preference name="com.braze.ios_disable_automatic_push_handling" value="NO" />
</platform>

Boolean preferences are read by the SDK using true and false keywords as a string representation, like in the following example:

1
2
3
4
<platform name="android">
    <preference name="com.braze.should_opt_in_when_push_authorized" value="true" />
    <preference name="com.braze.is_session_start_based_timeout_enabled" value="false" />
</platform>

Optional configurations

You can add any of the following preferences to the platform element in your project’s config.xml file:

The following is an example config.xml file with additional configurations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<platform name="ios">
    <preference name="com.braze.ios_disable_automatic_push_registration" value="NO"/"YES" />
    <preference name="com.braze.ios_disable_automatic_push_handling" value="NO"/"YES" />
    <preference name="com.braze.ios_enable_idfa_automatic_collection" value="YES"/"NO" />
    <preference name="com.braze.enable_location_collection" value="NO"/"YES" />
    <preference name="com.braze.geofences_enabled" value="NO"/"YES" />
    <preference name="com.braze.ios_session_timeout" value="5" />
    <preference name="com.braze.sdk_authentication_enabled" value="YES"/"NO" />
    <preference name="com.braze.display_foreground_push_notifications" value="YES"/"NO" />
    <preference name="com.braze.ios_disable_un_authorization_option_provisional" value="NO"/"YES" />
    <preference name="com.braze.trigger_action_minimum_time_interval_seconds" value="30" />
    <preference name="com.braze.ios_push_app_group" value="PUSH_APP_GROUP_ID" />
    <preference name="com.braze.ios_forward_universal_links" value="YES"/"NO" />
    <preference name="com.braze.ios_log_level" value="2" />
    <preference name="com.braze.ios_use_uuid_as_device_id" value="YES"/"NO" />
    <preference name="com.braze.ios_flush_interval_seconds" value="10" />
    <preference name="com.braze.ios_use_automatic_request_policy" value="YES"/"NO" />
    <preference name="com.braze.should_opt_in_when_push_authorized" value="YES"/"NO" />
</platform>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<platform name="android">
    <preference name="com.braze.android_small_notification_icon" value="RESOURCE_ENTRY_NAME_FOR_ICON_DRAWABLE" />
    <preference name="com.braze.android_large_notification_icon" value="RESOURCE_ENTRY_NAME_FOR_ICON_DRAWABLE" />
    <preference name="com.braze.android_notification_accent_color" value="str_ACCENT_COLOR_INTEGER" />
    <preference name="com.braze.android_default_session_timeout" value="str_SESSION_TIMEOUT_INTEGER" />
    <preference name="com.braze.android_handle_push_deep_links_automatically" value="true"/"false" />
    <preference name="com.braze.android_log_level" value="str_LOG_LEVEL_INTEGER" />
    <preference name="com.braze.firebase_cloud_messaging_registration_enabled" value="true"/"false" />
    <preference name="com.braze.android_fcm_sender_id" value="str_YOUR_FCM_SENDER_ID" />
    <preference name="com.braze.enable_location_collection" value="true"/"false" />
    <preference name="com.braze.geofences_enabled" value="true"/"false" />
    <preference name="com.braze.android_disable_auto_session_tracking" value="true"/"false" />
    <preference name="com.braze.sdk_authentication_enabled" value="true"/"false" />
    <preference name="com.braze.trigger_action_minimum_time_interval_seconds" value="str_MINIMUM_INTERVAL_INTEGER" />
    <preference name="com.braze.is_session_start_based_timeout_enabled" value="false"/"true" />
    <preference name="com.braze.default_notification_channel_name" value="DEFAULT_NAME" />
    <preference name="com.braze.default_notification_channel_description" value="DEFAULT_DESCRIPTION" />
    <preference name="com.braze.does_push_story_dismiss_on_click" value="true"/"false" />
    <preference name="com.braze.is_fallback_firebase_messaging_service_enabled" value="true"/"false" />
    <preference name="com.braze.fallback_firebase_messaging_service_classpath" value="FALLBACK_FIREBASE_MESSAGING_CLASSPATH" />
    <preference name="com.braze.is_content_cards_unread_visual_indicator_enabled" value="true"/"false" />
    <preference name="com.braze.is_firebase_messaging_service_on_new_token_registration_enabled" value="true"/"false" />
    <preference name="com.braze.is_push_deep_link_back_stack_activity_enabled" value="true"/"false" />
    <preference name="com.braze.push_deep_link_back_stack_activity_class_name" value="DEEPLINK_BACKSTACK_ACTIVITY_CLASS_NAME" />
    <preference name="com.braze.should_opt_in_when_push_authorized" value="true"/"false" />
</platform>

Disabling automatic session tracking (Android only)

By default, the Android Cordova plugin automatically tracks sessions. To disable automatic session tracking, add the following preference to the platform element in your project’s config.xml file:

1
2
3
<platform name="android">
    <preference name="com.braze.android_disable_auto_session_tracking" value="true" />
</platform>

To start tracking sessions again, call BrazePlugin.startSessionTracking(). Keep in mind, only sessions started after the next Activity.onStart() will be tracked.

Flutter Braze SDKについて

Android およびiOS でBraze Flutter SDK を統合すると、Dart で書かれたFlutter アプリ 内でBraze API を使用できるようになります。このプラグインには、基本的な分析機能が用意されており、iOS と Android 両方のアプリ内メッセージとコンテンツカードを1つのコードベースで統合できます。

Flutter SDK の統合

前提条件

Braze Flutter SDK を統合する前に、以下の作業を完了する必要があります。

ステップ1:Braze ライブラリーを統合する

コマンドラインから Braze Flutter SDK パッケージを追加します。これにより、適切な行がpubspec.yaml に追加されます。

1
flutter pub add braze_plugin

ステップ2: 完全なネイティブSDKセットアップ

Braze サーバーに接続するには、プロジェクトの android/res/values フォルダで braze.xml ファイルを作成します。以下のコードを貼り付けて、API 識別子キーとエンドポイントを値で置き換えます。

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="com_braze_api_key">YOUR_APP_IDENTIFIER_API_KEY</string>
<string translatable="false" name="com_braze_custom_endpoint">YOUR_CUSTOM_ENDPOINT_OR_CLUSTER</string>
</resources>

必要な権限をファイル AndroidManifest.xml に追加します。

1
2
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

AppDelegate.swift ファイルの先頭にBraze SDK インポートを追加します。

1
2
import BrazeKit
import braze_plugin

同じファイルで、application(_:didFinishLaunchingWithOptions:) メソッドで Braze 構成オブジェクトを作成し、API キーとエンドポイントをアプリの値に置き換えます。次に、構成を使用して Braze インスタンスを作成し、簡単にアクセスできるよう AppDelegate で静的プロパティを作成します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static var braze: Braze? = nil

func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
) -> 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

  return true
}

AppDelegate.m ファイルの先頭に BrazeKit をインポートします。

1
@import BrazeKit;

同じファイルで、application:didFinishLaunchingWithOptions: メソッドで Braze 構成オブジェクトを作成し、API キーとエンドポイントをアプリの値に置き換えます。次に、構成を使用して Braze インスタンスを作成し、簡単にアクセスできるよう AppDelegate で静的プロパティを作成します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Setup Braze
  BRZConfiguration *configuration =
      [[BRZConfiguration alloc] initWithApiKey:@"<BRAZE_API_KEY>"
                                      endpoint:@"<BRAZE_ENDPOINT>"];
  // - Enable logging or customize configuration here
  configuration.logger.level = BRZLoggerLevelInfo;
  Braze *braze = [BrazePlugin initBraze:configuration];
  AppDelegate.braze = braze;

  [self.window makeKeyAndVisible];
  return YES;
}

#pragma mark - AppDelegate.braze

static Braze *_braze = nil;

+ (Braze *)braze {
  return _braze;
}

+ (void)setBraze:(Braze *)braze {
  _braze = braze;
}

ステップ 3:プラグインのセットアップ

Dart コードにプラグインをインポートするには、以下を使用します。

1
import 'package:braze_plugin/braze_plugin.dart';

次に、サンプルアプリのように new BrazePlugin() を呼び出して、Braze プラグインのインスタンスを初期化します。

統合のテスト

SDK が統合されていることを確認するには、ダッシュボードでセッション統計を確認します。いずれかのプラットフォームでアプリケーションを実行すると、ダッシュボード ([概要] セクション) に新しいセッションが表示されます。

アプリで次のコードを呼び出して、特定のユーザーのセッションを開きます。

1
2
BrazePlugin braze = BrazePlugin();
braze.changeUser("{some-user-id}");

Audience> Search Usersのダッシュボードで{some-user-id}のユーザーを検索します。そこで、セッションとデバイスデータがロギングされていることを確認できます。

React Native Braze SDKについて

React Native Braze SDKを統合することで、基本的な分析機能を提供し、1つのコードベースだけでiOSとAndroidの両方のアプリ内メッセージとコンテンツカードを統合できる。

新アーキテクチャーの互換性

以下の最小SDKバージョンは、React Nativeの新アーキテクチャを使用するすべてのアプリと互換性がある:

SDKバージョン6.0.0から、BrazeはReact Native Turbo Moduleを使用しており、New Architectureとレガシーブリッジアーキテクチャの両方に対応している。

React Native SDKを統合する

前提条件

SDKを統合するには、React Nativeバージョン0.71以降が必要である。サポートされているバージョンの完全なリストについては、 React Native SDK GitHub リポジトリを参照してください。

ステップ1:Braze ライブラリーを統合する

1
npm install @braze/react-native-sdk
1
yarn add @braze/react-native-sdk

ステップ2:セットアップオプションを選択する

Braze SDKは、Braze Expoプラグインまたはネイティブレイヤーのいずれかを使用して管理できる。Expoプラグインを使えば、ネイティブレイヤーにコードを書くことなく、特定のSDK機能を設定できる。アプリのニーズに最も適したオプションを選択しよう。

ステップ 2.1:Braze Expo プラグインのインストール

Braze React Native SDK のバージョンが1.37.0以降であることを確認してください。サポートされているバージョンの全リストは、Braze React Nativeリポジトリをチェックしてほしい。

Braze Expoプラグインをインストールするには、以下のコマンドを実行する:

1
expo install @braze/expo-plugin

ステップ 2.2:app.json にプラグインを追加する

app.json で、Braze Expo プラグインを追加します。次の構成オプションを指定できます。

構成例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
  "expo": {
    "plugins": [
      [
        "@braze/expo-plugin",
        {
          "androidApiKey": "YOUR-ANDROID-API-KEY",
          "iosApiKey": "YOUR-IOS-API-KEY",
          "baseUrl": "YOUR-SDK-ENDPOINT",
          "sessionTimeout": 60,
          "enableGeofence": false,
          "enableBrazeIosPush": false,
          "enableFirebaseCloudMessaging": false,
          "firebaseCloudMessagingSenderId": "YOUR-FCM-SENDER-ID",
          "androidHandlePushDeepLinksAutomatically": true,
          "enableSdkAuthentication": false,
          "logLevel": 0,
          "minimumTriggerIntervalInSeconds": 0,
          "enableAutomaticLocationCollection": false,
          "enableAutomaticGeofenceRequests": false,
          "dismissModalOnOutsideTap": true,
          "androidPushNotificationHtmlRenderingEnabled": true,
          "androidNotificationAccentColor": "#ff3344",
          "androidNotificationLargeIcon": "@drawable/custom_app_large_icon",
          "androidNotificationSmallIcon": "@drawable/custom_app_small_icon",
          "iosRequestPushPermissionsAutomatically": false,
          "enableBrazeIosPushStories": true,
          "iosPushStoryAppGroup": "group.com.example.myapp.PushStories"
        }
      ],
    ]
  }
}

ステップ 2.3:アプリケーションのビルドおよび実行

アプリケーションを事前にビルドすることで、Braze Expoプラグインが動作するために必要なネイティブファイルが生成される。

1
expo prebuild

Expo ドキュメントの指定に従い、アプリケーションを実行します。コンフィギュレーション・オプションに変更を加えると、アプリケーションのプリビルドと再実行が必要になることを覚えておいてほしい。

ステップ 2.1:リポジトリの追加

最上位プロジェクト build.gradle で、buildscript > dependencies から以下を追加します。

1
2
3
4
5
6
7
buildscript {
    dependencies {
        ...
        // Choose your Kotlin version
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10")
    }
}

これにより、Kotlin がプロジェクトに追加されます。

ステップ2.2: Braze SDK の構成

Braze サーバーに接続するには、プロジェクトの res/values フォルダで braze.xml ファイルを作成します。次のコードを貼り付け、API キーおよびエンドポイントを実際の値に置き換えます。

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="com_braze_api_key">YOU_APP_IDENTIFIER_API_KEY</string>
<string translatable="false" name="com_braze_custom_endpoint">YOUR_CUSTOM_ENDPOINT_OR_CLUSTER</string>
</resources>

必要な権限をファイル AndroidManifest.xml に追加します。

1
2
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

ステップ2.3: ユーザーセッショントラッキングの実装

openSession() および closeSession() への呼び出しは自動的に処理されます。 MainApplication クラスの onCreate() メソッドに次のコードを追加します。

1
2
3
4
5
6
7
8
import com.braze.BrazeActivityLifecycleCallbackListener;

@Override
public void onCreate() {
    super.onCreate();
    ...
    registerActivityLifecycleCallbacks(new BrazeActivityLifecycleCallbackListener());
}
1
2
3
4
5
6
7
import com.braze.BrazeActivityLifecycleCallbackListener

override fun onCreate() {
    super.onCreate()
    ...
    registerActivityLifecycleCallbacks(BrazeActivityLifecycleCallbackListener())
}

ステップ2.4: インテント更新の処理

MainActivity で android:launchModesingleTask に設定されている場合は、次のコードを MainActivity クラスに追加します。

1
2
3
4
5
@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}
1
2
3
4
override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    setIntent(intent)
}

ステップ 2.1:(オプション) ダイナミック XCFramework に関する Podfile の構成

BrazeUI などの特定の Braze ライブラリーを Objective-C++ ファイルにインポートするには、#import 構文を使用する必要があります。Braze Swift SDKのバージョン7.4.0以降、バイナリにはこの構文と互換性のあるダイナミック XCFramework としてのオプションの配布チャネルがあります。

この配布チャネルを使用する場合は、Podfile で CocoaPods のソースの場所を手動で上書きします。以下のサンプルを参照し、インポートする関連バージョンで {your-version} を置き換えてください。

1
2
3
pod 'BrazeKit', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeKit.podspec'
pod 'BrazeUI', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeUI.podspec'
pod 'BrazeLocation', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeLocation.podspec'

ステップ 2.2:ポッドのインストール

React Native ではライブラリーがネイティブプラットフォームに自動でリンクされるため、CocoaPods を使用して SDK をインストールできます。

プロジェクトのルートフォルダから:

1
2
3
4
5
# To install using the React Native New Architecture
cd ios && RCT_NEW_ARCH_ENABLED=1 pod install

# To install using the React Native legacy architecture
cd ios && pod install

ステップ 2.3:Braze SDK の構成

AppDelegate.swift ファイルの先頭にある Braze SDK をインポートします。

1
import BrazeKit

application(_:didFinishLaunchingWithOptions:) メソッドで、API キーおよびエンドポイントをアプリの値に置き換えます。次に、構成を使用して Braze インスタンスを作成し、簡単にアクセスできるよう AppDelegate で静的プロパティを作成します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
) -> Bool {
    // Setup Braze
    let configuration = Braze.Configuration(
        apiKey: "{BRAZE_API_KEY}",
        endpoint: "{BRAZE_ENDPOINT}")
    // Enable logging and customize the configuration here.
    configuration.logger.level = .info
    let braze = BrazeReactBridge.perform(
      #selector(BrazeReactBridge.initBraze(_:)),
      with: configuration
    ).takeUnretainedValue() as! Braze

    AppDelegate.braze = braze

    /* Other configuration */

    return true
}

// MARK: - AppDelegate.braze

static var braze: Braze? = nil

AppDelegate.m ファイルの先頭にある Braze SDK をインポートします。

1
2
#import <BrazeKit/BrazeKit-Swift.h>
#import "BrazeReactBridge.h"

application:didFinishLaunchingWithOptions: メソッドで、API キーおよびエンドポイントをアプリの値に置き換えます。次に、構成を使用して Braze インスタンスを作成し、簡単にアクセスできるよう AppDelegate で静的プロパティを作成します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // 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;

  /* Other configuration */

  return YES;
}

#pragma mark - AppDelegate.braze

static Braze *_braze = nil;

+ (Braze *)braze {
  return _braze;
}

+ (void)setBraze:(Braze *)braze {
  _braze = braze;
}

ステップ 3:ライブラリーをインポートする

次に、React Nativeのコードでライブラリをimport 。詳しくはサンプル・プロジェクトをご覧いただきたい。

1
import Braze from "@braze/react-native-sdk";

ステップ4:統合をテストする(オプション)

SDKの統合をテストするには、アプリで以下のコードを呼び出して、どちらのプラットフォームでもユーザーの新しいセッションを開始する。

1
Braze.changeUser("userId");

たとえば、アプリの起動時にユーザー ID を割り当てることができます。

1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { useEffect } from "react";
import Braze from "@braze/react-native-sdk";

const App = () => {
  useEffect(() => {
    Braze.changeUser("some-user-id");
  }, []);

  return (
    <div>
      ...
    </div>
  )

Brazeのダッシュボードで、ユーザー検索に行き、some-user-id に一致するIDを持つユーザーを探す。ここで、セッションデータとデバイスデータが記録されたことを確認できる。

六SDKの統合

ステップ1:ファイルの追加

Braze SDK ファイルは、Braze Roku SDK リポジトリsdk_files ディレクトリにあります。

  1. source ディレクトリで、アプリに BrazeSDK.brs を追加します。
  2. components ディレクトリで、アプリに BrazeTask.brsBrazeTask.xml を追加します。

ステップ 2:参照の追加

次の script 要素を使用して、メインシーンに BrazeSDK.brs への参照を追加します。

1
<script type="text/brightscript" uri="pkg:/source/BrazeSDK.brs"/>

ステップ3:構成

main.brs 内で、グローバルノードにBrazeのコンフィギュレーションを設定する:

1
2
3
4
5
6
7
8
globalNode = screen.getGlobalNode()
config = {}
config_fields = BrazeConstants().BRAZE_CONFIG_FIELDS
config[config_fields.API_KEY] = {YOUR_API_KEY}
' example endpoint: "https://sdk.iad-01.braze.com/"
config[config_fields.ENDPOINT] = {YOUR_ENDPOINT}
config[config_fields.HEARTBEAT_FREQ_IN_SECONDS] = 5
globalNode.addFields({brazeConfig: config})

SDK エンドポイントと API キーは、Braze ダッシュボード内にあります。

ステップ4: Braze の初期化

Braze インスタンスを初期化します。

1
2
m.BrazeTask = createObject("roSGNode", "BrazeTask")
m.Braze = getBrazeInstance(m.BrazeTask)

オプション構成

ロギング

Braze 統合をデバッグするため、Braze ログの Roku デバッグコンソールを表示できます。詳細については、Roku Developers の Debugging code を参照してください。

Unity Braze SDKについて

型、関数、変数などの完全なリストについては、Unity宣言ファイルを参照してください。また、すでにiOS 用にUnity を手動で統合している場合は、代わりに 自動統合 に切り替えることができます。

Unity SDKの統合

前提条件

開始する前に、環境が最新のBraze Unity SDKバージョンでサポートされていることを確認します。

ステップ1:Braze Unity パッケージの選択

Braze .unitypackage は、Android プラットフォームと iOS プラットフォーム向けのネイティブバインディングを C# インターフェイスとともにバンドルします。

Braze Unity リリースページでいくつかの Braze Unity パッケージをダウンロードできます。

  • Appboy.unitypackage
    • このパッケージは、Braze Android および iOS SDK と、iOS SDK の SDWebImage 依存関係をバンドルします。これは、Braze アプリ内メッセージングと、iOS 上のコンテンツカード機能を適切に機能させるために必要です。SDWebImage フレームワークは、GIF を含む画像のダウンロードと表示に使用されます。完全なBraze機能を使用する場合は、このパッケージを読み込むしてインポートします。
  • Appboy-nodeps.unitypackage
    • このパッケージは Appboy.unitypackage に似ていますが、SDWebImage フレームワークが存在しない点が異なります。このパッケージは、iOS アプリに SDWebImage フレームワークが存在しないようにする場合に便利です。

Braze .unitypackage は、Android プラットフォームと iOS プラットフォーム向けのネイティブバインディングを C# インターフェイスとともにバンドルします。

Braze Unity パッケージは、次の2種類の統合オプションを使用して、Braze Unity リリースページでダウンロードできます。

  1. Appboy.unitypackage のみ
    • このパッケージは、Braze Android と iOS SDK を追加の依存関係なしでバンドルします。この統合方法では、Braze アプリ内メッセージングと、iOS 上のコンテンツカード機能が適切に機能しません。カスタムコードなしで完全なBraze機能を使用する場合は、代わりに以下のオプションを使用してください。
    • この統合オプションを使用する場合は、[Braze 構成] の下にある Unity UI で Import SDWebImage dependency の横にあるボックスにチェックマークが入れられていないことを確認してください。
  2. SDWebImage を含む Appboy.unitypackage
    • この統合オプションは、Braze Android および iOS SDK と、iOS SDK の SDWebImage 依存関係をバンドルします。これは、Braze アプリ内メッセージングと、iOS 上のコンテンツカード機能を適切に機能させるために必要です。SDWebImage フレームワークは、GIF を含む画像のダウンロードと表示に使用されます。完全なBraze機能を使用する場合は、このパッケージを読み込むしてインポートします。
    • SDWebImage を自動的にインポートするには、[Braze 構成] の下にある Unity UIで Import SDWebImage dependency の横にあるボックスにチェックマークが入れられていることを確認してください。

ステップ2: パッケージをインポートする

Unity エディターで Unity プロジェクトにパッケージをインポートするには、[アセット] > [パッケージをインポート] > [カスタムパッケージ] の順に移動します。次に、Importをクリックします。

または、カスタム Unity パッケージのインポートに関して詳しくは、Unity アセットパッケージのインポートの説明を参照してください。

Unity エディターで Unity プロジェクトにパッケージをインポートするには、[アセット] > [パッケージをインポート] > [カスタムパッケージ] の順に移動します。次に、Importをクリックします。

または、カスタム Unity パッケージのインポートに関して詳しくは、Unity アセットパッケージのインポートの説明を参照してください。

ステップ 3:SDK の設定

ステップ 3.1:設定 AndroidManifest.xml

fullo AndroidManifest.xml を実行します。アプリにAndroidManifest.xml がない場合は、以下をテンプレートとして使用できます。それ以外の場合、すでにAndroidManifest.xml がある場合は、次のいずれかの欠落セクションが既存のAndroidManifest.xml に追加されていることを確認します。

  1. Assets/Plugins/Android/ ディレクトリに移動し、AndroidManifest.xml ファイルを開きます。これは、Unityエディタの[デフォルトの場所です。
  2. AndroidManifest.xml で、必要な権限とアクティビティを次のテンプレートに追加します。
  3. 終了すると、AndroidManifest.xml には、"android.intent.category.LAUNCHER" が存在する単一のアクティビティのみが含まれます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="REPLACE_WITH_YOUR_PACKAGE_NAME">

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.INTERNET" />

  <application android:icon="@drawable/app_icon" 
               android:label="@string/app_name">

    <!-- Calls the necessary Braze methods to ensure that analytics are collected and that push notifications are properly forwarded to the Unity application. -->
    <activity android:name="com.braze.unity.BrazeUnityPlayerActivity" 
      android:theme="@style/UnityThemeSelector"
      android:label="@string/app_name" 
      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" 
      android:screenOrientation="sensor">
      <meta-data android:name="android.app.lib_name" android:value="unity" />
      <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>

    <!-- A Braze specific FirebaseMessagingService used to handle push notifications. -->
    <service android:name="com.braze.push.BrazeFirebaseMessagingService"
      android:exported="false">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
  </application>
</manifest>

ステップ 3.2:AndroidManifest.xml をパッケージ名で更新します

パッケージ名を確認するには、[ファイル] > [ビルド設定] > [プレーヤー設定] > [Android タブ]を選択します。

AndroidManifest.xml では、REPLACE_WITH_YOUR_PACKAGE_NAME のすべてのインスタンスを前のステップの Package Name に置き換える必要があります。

ステップ3.3:グレードル依存関係の追加

Unity プロジェクトに gradle の依存関係を追加するには、まず公開設定で [Custom Main Gradle テンプレート] を有効にします。これにより、プロジェクトで使用するテンプレートグラドルファイルが作成されます。gradle ファイルは、依存関係の設定やその他のビルド時のプロジェクト設定を処理します。詳細については、Braze Unity サンプルアプリのmainTemplate.gradle を参照してください。

次の依存関係が必要です。

1
2
3
4
5
6
implementation 'com.google.firebase:firebase-messaging:22.0.0'
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
implementation "androidx.recyclerview:recyclerview:1.2.1"
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.6.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"
implementation 'androidx.core:core:1.6.0'

これらの依存関係は、External Dependency Managerを使用して設定することもできます。

ステップ 3.4:Unity Android 統合の自動化

Braze は、Unity Android 統合を自動化するためのネイティブ Unity ソリューションを提供しています。

  1. Unity エディターで [Braze] > [Braze 構成] の順に移動して、[Braze 構成設定] を開きます。
  2. [Unity Android 統合の自動化] ボックスにチェックマークを入れます。
  3. Braze API キーフィールドで、設定の管理にあるアプリアプリケーションのAPI キーをBraze ダッシュボードから入力します。

ステップ 3.1:API キーの設定

Braze は、Unity iOS 統合を自動化するためのネイティブ Unity ソリューションを提供しています。このソリューションは、Unity の PostProcessBuildAttribute を使用してビルドされた Xcode プロジェクトを変更し、IMPL_APP_CONTROLLER_SUBCLASS マクロを使用して UnityAppController をサブクラス化します。

  1. Unity エディターで [Braze] > [Braze 構成] の順に移動して、[Braze 構成設定] を開きます。
  2. [Unity iOS 統合の自動化] ボックスにチェックマークを入れます。
  3. Braze API キー フィールドで、設定の管理 にあるアプリアプリケーションのAPI キーを入力します。

アプリですでに別の UnityAppController サブクラスが使用されている場合、サブクラスの実装を AppboyAppDelegate.mm とマージする必要があります。

Unityパッケージをカスタマイズする

ステップ1:リポジトリのクローン作成

ターミナルで、Braze Unity SDK GitHub リポジトリ のクローンを作成し、そのフォルダに移動します。

1
2
git clone [email protected]:braze-inc/braze-unity-sdk.git
cd ~/PATH/TO/DIRECTORY/braze-unity-sdk
1
2
git clone git@github.com:braze-inc/braze-unity-sdk.git
cd C:\PATH\TO\DIRECTORY\braze-unity-sdk

ステップ2: リポジトリからのパッケージのエクスポート

まず、Unityを起動し、バックグラウンドで実行し続けます。次に、リポジトリルートで次のコマンドを実行してパッケージをbraze-unity-sdk/unity-package/ にエクスポートします。

1
/Applications/Unity/Unity.app/Contents/MacOS/Unity -batchmode -nographics -projectPath "$(pwd)" -executeMethod Appboy.Editor.Build.ExportAllPackages -quit
1
"%UNITY_PATH%" -batchmode -nographics -projectPath "%PROJECT_ROOT%" -executeMethod Appboy.Editor.Build.ExportAllPackages -quit	

ステップ 3:Unityへのパッケージのインポート

  1. Unity で、Assets> Import Package> Custom Package に移動して、目的のパッケージをUnity プロジェクトにインポートします。
  2. インポートしたくないファイルがある場合は、ここで選択を解除します。
  3. Assets/Editor/Build.csにあるエクスポートされたUnityパッケージをカスタマイズします。

自動統合への切り替え(Swift のみ)

Braze Unity SDKで提供される自動化されたiOSインテグレーションを利用するには、手動から自動化されたインテグレーションに移行するための以下のステップに従う。

  1. XcodeプロジェクトのUnityAppController サブクラスから、Braze関連のコードをすべて削除する。
  2. UnityまたはXcodeプロジェクトからBraze iOSライブラリを削除します(Appboy_iOS_SDK.frameworkSDWebImage.frameworkなど)。
  3. Braze Unity パッケージをプロジェクトに再度インポートします。フルウォークスルーについては、ステップ2 を参照してください。パッケージ をインポートします。
  4. API キーを再設定します。フルウォークスルーについては、ステップ3.1を参照してください。APIキーを設定します。

オプション構成

詳細なログ記録

Unityエディターで冗長ロギングを有効にするには、以下のようにする:

  1. [Braze] > [Braze 構成] の順に移動して、[Braze 構成設定] を開きます。
  2. [Braze Android 設定を表示する] ドロップダウンをクリックします。
  3. [SDK ログレベル] フィールドに値「0」を入力します。

Prime 31 の互換性

Prime31 プラグインで Braze Unity プラグインを使用するには、Prime31 互換の Activity クラスを使用するようにプロジェクトの AndroidManifest.xml を編集します。の参照をすべて変更する。 com.braze.unity.BrazeUnityPlayerActivity から com.braze.unity.prime31compatible.BrazeUnityPlayerActivity

Amazon Device Messaging (ADM)

ブレーズは、ADMプッシュをUnityアプリに統合することをサポートしています。ADM プッシュを統合する場合は、ADM API キーを含むapi_key.txt というファイルを作成し、Plugins/Android/assets/ フォルダに配置します。 ADM とブレーズの統合の詳細については、ADM プッシュ統合命令 を参照してください。

Braze Unity プレーヤーの拡張(Android のみ)

提供されている AndroidManifest.xml ファイルの例では、1つの Activity クラス BrazeUnityPlayerActivity が登録されています。このクラスは Braze SDK と統合され、セッション処理、アプリ内メッセージ登録、プッシュ通知分析ログなどを使用して UnityPlayerActivity を拡張します。UnityPlayerActivity クラスの拡張の詳細については、「Unity」を参照してください。

ライブラリやプラグインプロジェクトで独自のカスタムUnityPlayerActivity を作成する場合は、カスタム機能をBrazeと統合するために、当社のBrazeUnityPlayerActivity を拡張する必要がある。BrazeUnityPlayerActivity を拡張する作業を始める前に、Unity プロジェクトに Braze を統合するための手順に従ってください。

  1. Braze Android SDK統合の説明に従って、Braze Android SDK をライブラリまたはプラグインプロジェクトに依存関係として追加します。
  2. Unity 固有の機能を含む Unity .aar を、Unity 用に構築している Android ライブラリプロジェクトに統合します。appboy-unity.aar は、公開リポジトリから入手できます。Unity ライブラリがうまく統合されたら、BrazeUnityPlayerActivity を拡張するように UnityPlayerActivity を変更します。
  3. ライブラリまたはプラグインプロジェクトをエクスポートし、通常どおり /<your-project>/Assets/Plugins/Android にドロップします。ライブラリやプラグインにBrazeのソースコードを含めないこと。それらはすでに/<your-project>/Assets/Plugins/Android に存在するからである。
  4. /<your-project>/Assets/Plugins/Android/AndroidManifest.xml を編集し、BrazeUnityPlayerActivity のサブクラスをメイン・アクティビティとして指定する。

これでUnity IDEから、Brazeと完全に統合され、カスタムUnityPlayerActivity 機能を含む.apk をパッケージできるようになるはずだ。

トラブルシューティング

エラー:”ファイルを読み込むことができませんでした。

以下のようなエラーは無視して問題ありません。アップルのソフトウェアはCgBIと呼ばれる独自のPNG拡張子を使用しているが、Unityはこれを認識しない。これらのエラーは、iOSのビルドやBrazeバンドルの関連画像の適切な表示には影響しない。

1
Could not create texture from Assets/Plugins/iOS/AppboyKit/Appboy.bundle/...png: File could not be read

Unreal Engine Braze SDKについて

Braze Unreal SDKプラグインを使用すると、次のことができる:

  • アプリやゲーム内のセッションを測定、追跡する
  • アプリ内購入とカスタムイベントを追跡する
  • 標準およびカスタム属性でユーザープロファイルを更新する
  • プッシュ通知を送信する
  • Unreal アプリを大規模なキャンバスジャーニーと統合する
  • アプリ内の行動に基づいて、EメールやSMSなどのクロスチャネルメッセージを送信する。

Unreal Engine SDK の開発

ステップ1:Brazeプラグインを追加する

ターミナルで、Unreal Engine Braze SDK GitHubリポジトリを複製する。

1
git clone [email protected]:braze-inc/braze-unreal-sdk.git

次に、BrazeSample/Plugins/Braze ディレクトリをコピーし、アプリのPluginフォルダに追加する。

ステップ2: プラグインをイネーブルメントにする

C++またはBlueprintプロジェクトのプラグインをイネーブルメントする。

C++プロジェクトの場合は、Brazeモジュールを参照するようにモジュールを設定する。\*.Build.cs file"Braze"PublicDependencyModuleNames に追加する。

1
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Braze" });

Blueprintプロジェクトでは、設定プラグインと進み、Brazeの横にある「イネーブルメント」にチェックを入れる。

EnablePlugin

ステップ 3:APIキーとエンドポイントを設定する。

プロジェクトのDefaultEngine.ini にAPIキーとエンドポイントを設定する。

1
2
3
4
5
[/Script/Braze.BrazeConfig]
bAutoInitialize=True ; true by default, initialize when the project starts
AndroidApiKey= ; your API key
IOSApiKey= ; your API key
CustomEndpoint= ; your endpoint

オプション構成

ロギング

C++またはブループリント・ノードを使って、実行時にログ・レベルを設定することができる。

実行時にログレベルを設定するには、UBrazeSubsystem::AndroidSetLogLevel を呼ぶ。

1
2
3
UBrazeSubsystem* const BrazeSubsystem = GEngine->GetEngineSubsystem<UBrazeSubsystem>();
BrazeSubsystem->AndroidSetLogLevel(EBrazeLogLevel::Verbose);
UBraze* const BrazeInstance = BrazeSubsystem->InitializeBraze();

ブループリントでは、Android Set Log Levelノードを使用できる:

ブループリントのAndroid Set Log Levelノード

Braze SDK Initializeが呼び出されたときにロギングが確実に設定されるように、InitializeBraze の前にこれを呼び出すことを推奨する。

info.plist でログレベルをイネーブルメントにするには、設定>プロジェクト設定に進み、プラットフォームで iOSを選択する。Extra PList Data」で「Additional Plist Data」を探し、ログレベルを入力する:

1
2
3
4
5
<key>Appboy</key>
<dict>
  <key>LogLevel</key>
  <string>0</string>
</dict>

デフォルトのログレベルは8で、これは最小限のロギングである。ログレベルについてもっと読む:その他のSDKカスタマイズ

Integrating the Xamarin SDK

Integrating the Braze Xamarin SDK will provide you with basic analytics functionality as well as working in-app messages with which you can engage your users.

Prerequisites

Before you can integrate the Xamarin Braze SDK, be sure you meet the following requirements:

  • Starting in version 3.0.0, this SDK requires using .NET 6+ and removes support for projects using the Xamarin framework.
  • Starting in version 4.0.0, this SDK dropped support for Xamarin & Xamarin.Forms and added support for .NET MAUI. See Microsoft’s policy around the end of support for Xamarin.

Step 1: Get the Xamarin binding

A Xamarin binding is a way to use native libraries in Xamarin apps. The implementation of a binding consists of building a C# interface to the library, and then using that interface in your application. See the Xamarin documentation. There are two ways to include the Braze SDK binding: using NuGet or compiling from source.

The simplest integration method involves getting the Braze SDK from the NuGet.org central repository. In the Visual Studio sidebar, right click Packages folder and click Add Packages.... Search for ‘Braze’ and install the BrazePlatform.BrazeAndroidBinding package into your project.

The second integration method is to include the binding source. Under appboy-component/src/androidnet6 you will find our binding source code; adding a project reference to the BrazeAndroidBinding.csproj in your Xamarin application will cause the binding to be built with your project and provide you access to the Braze Android SDK.

A Xamarin binding is a way to use native libraries in Xamarin apps. The implementation of a binding consists of building a C# interface to the library and then using that interface in your application. There are two ways to include the Braze SDK binding: using NuGet or compiling from source.

The simplest integration method involves getting the Braze SDK from the NuGet.org central repository. In the Visual Studio sidebar, right-click Packages folder and click Add Packages.... Search for ‘Braze’ and install the latest Xamarin iOS NuGet packages: Braze.iOS.BrazeKit, Braze.iOS.BrazeUI, and Braze.iOS.BrazeLocation into your project.

We also provide the compatibility libraries packages: Braze.iOS.BrazeKitCompat and Braze.iOS.BrazeUICompat, to help make your migration to .NET MAUI easier.

The second integration method is to include the binding source. Under appboy-component/src/iosnet6 you will find our binding source code; adding a project reference to the BrazeiOSBinding.csproj in your Xamarin application will cause the binding to be built with your project and provide you access to the Braze iOS SDK. Make sure BrazeiOSBinding.csproj is showing in your project’s “Reference” folder.

Step 2: Configure your Braze instance

Step 2.1: Configure the Braze SDK in Braze.xml

Now that the libraries have been integrated, you have to create an Braze.xml file in your project’s Resources/values folder. The contents of that file should resemble the following code snippet:

1
2
3
4
5
6
7
8
9
  <?xml version="1.0" encoding="utf-8"?>
  <resources>
    <string translatable="false" name="com_braze_api_key">YOUR_API_KEY</string>
    <string translatable="false" name="com_braze_custom_endpoint">YOUR_CUSTOM_ENDPOINT_OR_CLUSTER</string>
    <string-array name="com_braze_internal_sdk_metadata">
      <item>XAMARIN</item>
      <item>NUGET</item>
    </string-array>
  </resources>

If you are including the binding source manually, remove <item>NUGET</item> from your code.

Step 2.2: Add required permissions to Android manifest

Now that you’ve added your API key, you need to add the following permissions to your AndroidManifest.xml file:

1
<uses-permission android:name="android.permission.INTERNET" />

For an example of your AndroidManifest.xml, see the Android MAUI sample application.

Step 2.3: Track user sessions and registering for in-app messages

To enable user session tracking and register your app for in-app messages, add the following call to the OnCreate() lifecycle method of the Application class in your app:

1
RegisterActivityLifecycleCallbacks(new BrazeActivityLifecycleCallbackListener());

When setting up your Braze instance, add the following snippet to configure your instance:

1
2
3
var configuration = new BRZConfiguration("YOUR_API_KEY", "YOUR_ENDPOINT");
configuration.Api.AddSDKMetadata(new[] { BRZSDKMetadata.Xamarin });
braze = new Braze(configuration);

See the App.xaml.cs file in the iOS MAUI sample application.

Step 3: Test the integration

Now you can launch your application and see sessions being logged to the Braze dashboard (along with device information and other analytics). For a more in-depth discussion of best practices for the basic SDK integration, consult the Android integration instructions.

Now you can launch your application and see sessions being logged to the Braze dashboard. For a more in-depth discussion of best practices for the basic SDK integration, consult the iOS integration instructions.

「このページはどの程度役に立ちましたか?」
New Stuff!