iOS SDK+ 統合ガイド
このページでは、Rokt Ecommerce iOS SDK+の実装方法について説明します。SDK+は、設定された画面でユーザーとトランザクションデータをRoktに渡し、Roktが確認画面でのオファーなどの関連するエクスペリエンスを表示できるようにします。
1. Add the Rokt SDK+ to Your iOS App#
Rokt SDK+は、最低でもiOS 15.0のデプロイメントターゲットが必要です。プロジェクトで既に使用しているSwift Package ManagerまたはCocoaPodsを使用してください。
1Add the Rokt SDK+ to your iOS app#
Xcodeで、File → Add Package Dependenciesを選択し、https://github.com/ROKT/rokt-sdk-plus-ios.gitを入力し、依存関係ルールをUp to Next Major Versionに設定し、**RoktSDKPlus**製品をアプリターゲットに追加します。または、Package.swiftで固定します:
| Package | Repository URL | Product |
|---|---|---|
| Rokt SDK+ for iOS | https://github.com/ROKT/rokt-sdk-plus-ios.git | RoktSDKPlus |
dependencies: [
.package(url: "https://github.com/ROKT/rokt-sdk-plus-ios.git", from: "9.2.0"),
]
PodfileにRokt SDK+ポッドを追加します:
pod 'RoktSDKPlus', '~> 9.2'
2. Initialize the Rokt SDK+#
AppDelegateファイルに次の初期化スニペットを挿入します。your-keyとyour-secretをRoktチームから提供されたキーとシークレットに置き換えてください。
import mParticle_Apple_SDK
import RoktPaymentExtension
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Initialize the SDK+
let options = MParticleOptions(key: "your-key",
secret: "your-secret")
// Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
options.environment = .development
// Enter your custom subdomain if you are using a first-party domain configuration (optional)
let networkOptions = MPNetworkOptions()
networkOptions.customBaseURL = URL(string: "https://rkt.example.com")
options.networkOptions = networkOptions
// Identify the current user:
let identifyRequest = MPIdentityApiRequest.withEmptyUser()
// If you're using an un-hashed email address, set it in 'email'.
identifyRequest.email = "j.smith@example.com"
// If you're using a hashed email address, set it in 'other' instead of email
identifyRequest.setIdentity("sha256 hashed email goes here", identityType: .other)
// Customer phone number in E.164 format.
identifyRequest.setIdentity("+13125551515", identityType: .phoneNumber)
// If you can only provide a SHA-256-hashed mobile number, set it in 'other4' instead of 'phoneNumber' — do not pass both.
identifyRequest.setIdentity("sha256 hashed mobile goes here", identityType: .other2)
// If the user is identified with their email address, set additional user attributes.
options.identifyRequest = identifyRequest
options.onIdentifyComplete = {(result: MPIdentityApiResult?, error: Error?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
}
}
MParticle.sharedInstance().start(with: options)
// Register after mParticle.start(), before selectShoppableAds
if let paymentExt = RoktPaymentExtension(
applePayMerchantId: "merchant.com.yourapp.rokt", // omit if not offering Apple Pay
urlScheme: "myapp" // omit if not offering Afterpay / Clearpay
) {
MParticle.sharedInstance().rokt.registerPaymentExtension(paymentExt)
}
return true
}
mParticle Rokt kit設定(mParticleダッシュボード)でstripePublishableKeyを設定します。このキットは登録時にstripeKeyとしてRoktに転送します—コード内で渡す必要はありません。アプリ内では、Apple PayのマーチャントIDおよび/またはurlSchemeをRoktPaymentExtension作成時に提供します。applePayMerchantIdまたはurlSchemeの少なくとも一つを提供する必要があります。両方が省略されると、初期化子はnilを返します。
AppDelegateに初期化スニペットを挿入すると、次のカスタマイズ可能なフィールドが表示されます:
1Entering your Rokt key and secret#
keyとsecretをRoktアカウントマネージャーから提供された値に設定します。
2Setting your data environment#
environmentをテスト中は.development(Swift)またはMPEnvironmentDevelopment(Objective-C)に設定してデータを開発環境にルーティングし、実際の顧客活動をProductionに送信するには.productionまたはMPEnvironmentProductionに設定します。
3Entering a custom first-party domain#
First-Party Domain Configurationの指示に従い、customBaseURLをMPNetworkOptionsに設定してカスタムサブドメインを使用します。Rokt SDK+を独自のドメイン経由でルーティングすることで、広告ブロッカーやブラウザが広告やデータをブロックするリスクを減らします。options.networkOptionsを省略すると、Roktのデフォルトエンドポイントにトラフィックを送信します。
4Identifying your user and setting attributes#
identifyRequestで、ユーザーの生のハッシュされていないメールをemailプロパティに渡します。ハッシュされたメールやその他の識別子については、Supported User Identifiersを参照してください。識別が完了したら、onIdentifyCompleteコールバックを使用して追加のユーザー属性を設定します—推奨リストについてはUser Attributesを参照してください。
options.onIdentifyComplete = {(result: MPIdentityApiResult?, error: Error?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
}
}
初期化スニペットには必ずidentifyRequestを含めてください。初期化時にユーザーのメールアドレスがない場合は、割り当てを省略しても構いません。SDK+は初期化され、後で3. ユーザーの識別を通じてユーザーを識別できます。エラーハンドリングを参照して、error引数を検査する方法を確認してください。エラーハンドリングがないと、大規模なデータ整合性の問題が発生する可能性があります。
5Registering the payment extension#
RoktPaymentExtensionをMParticle.sharedInstance().start()の後、selectShoppableAdsの前に登録して、Shoppable Adsの支払いを有効にします。すべてのShoppable Ads配置には登録が必要です。Apple PayにはapplePayMerchantIdを、Afterpay / ClearpayにはurlSchemeを渡すか、両方を渡してください。付録E: Shoppable Ads支払いの設定を参照してください。拡張機能はSwiftで作成および登録されます。Objective-Cアプリでは、小さなSwiftファイルからこれを行ってください。
3. Identify the User#
SDK+初期化スクリプトは、スクリプトのidentifyRequestオブジェクトに提供された識別子を使用して現在のユーザーを識別します。SDKの初期化後、ユーザーがログイン、ログアウト、またはチェックアウト時などに識別子を提供するたびに、適切な方法を使用してユーザーのアイデンティティを同期させる必要があります。
サポートされているユーザー識別子サポートされているユーザー識別子 への直接リンク
サポートされているユーザー識別子を表示
| フィールド | タイプ | 説明 |
|---|---|---|
email | string | 顧客の生のハッシュ化されていないメールアドレスを identifyRequest.email に割り当てます。 |
emailSha256 | string | SHA-256 ハッシュ化されたメール(iOS パス)。identifyRequest.setIdentity(hashedEmail, identityType: .other) を介して渡します。ハッシュ化された形式のみが利用可能な場合は、email の代わりに使用します。 |
mobileSha256 | string | SHA-256 ハッシュ化された携帯番号(iOS パス)。identifyRequest.setIdentity(hashedMobile, identityType: .other4) を介して渡します。 |
mobile | string | E.164 形式の電話番号。identifyRequest.setIdentity(mobileNumber, identityType: .phoneNumber) を介して渡します。 |
customerid | string | 内部の顧客/アカウント識別子を identifyRequest.customerId に割り当てます。 |
ユーザーを識別するには:
1Create an identifyRequest object#
ユーザーの識別子を含む identifyRequest オブジェクトを作成します。
2Create an identityCallback#
識別が成功した後に追加のユーザー属性を設定するための identityCallback を作成します。
3Send the request using the method that matches the user's action#
ユーザーのアクションに一致するメソッドに identifyRequest (およびオプションの identityCallback)を渡します:
MParticle.sharedInstance().identity.login: ユーザーがログインまたはアカウントを作成したときに呼び出します。MParticle.sharedInstance().identity.identify: ログインの遷移なしでセッション中にユーザーのメールを取得したときに呼び出します(例:ゲストがチェックアウト時にメールを入力する場合)。MParticle.sharedInstance().identity.logout: ユーザーがログアウトしたときに呼び出します。
これらのメソッドを呼び出すことで、SDK の現在のユーザー状態の記録が遷移します。login と logout メソッドは、Rokt の帰属を改善するために対応するイベントも自動的にログします。
例えば、メール j.smith@example.com、携帯番号 +13125551515、顧客 ID cust_10482 を持つユーザー Jane Smith の場合:
// 1. Create the identifyRequest object
let identifyRequest = MPIdentityApiRequest.withEmptyUser()
identifyRequest.email = "j.smith@example.com"
// Customer phone number in E.164 format.
identifyRequest.setIdentity("+13125551515", identityType: .phoneNumber)
// If you can only provide a SHA-256-hashed mobile number, use .other2 instead of .phoneNumber — do not pass both.
identifyRequest.setIdentity("SHA-256 hashed mobile number", identityType: .other2)
// 2. User attributes are set using identityCallback
let identityCallback = {(result: MPIdentityApiResult?) in
if let user = result?.user {
user.setUserAttribute("firstname", value: "Jane")
user.setUserAttribute("lastname", value: "Smith")
}
}
// 3. Call one of the following methods that best matches the user's action:
MParticle.sharedInstance().identity.login(identifyRequest, completion: identityCallback) // Call when the user logs in or creates an account
MParticle.sharedInstance().identity.identify(identifyRequest, completion: identityCallback) // Call when you obtain the user's email mid-session, but not during a login
MParticle.sharedInstance().identity.logout() // Call when the user logs out
4. Set User Attributes#
ユーザーがアプリをナビゲートする際に、段階的に ユーザー属性を設定してください。チェックアウト時だけでなく、設定する属性が多いほど、Rokt は顧客をより正確に解決し、関連するオファーを提供できます。
import mParticle_Apple_SDK
// Retrieve the current user. This will only succeed if you have identified the user during SDK+ initialization or by calling the identify method.
let currentUser = MParticle.sharedInstance().identity.currentUser
// Once you have successfully set the current user to `currentUser`, you can set user attributes with:
currentUser?.setUserAttribute("custom-attribute-name", value: "custom-attribute-value")
// Note: all user attributes (including list attributes and tags) must have distinct names.
// Rokt recommends setting as many of the following user attributes as possible:
currentUser?.setUserAttribute("firstname", value: "John")
currentUser?.setUserAttribute("lastname", value: "Doe")
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser?.setUserAttribute("mobile", value: "3125551515")
currentUser?.setUserAttribute("age", value: "33")
currentUser?.setUserAttribute("gender", value: "M")
currentUser?.setUserAttribute("billingcity", value: "Brooklyn")
currentUser?.setUserAttribute("billingstate", value: "NY")
currentUser?.setUserAttribute("billingzipcode", value: "123456")
currentUser?.setUserAttribute("dob", value: "yyyymmdd")
currentUser?.setUserAttribute("title", value: "Mr")
currentUser?.setUserAttribute("language", value: "en")
currentUser?.setUserAttribute("predictedltv", value: "136.23")
// You can create a user attribute to contain a list of values
currentUser?.setUserAttributeList("favorite-genres", values: ["documentary", "comedy", "romance", "drama"])
// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser?.removeUserAttribute("attribute-to-remove")
ユーザー属性ユーザー属性 への直接リンク
収集可能な限り、以下の項目を設定してください:
すべてのユーザー属性を表示
| フィールド | タイプ | 説明 |
|---|---|---|
firstname | string | 顧客の名。パーソナライズに使用されます。 |
lastname | string | 顧客の姓。パーソナライズに使用されます。 |
mobile | string | 電話番号は 1112345678 または +1 (222) 345-6789 の形式で記載。アイデンティティ解決と関連性に使用されます。 |
birthyear | integer | 顧客の生年 (例: 1990)。生年月日フィールドとして推奨。代替: dob, age。適格性と関連性に使用されます。 |
age | integer | 顧客の年齢。dob の代替。適格性と関連性に使用されます。 |
dob | string | 生年月日、yyyymmdd。age の代替。適格性と関連性に使用されます。 |
gender | string | 顧客の性別。例: M, F, Male, または Female。関連性に使用されます。 |
title | string | 敬称。例: Mr, Mrs, Ms。パーソナライズに使用されます。 |
language | string | 購入に関連付けられたISO 639-1言語コード。関連性に使用されます。 |
billingaddress1 | string | 住所 (例: 123 Main St)。アイデンティティ解決と関連性に使用されます。 |
billingaddress2 | string | アパート/ユニット (例: Apt 4B)。アイデンティティ解決に使用されます。 |
billingcity | string | 請求先の市。関連性に使用されます。 |
billingstate | string | 請求先の州/県/地域。関連性と適格性に使用されます。 |
billingzipcode | string | 完全なZIPまたは郵便番号 (米国の優先形式はZIP+4)。アイデンティティ解決と関連性に使用されます。 |
country | string | ISO 3166-1 alpha-2国コード (例: US, GB, AU)。適格性と関連性に使用されます。 |
newcustomer | boolean | 初めての購入者かどうか。関連性に使用されます。 |
customertype | string | ユーザーが認証されているかどうか (guest / logged_in)。関連性に使用されます。 |
loyaltytier | string | パートナーのロイヤルティプログラムの階層。関連性と適格性に使用されます。 |
loyaltyid | string | ロイヤルティプログラムのメンバーID。アイデンティティ解決に使用されます。 |
predictedltv | decimal | 予測される総生涯価値。通常はパートナーの機械学習モデルから得られます。関連性に使用されます。 |
subscriptionstatus | string | 該当する場合のサブスクリプション状態 (active, trial, churned, paused, none)。関連性と適格性に使用されます。 |
customersegment | string | パートナー内部のセグメンテーション (例: vip, at_risk, new, reactivated)。関連性に使用されます。 |
acquisitionchannel | string | 顧客が最初に獲得された方法。関連性に使用されます。 |
すべてのユーザー属性(リスト属性を含む)は、異なる名前を持たなければなりません。
5. Log Events#
画面ビュー、コマースイベント、およびカスタムイベントを追跡して、Roktが各顧客がどの段階にいるかを理解できるようにします。
logScreen を画面の名前(例: "homepage", "product_detail_page")と共に呼び出します。追加のカスタム属性を eventInfo に含めます。
MParticle.sharedInstance().logScreen(
"homepage",
eventInfo: ["custom-attribute": "custom-value"]
)
コマースイベントは、ユーザーの旅における製品レベルの詳細を含みます。顧客が取る各製品アクションに対して別々のコマースイベントをトリガーします。
完全なコマースイベントのカバレッジに投資することは、統合中にできる最も効果的なことの一つです。各イベントは、顧客がどの段階にいるかについてRoktに異なる情報を伝えます:製品ビューは探索を示し、カートへの追加は検討を示し、チェックアウトの開始は購入意図を示し、購入完了はコンバージョンを確認します。豊富なシグナルにより、Roktはオファーをより効果的にパーソナライズし、配置のパフォーマンスを正確に測定し、コンバージョンを正しいタッチポイントに帰属させることができます。この作業を初期統合中に行うことで、後のレトロフィットを避けることができます。シグナルは時間とともに蓄積されます:Roktが受け取る各イベントは、パーソナライズを鋭くし、帰属精度を向上させ、将来の訪問で顧客ベースをよりよく解決しセグメント化するために使用されるコンテキストを追加します。
コマースイベントは、MPCommerceEvent を使用してログに記録され、顧客のアクション(製品の閲覧、カートへの追加、チェックアウトの開始、購入の完了など)を識別する MPCommerceEventAction を使用します。
すべての製品アクションタイプを表示
| 顧客のアクション | Swift アクションタイプ | Objective-C アクションタイプ |
|---|---|---|
| 商品詳細ページを閲覧 | .viewDetail | MPCommerceEventActionViewDetail |
| 商品をクリック | .click | MPCommerceEventActionClick |
| カートに商品を追加 | .addToCart | MPCommerceEventActionAddToCart |
| カートから商品を削除 | .removeFromCart | MPCommerceEventActionRemoveFromCart |
| ウィッシュリストに商品を追加 | .addToWishlist | MPCommerceEventActionAddToWishlist |
| ウィッシュリストから商品を削除 | .removeFromWishlist | MPCommerceEventActionRemoveFromWishlist |
| チェックアウトフローを開始 | .checkout | MPCommerceEventActionCheckout |
| チェックアウトオプションを選択 | .checkoutOption | MPCommerceEventActionCheckoutOption |
| 注文を確認 | .purchase | MPCommerceEventActionPurchase |
| 注文を返金 | .refund | MPCommerceEventActionRefund |
コマースイベントをトラッキングするには、3つのフェーズがあります:
1Define the product#
商品の名前、SKU、数量、価格を指定して MPProduct を作成します。category、brand、variant、position などの追加フィールドをインスタンスに直接設定します。
let product = MPProduct(
name: "Double Room - Econ Rate",
sku: "econ-1",
quantity: 4,
price: 100.00
)
product.category = "room"
product.brand = "lodge-o-rama"
product.variant = "standard"
2Summarize the transaction#
MPTransactionAttributes を Purchase、Checkout、および CheckoutOption イベントのために作成します。該当する場合は、配送や注文レベルのクーポンを含めます — 注文レベルのクーポンはここに含まれ、個々の商品には含まれません。
let attributes = MPTransactionAttributes()
attributes.transactionId = "ORDER-12345"
attributes.revenue = 149.99
attributes.tax = 12.50
attributes.shipping = 5.99
attributes.couponCode = "SUMMER20"
3Log the commerce event#
上記の表から MPCommerceEventAction を使用して MPCommerceEvent を構築し、該当する場合は transactionAttributes を添付し、MParticle.sharedInstance().logEvent に渡します。ログに記録したい顧客のアクションを選択します:
商品リスト(またはカテゴリ)ページビューを商品インプレッションとしてログに記録します。すべての表示されている商品を単一の呼び出しで渡し、インプレッションの名前をリスト/カテゴリ名に設定します(Rokt はこれを list_name として使用します)。
| フィールド | タイプ | 必須 | 説明 |
|---|---|---|---|
Name | string | yes | リストまたはカテゴリ名(例: "Mens Running Shoes")。list_name になります。 |
Products | array | yes | createProduct からの製品オブジェクト。各アイテムの1インデックスのランクに Position を設定します。 |
currency | string | yes | ISO 4217 通貨コード(イベントレベルの customAttribute として渡されます)。 |
let product = MPProduct(
name: "Trail Runner v3",
sku: "SKU-001",
quantity: 1,
price: 129.95
)
product.position = 1 // 1-indexed rank in the list
let event = MPCommerceEvent(impressionName: "Mens Running Shoes", product: product)
event.currency = "USD"
MParticle.sharedInstance().logEvent(event)
製品詳細ページが開かれたときにログを記録します。
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
productsku | string | yes | 製品SKU。 |
productname | string | yes | 表示名。 |
itemprice | decimal | yes | 表示時の単価。 |
currency | string | yes | ISO 4217通貨コード。 |
list_name | string | no | ユーザーがPLPから来た場合に設定。 |
let product = MPProduct(
name: "Trail Runner v3",
sku: "SKU-001",
quantity: 1,
price: 129.95
)
let event = MPCommerceEvent(action: .viewDetail, product: product)
event.currency = "USD"
event.customAttributes = ["list_name": "PLP-Running"]
MParticle.sharedInstance().logEvent(event)
商品がカートに追加されたときにログを記録します。
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
productsku | string | yes | 製品SKU。 |
quantity | integer | yes | 追加された単位数。 |
itemprice | decimal | yes | 追加時の単価。 |
currency | string | yes | ISO 4217通貨コード。 |
couponCode | string | no | 追加時に適用された注文レベルのクーポン。 |
let product = MPProduct(
name: "Trail Runner v3",
sku: "SKU-001",
quantity: 1,
price: 129.95
)
let event = MPCommerceEvent(action: .addToCart, product: product)
event.currency = "USD"
MParticle.sharedInstance().logEvent(event)
商品がカートから削除されたときにログを記録します。
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
productsku | string | yes | 製品SKU。 |
quantity | integer | yes | 削除された単位数。 |
currency | string | yes | ISO 4217通貨コード。 |
let product = MPProduct(
name: "Trail Runner v3",
sku: "SKU-001",
quantity: 1, // units removed
price: 129.95
)
let event = MPCommerceEvent(action: .removeFromCart, product: product)
event.currency = "USD"
MParticle.sharedInstance().logEvent(event)
顧客がカートページに到着したときにログを記録します。カートページビューにはネイティブなMPCommerceEventActionがないため、イベント名"view_cart"と.otherイベントタイプを持つMPEventを使用します。カスタム属性としてカートの全内容を渡します。
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
event_name | string | yes | 常に"view_cart"。 |
event_type | EventType | yes | MPEventType.otherを使用。 |
cartitems | array | yes | 実際のJSON配列としてのカート全内容(文字列化しない)。 |
cartitemcount | integer | yes | カートラインの数。 |
totalprice | decimal | yes | カート合計。 |
currency | string | yes | ISO 4217通貨コード。 |
couponcode | string | no | 適用された場合の注文レベルのプロモーション。 |
cartitems配列の各エントリは次の形状を持ちます:
| Field | Type | Description |
|---|---|---|
cartitemid | string | Stable partner-side cart-line identifier. Usually equals productsku when there is one line per SKU; use a unique value if you allow multiple lines for the same SKU (e.g. gift-wrap variants). |
productsku | string | Product SKU / stock identifier. |
productname | string | Product display name. |
productcategory | string | Product category / taxonomy leaf. |
productbrand | string | Product brand. |
productvariant | string | Variant identifier (size, color, etc.). |
itemprice | decimal | Per-unit price at event time. |
unitprice | decimal | Per-unit list price pre-discount. Omit if equal to itemprice. |
quantity | integer | Units in this line. |
currency | string | ISO 4217 code. Omit if matches the top-level currency. |
couponcode | string | Coupon applied to this line (if any). Order-level promos belong in transactionAttributes.Coupon. |
productposition | integer | 1-indexed rank of the product within a list or search results. |
if let event = MPEvent(name: "view_cart", type: .other) {
event.customAttributes = [
"cartitemcount": 3,
"totalprice": 169.85,
"currency": "USD",
"couponcode": "SUMMER20",
"cartitems": [
["cartitemid": "SKU-001", "productsku": "SKU-001", "productname": "Trail Runner v3", "itemprice": 129.95, "quantity": 1],
["cartitemid": "SKU-002", "productsku": "SKU-002", "productname": "Cushion Insole", "itemprice": 19.95, "quantity": 2]
]
]
MParticle.sharedInstance().logEvent(event)
}
顧客がチェックアウトフローに入ったときにログを記録します。カートの合計と注文レベルのクーポンを含むトランザクションサマリーとすべてのカート製品を送信します。
| Field | Type | Required | Description |
|---|---|---|---|
cartitems | array | yes | カートの全内容。 |
totalprice | decimal | yes | 税金/送料前のカート合計。 |
cartitemcount | integer | yes | カートの行数。 |
currency | string | yes | ISO 4217通貨コード。 |
couponCode | string | no | 適用された場合の注文レベルのプロモ。 |
let product1 = MPProduct(name: "Trail Runner v3", sku: "SKU-001", quantity: 1, price: 129.95)
let product2 = MPProduct(name: "Cushion Insole", sku: "SKU-002", quantity: 2, price: 19.95)
let attributes = MPTransactionAttributes()
attributes.revenue = 169.85
attributes.couponCode = "SUMMER20"
let event = MPCommerceEvent(action: .checkout, product: product1)
event.addProduct(product2)
event.transactionAttributes = attributes
event.currency = "USD"
event.customAttributes = ["cartitemcount": 3]
MParticle.sharedInstance().logEvent(event)
顧客が配送ステップを完了したときにログを記録します。checkoutOptionを"shipping"に設定し、配送選択をカスタム属性として渡します。
| Field | Type | Required | Description |
|---|---|---|---|
cartitems | array | yes | カートの全内容。 |
option | string | yes | このイベントでは常に"shipping"です。 |
shippingmethod | string | yes | standard / express / next_day。 |
zipcode | string | yes | 配送ZIP/郵便番号。 |
country | string | yes | ISO 3166-1 alpha-2国コード。 |
totalprice | decimal | yes | カート合計。 |
currency | string | yes | ISO 4217通貨コード。 |
let product1 = MPProduct(name: "Trail Runner v3", sku: "SKU-001", quantity: 1, price: 129.95)
let product2 = MPProduct(name: "Cushion Insole", sku: "SKU-002", quantity: 2, price: 19.95)
let event = MPCommerceEvent(action: .checkoutOption, product: product1)
event.addProduct(product2)
event.checkoutOption = "shipping"
event.currency = "USD"
event.customAttributes = [
"shippingmethod": "express",
"zipcode": "94103",
"country": "US",
"totalprice": 169.85
]
MParticle.sharedInstance().logEvent(event)
顧客が支払いステップを完了したときにログを記録します。checkoutOptionを"payment"に設定し、選択された支払い方法をカスタム属性として渡します。
| Field | Type | Required | Description |
|---|---|---|---|
cartitems | array | yes | カートの全内容。 |
option | string | yes | このイベントでは常に"payment"です。 |
paymenttype | string | yes | credit_card / paypal / apple_pay / etc. |
payment_method | string | no | 関連する場合の具体的な方法(例:カードブランド)。 |
paymentServiceProvider | string | no | PSP識別子(例:stripe)。camelCaseである必要があります。 |
ccbin | string | no | カードが使用された場合の最初の6-8桁。 |
totalprice | decimal | yes | カート合計。 |
currency | string | yes | ISO 4217通貨コード。 |
let product1 = MPProduct(name: "Trail Runner v3", sku: "SKU-001", quantity: 1, price: 129.95)
let product2 = MPProduct(name: "Cushion Insole", sku: "SKU-002", quantity: 2, price: 19.95)
let event = MPCommerceEvent(action: .checkoutOption, product: product1)
event.addProduct(product2)
event.checkoutOption = "payment"
event.currency = "USD"
event.customAttributes = [
"paymenttype": "credit_card",
"payment_method": "visa",
"paymentServiceProvider": "stripe",
"ccbin": "424242",
"totalprice": 169.85
]
MParticle.sharedInstance().logEvent(event)
注文が確認されたときにログを記録します。注文、収益、税金、送料、および注文レベルのクーポンを識別するトランザクション概要とともにカート全体を送信します。
| Field | Type | Required | 説明 |
|---|---|---|---|
cartitems | array | yes | 注文時のカート内容全体。 |
transactionId | string | yes | 注文/取引の識別子。 |
totalprice | decimal | yes | 注文合計(収益)。 |
tax | decimal | yes | 注文の総税額。 |
shipping | decimal | yes | 配送料。 |
currency | string | yes | ISO 4217通貨コード。 |
couponCode | string | no | 適用された場合の注文レベルのプロモ。 |
cartitemcount | integer | no | カートラインの数。 |
let product1 = MPProduct(name: "Trail Runner v3", sku: "SKU-001", quantity: 1, price: 129.95)
let product2 = MPProduct(name: "Cushion Insole", sku: "SKU-002", quantity: 2, price: 19.95)
let attributes = MPTransactionAttributes()
attributes.transactionId = "ORDER-10482"
attributes.revenue = 169.85
attributes.tax = 14.20
attributes.shipping = 5.99
attributes.couponCode = "SUMMER20"
let event = MPCommerceEvent(action: .purchase, product: product1)
event.addProduct(product2)
event.transactionAttributes = attributes
event.currency = "USD"
event.customAttributes = ["cartitemcount": 3]
MParticle.sharedInstance().logEvent(event)
注文(またはその中のライン)が払い戻されたときにログを記録します。払い戻される商品と元の注文IDを参照する取引概要のみを送信してください。
| Field | Type | Required | 説明 |
|---|---|---|---|
productsku | string | yes | 払い戻されたラインのSKU。 |
quantity | integer | yes | 払い戻された単位数。 |
transactionId | string | yes | 払い戻し対象の元の注文ID。 |
totalprice | decimal | yes | 払い戻された金額。 |
currency | string | yes | ISO 4217通貨コード。 |
let refundedProduct = MPProduct(
name: "Trail Runner v3",
sku: "SKU-001",
quantity: 1, // units refunded
price: 129.95
)
let attributes = MPTransactionAttributes()
attributes.transactionId = "ORDER-10482" // original order id
attributes.revenue = 129.95 // refunded amount
let event = MPCommerceEvent(action: .refund, product: refundedProduct)
event.transactionAttributes = attributes
event.currency = "USD"
MParticle.sharedInstance().logEvent(event)
MPEventを使用してカスタムイベントを追跡し、イベント名、イベントタイプ、およびオプションのカスタム属性を渡します。
カスタムイベントの種類を表示
Swift
| Type | 使用目的 |
|---|---|
.navigation | アプリ内のユーザーナビゲーションフローとページ遷移。 |
.location | 位置情報に基づくインタラクションと移動。 |
.search | 検索クエリと検索関連のアクション。 |
.transaction | 金融取引と購入関連の活動。 |
.userContent | レビュー、コメント、投稿などのユーザー生成コンテンツ。 |
.userPreference | ユーザー設定、好み、カスタマイズの選択。 |
.social | ソーシャルメディアのインタラクションと共有活動。 |
.other | 上記のカテゴリに当てはまらないもの。 |
Objective-C
| タイプ | 使用用途 |
|---|---|
MPEventTypeNavigation | アプリ内のユーザーのナビゲーションフローやページ遷移。 |
MPEventTypeLocation | 位置情報に基づくインタラクションや移動。 |
MPEventTypeSearch | 検索クエリや検索関連のアクション。 |
MPEventTypeTransaction | 金融取引や購入関連のアクティビティ。 |
MPEventTypeUserContent | レビュー、コメント、投稿などのユーザー生成コンテンツ。 |
MPEventTypeUserPreference | ユーザー設定、好み、カスタマイズの選択。 |
MPEventTypeSocial | ソーシャルメディアのインタラクションや共有活動。 |
MPEventTypeOther | 上記のカテゴリに当てはまらないもの。 |
if let event = MPEvent(name: "video_watched", type: .navigation) {
event.customAttributes = ["category": "Destination Intro", "title": "Paris"]
MParticle.sharedInstance().logEvent(event)
}
6. Show a Placement#
Roktがコンテンツを表示するために、すべての支払いおよび確認画面でselectPlacementsを呼び出します。画面の種類とテストまたは本番環境であるかを指定するために、以下のページ識別子のいずれかを含めます。
stg.rokt.conf: A confirmation screen in a staging (or testing) environment.prod.rokt.conf: A confirmation screen in a production environment.stg.rokt.payments: A payments screen in a staging (or testing) environment.prod.rokt.payments: A payments screen in a production environment.
画面が読み込まれ、すべての関連属性が利用可能になったらすぐに、selectPlacementsを呼び出します。最低限、email、firstname、lastname、billingzipcode、およびconfirmationrefを渡します。完全なリストはPlacement Attributesを参照してください。
Pay+プレースメントの場合、各ページでのselectPlacements呼び出しにpaymenttypeとpaymentServiceProviderを含めます。paymentServiceProviderは支払いページで利用可能な支払い方法を伝え、paymenttypeはユーザーが支払った方法を伝えます。
import mParticle_Apple_SDK
let attributes = [
"email": "test@gmail.com",
"firstname": "Jenny",
"lastname": "Smith",
"billingzipcode": "07762",
"confirmationref": "54321"
]
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes)
埋め込みプレースメントはオーバーレイプレースメントと同じ属性要件を共有しますが、プレースメントビューを独自のUI内にレンダリングします。プレースメントイベント(ロード、アンロード、ローディングインジケーター、埋め込みサイズ変更など)に応答するためにonEventコールバックを使用します。イベントタイプはRoktEvent(RoktContractsパッケージから)のサブクラスです。コールバックでイベントタイプを確認してください。
import mParticle_Apple_SDK
let attributes = [
"email": "test@gmail.com",
"firstname": "Jenny",
"lastname": "Smith",
"billingzipcode": "07762",
"confirmationref": "54321"
]
let roktFrame = CGRect(x: 0, y: 0, width: 320, height: 50)
let roktView = RoktEmbeddedView(frame: roktFrame)
let embeddedViews = ["RoktEmbedded1": roktView]
let roktConfig = RoktConfig.Builder().colorMode(.light).build()
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: embeddedViews, config: roktConfig) { event in
switch event {
case let sizeEvent as RoktEvent.EmbeddedSizeChanged:
// Example event - Height changed: use sizeEvent.identifier and sizeEvent.updatedHeight
// The full list of events is provided below
break
default:
break
}
}
Shoppable Adsは、Roktプレースメント内にオーバーレイとしてレンダリングされる、アプリ内カタログ閲覧と即時チェックアウトを備えた購入後のアップセルオファーです。selectPlacementsではなく、selectShoppableAdsで表示します。登録されたRoktPaymentExtensionが必要です。登録されていない場合、selectShoppableAdsはPlacementFailureイベントを発生させます。Appendix E: Configure Shoppable Ads paymentsを参照してください。
import mParticle_Apple_SDK
let attributes = [
"email": "j.smith@example.com",
"firstname": "Jane",
"lastname": "Smith",
"confirmationref": "ORD-8829-XK2",
"amount": "52.25",
"currency": "USD",
"paymenttype": "visa",
"shippingaddress1": "123 Main St",
"shippingcity": "Brooklyn",
"shippingstate": "NY",
"shippingzipcode": "11201",
"shippingcountry": "US"
]
MParticle.sharedInstance().rokt.selectShoppableAds("ConfirmationPage", attributes: attributes, config: nil) { event in
switch event {
case let e as RoktEvent.CartItemInstantPurchase:
print("Purchase completed: \(e.catalogItemId)")
case let e as RoktEvent.CartItemInstantPurchaseFailure:
print("Purchase failed: \(e.error ?? "unknown")")
case is RoktEvent.InstantPurchaseDismissal:
print("User dismissed purchase")
default:
break
}
}
プラットフォームに配送先住所の詳細がない場合(例: チケットやデジタル商品購入)、代わりに請求先住所の詳細を渡してください。Roktは、購入を完了する前に顧客が配送先住所を確認または編集するためのUIを提供します。
カード転送の場合、partnerpaymentreferenceとlast4digitsも渡してください — Placement Attributesを参照してください。以下のEvents APIにあるCartItemInstantPurchaseおよび関連イベントは、Shoppable Ads購入フロー中に発火します。
追加設定追加設定 への直接リンク
配置UIをカスタマイズするために、RoktConfigのようなオプションのパラメータを渡します(例: ダーク/ライトモード)。埋め込みビューやonEventコールバックを含む追加のオプションパラメータが以下に示されています。
let roktConfig = RoktConfig.Builder().colorMode(.light).build()
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, config: roktConfig) { _ in }
異なる値でRoktExperienceまたは埋め込み識別子RoktEmbedded1を更新したい場合は、Roktアカウントマネージャーに連絡して、Rokt配置が一貫して設定されていることを確認してください。
オプション機能オプション機能 への直接リンク
| 機能 | 目的 |
|---|---|
Rokt.close() | オーバーレイ配置を自動的に閉じる。 |
サポートされている属性の完全なリストについては、以下のPlacement Attributesを参照してください。
Roktチームがブランドに合わせて配置レイアウトを設定します。
配置属性配置属性 への直接リンク
これらの属性をattributes辞書にselectPlacementsとして渡します。常に最新の値を提供してください。ここで渡された属性は、以前のsetUserAttribute呼び出しを上書きします。
すべての配置属性を表示
| フィールド | タイプ | 説明 |
|---|---|---|
email | string | 顧客のメールアドレス(ハッシュされていない)。アイデンティティ解決とShoppable Adsの注文確認に使用されます。 |
firstname | string | 顧客の名前。パーソナライゼーションとShoppable Adsの注文履行に使用されます。 |
lastname | string | 顧客の姓。パーソナライゼーションとShoppable Adsの注文履行に使用されます。 |
mobile | string | E.164形式の顧客の携帯電話番号。アイデンティティ解決に使用されます。 |
confirmationref | string | 注文/確認参照番号。関連性、重複排除、Shoppable Adsの注文調整に使用されます。 |
currency | string | 取引通貨(ISO 4217、例: USD, GBP, AUD)。関連性とShoppable Adsに使用されます。 |
country | string | ISO 3166-1 alpha-2の国コード。適格性と関連性に使用されます。 |
language | string | 顧客の希望言語(ISO 639-1)。関連性に使用されます。 |
totalprice | decimal | 税金と送料を含むカートの合計値。関連性に使用されます。 |
amount | decimal | 税金と送料を含まないカートの小計。totalpriceとは異なります。関連性とShoppable Adsに使用されます。 |
cartItems | array | カートラインオブジェクトの構造化された配列。キャメルケースである必要があります。関連性に使用されます。 |
couponcode | string | 適用されたプロモーションコード(ある場合)。関連性に使用されます。 |
newcustomer | boolean | 初回購入者かどうか。関連性に使用されます。 |
customertype | string | guestまたはlogged_in。関連性に使用されます。 |
value | decimal | 顧客の累積購入価値。関連性に使用されます。 |
subscriptionstatus | string | 該当する場合のサブスクリプション状態(active, trial, churned, paused, none)。関連性と適格性に使用されます。 |
customersegment | string | パートナー内部セグメンテーション(vip, at_risk, new, reactivated)。関連性に使用されます。 |
paymenttype | string | 選択された支払い方法 (credit_card, paypal, apple_pay など)。Pay+ の適格性および Shoppable Ads の支払い方法の優先順位付けに使用されます。 |
paymentServiceProvider | string | ページで受け入れられる支払い方法のカンマ区切りリスト(例: applepay,paypal,cardpayment)。値は小文字でスペースを含まない必要があります。受け入れられる値の完全なリストについては、Payment Service Provider を参照してください。Pay+ の適格性に使用されます。 |
ccbin | string | クレジットカードの BIN(6-8 桁)。関連性に使用されます。 |
billingaddress1 | string | 請求先の住所。アイデンティティ解決と関連性に使用されます。 |
billingaddress2 | string | 請求先のアパート/ユニット。アイデンティティ解決に使用されます。 |
billingcity | string | 請求先の市区町村。関連性に使用されます。 |
billingstate | string | 請求先の州または省。関連性に使用されます。 |
billingzipcode | string | 請求先の郵便番号/郵便番号。アイデンティティ解決と関連性に使用されます。 |
billingname | string | 請求先住所のカード所有者のフルネーム。アイデンティティ解決に使用されます。 |
shippingmethod | string | 選択された配送方法 (standard, express, next_day)。関連性に使用されます。 |
shippingname | string | 配送先住所の受取人のフルネーム。Shoppable Ads の注文履行に使用されます。 |
shippingaddress1 | string | 配送先の住所。関連性と Shoppable Ads の注文履行に使用されます。 |
shippingcity | string | 配送先の市区町村。関連性と Shoppable Ads の注文履行に使用されます。 |
shippingstate | string | 配送先の州または省。関連性と Shoppable Ads の注文履行に使用されます。 |
shippingzipcode | string | 配送先の郵便番号または郵便番号。関連性と Shoppable Ads の注文履行に使用されます。 |
shippingcountry | string | 配送先の国(ISO 3166-1 alpha-2)。関連性と Shoppable Ads の注文履行に使用されます。 |
partnerpaymentreference | string | 顧客の保存された支払い方法の推測不可能な識別子。Shoppable Ads のカード転送に必要です。 |
last4digits | string | 使用されたカードの最後の4桁。Shoppable Ads 中に顧客に表示されます。 |
plcc | string | "yes" または "no" — 顧客がプライベートラベルのクレジットカードを持っているかどうか。Pay+ の関連性に使用されます。 |
discountamount | decimal | 注文レベルの割引額。Pay+ の関連性に使用されます。 |
prescreen | string | "yes" または "no" — 顧客がクレジットオファーの事前承認を受けているかどうか。Pay+ の関連性に使用されます。 |
adsexperience | string | 必須です。Shoppable Ads エクスペリエンスを選択するには "shoppable" を渡します。 |
イベント APIイベント API への直接リンク
SDK+ は、Rokt.events API を通じてプレースメントのライフサイクルイベントを発行します。ロード状態、エンゲージメント、失敗、Shoppable Adsの購入フローに応答するためにサブスクライブします。
import mParticle_Apple_SDK
MParticle.sharedInstance().rokt.events("RoktLayout", onEvent: { roktEvent in
if let event = roktEvent as? RoktEvent.ShowLoadingIndicator {
// Example showing handling of ShowLoadingIndicator event
// The full list of events is provided below
}
})
標準イベント標準イベント への直接リンク
すべての標準イベントを表示
| イベント | 説明 | パラメータ |
|---|---|---|
| ShowLoadingIndicator | SDK+ がRoktバックエンドを呼び出す前にトリガーされます | |
| HideLoadingIndicator | SDK+ がRoktバックエンドから成功または失敗を受信したときにトリガーされます | |
| PlacementInteractive | プレースメントがレンダリングされ、インタラクティブになったときにトリガーされます | identifier: String |
| PlacementReady | プレースメントが表示準備ができているが、まだコンテンツがレンダリングされていないときにトリガーされます | identifier: String |
| OfferEngagement | ユーザーがオファーにエンゲージしたときにトリガーされます | identifier: String |
| OpenUrl | ユーザーがパートナーアプリに送信するように設定されたURLを押したときにトリガーされます | identifier: String, url: String |
| PositiveEngagement | ユーザーがオファーに積極的にエンゲージしたときにトリガーされます | identifier: String |
| PlacementClosed | ユーザーによってプレースメントが閉じられたときにトリガーされます | identifier: String |
| PlacementCompleted | オファーの進行が終了し、表示するオファーがなくなったときにトリガーされます。 キャッシュがヒットしたが、以前に却下されたために取得されたプレースメントが表示されない場合にもトリガーされます | identifier: String |
| PlacementFailure | 何らかの失敗によりプレースメントを表示できない場合、または表示するプレースメントがない場合にトリガーされます | identifier: String (optional) |
| FirstPositiveEngagement | ユーザーが初めてオファーに積極的にエンゲージしたときにトリガーされます | identifier: String, setFulfillmentAttributes: func (attributes: [String: String]) |
| CartItemInstantPurchase | プレースメントを通じて購入が行われたときにトリガーされます | identifier: String, name: String?, cartItemId: String, catalogItemId: String, currency: String, description: String, linkedProductId: String?, providerData: String, quantity: NSDecimalNumber?, totalPrice: NSDecimalNumber?, unitPrice: NSDecimalNumber? |
| EmbeddedSizeChanged | 埋め込みプレースメントの高さが変わったときにトリガーされます | identifier: String, updatedHeight: CGFloat |
Shoppable Ads イベントShoppable Ads イベント への直接リンク
Shoppable Ads イベントを表示
| イベント | 説明 | パラメータ |
|---|---|---|
| CartItemInstantPurchaseInitiated | 購入フローが開始されました — ユーザーが「購入」をタップしました | identifier, catalogItemId, cartItemId |
| CartItemInstantPurchase | 購入が正常に完了しました | identifier, name, cartItemId, catalogItemId, currency, description, linkedProductId, providerData, quantity, totalPrice, unitPrice |
| CartItemInstantPurchaseFailure | 購入が失敗しました | identifier, catalogItemId, cartItemId, error |
| CartItemDevicePay | Apple Pay / デバイス支払いがトリガーされました | identifier, catalogItemId, cartItemId, paymentProvider |
| InstantPurchaseDismissal | ユーザーが購入オーバーレイを却下しました | identifier |
Rokt Shoppable Adをリクエストした後、以下のいずれかのイベントが発行される可能性があり、Rokt Thanksの後続のリクエストを行うタイミングを判断するために使用されるべきです:
PlacementClosedPlacementCompletedPlacementFailure
7. Appendix#
Appendix A: アプリケーション設定Appendix A: アプリケーション設定 への直接リンク
アプリケーションは、RoktConfig を通じて設定を送信することで、iOS SDK+ がシステムのデフォルト設定ではなく、アプリのカスタム設定を使用するようにできます。
ColorMode オブジェクトColorMode オブジェクト への直接リンク
| 値 | 説明 |
|---|---|
| light | アプリケーションはライトモードです |
| dark | アプリケーションはダークモードです |
| system | アプリケーションはシステムのカラーモードにデフォルトします |
// if application supports only Light Mode.
let roktConfig = RoktConfig.Builder().colorMode(.light).build()
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, config: roktConfig) { _ in }
// if application supports only Light Mode.
RoktConfig *roktConfig = [[[RoktConfigBuilder new] colorMode:RoktColorModeLight] build];
[[MParticle sharedInstance].rokt selectPlacements:@"RoktExperience"
attributes:attributes
embeddedViews:nil
config:roktConfig
onEvent:^(RoktEvent *_Nonnull event) {
// Handle placement events if needed
}];
CacheConfig オブジェクトCacheConfig オブジェクト への直接リンク
| パラメータ | 説明 |
|---|---|
| cacheDuration | Rokt SDK+ がエクスペリエンスをキャッシュするためのオプションの TimeInterval。許可される最大値は90分で、デフォルト(値が提供されていないか無効な場合)は90分です。 |
| cacheAttributes | キャッシュキーとして使用されるオプションの属性。nullの場合、selectPlacements 呼び出しで送信されたすべての属性がキャッシュキーとして使用されます。 |
// to cache the experience for 1200 seconds, using email and orderNumber attributes as the cache key.
let roktConfig = RoktConfig.Builder()
.cacheConfig(RoktConfig.CacheConfig(
cacheDuration: TimeInterval(1200),
cacheAttributes: ["email": "j.smith@example.com", "orderNumber": "123"]
))
.build()
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, config: roktConfig) { _ in }
// to cache the experience for 1200 seconds, using email and orderNumber attributes as the cache key.
NSDictionary *cacheKeyAttributes = @{
@"email": @"j.smith@example.com",
@"orderNumber": @"123"
};
RoktCacheConfig *cacheConfig =
[[RoktCacheConfig alloc] initWithCacheDuration:1200
cacheAttributes:cacheKeyAttributes];
RoktConfig *roktConfig = [[[RoktConfigBuilder new] cacheConfig:cacheConfig] build];
[[MParticle sharedInstance].rokt selectPlacements:@"RoktExperience"
attributes:attributes
embeddedViews:nil
config:roktConfig
onEvent:^(RoktEvent *_Nonnull event) {
// Handle placement events if needed
}];
Appendix B: SwiftUIサポートとMPRoktLayoutAppendix B: SwiftUIサポートとMPRoktLayout への直接リンク
アプリが主にSwiftUIで書かれている場合、iOSアプリにRoktプレースメントを統合するためのよりモダンな宣言的アプローチとして、MPRoktLayout コンポーネントを提供しています。
MPRoktLayout クラスは、selectPlacements を手動で呼び出すことなく、Roktプレースメントを表示するためのSwiftUI互換の方法を提供し、オーバーレイと埋め込みの両方のプレースメントタイプをサポートします。
SwiftUIコンポーネントの追加SwiftUIコンポーネントの追加 への直接リンク
import SwiftUI
import mParticle_Apple_SDK
import mParticle_Rokt_Swift
struct OrderConfirmationView: View {
let attributes = [
"email": "test@gmail.com",
"firstname": "Jenny",
"lastname": "Smith",
"billingzipcode": "07762",
"confirmationref": "54321"
]
@State private var sdkTriggered = true
var body: some View {
VStack(alignment: .leading) {
// Other UI components
Text("Order Confirmation")
.font(.title)
// Rokt placement using SwiftUI
MPRoktLayout(
sdkTriggered: $sdkTriggered,
identifier: "RoktExperience",
locationName: "RoktEmbedded1", // For embedded placements
attributes: attributes,
config: roktConfig, // Optional RoktConfig
onEvent: { roktEvent in
// Optional: Handle different event types see above
}
).roktLayout
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
}
パラメータパラメータ への直接リンク
| パラメータ | 型 | 説明 |
|---|---|---|
| sdkTriggered | Bool | プレースメントをいつトリガーするかを制御します |
| identifier | String | Roktプレースメント識別子(例: "RoktExperience") |
| locationName | String? | 埋め込みプレースメントのためのオプションのロケーション名(例: "RoktEmbedded1") |
| attributes | [String: String] | プレースメントに渡す属性の辞書 |
| config | RoktConfig? | カラーモード、キャッシングなどのオプションの設定オブジェクト |
| onEvent | ((RoktEvent) -> Void)? | すべてのプレースメントイベントを処理するためのオプションのコールバック |
Appendix C: エラーハンドリングAppendix C: エラーハンドリング への直接リンク
IDSync APIはアプリの状態の中心となることを意図しており、高速で高可用性を備えています。アプリがインターネット接続なしでユーザーのログイン、ログアウト、または状態の変更を防ぐように、これらのAPIをゲート操作として扱い、一貫したユーザー状態を維持することを意図しています。SDK+はAPIコールを自動的に再試行しませんが、コールバックAPIを提供しているため、ビジネスロジックに従って再試行することができます。再試行や不整合な状態に対する許容度は、製品の要件に依存します。
エラーを処理しない場合、大規模なデータ整合性の問題が発生する可能性があります。実装中にエラーを監視することをお勧めします。
IDSyncコールバックブロックは、次の2つのオブジェクトのいずれかで呼び出されます:
MPIdentityApiResult: 新しいまたは更新されたユーザーオブジェクトを含む結果オブジェクト。NSError/Error: IDSyncコールが失敗した場合にコードと説明を含むエラーオブジェクト
let identityCallback = {(result: MPIdentityApiResult?, error: Error?) in
if (result?.user != nil) {
//IDSync request succeeded, mutate attributes or query for the MPID as needed
result?.user.setUserAttribute("example attribute key", value: "example attribute value")
} else {
NSLog(error!.localizedDescription)
let resultCode = MPIdentityErrorResponseCode(rawValue: UInt((error! as NSError).code))
switch (resultCode!) {
case .clientNoConnection,
.clientSideTimeout:
//retry the IDSync request
break;
case .requestInProgress,
.retry:
//inspect your implementation if this occurs frequency
//otherwise retry the IDSync request
break;
default:
// inspect error.localizedDescription to determine why the request failed
// this typically means an implementation issue
break;
}
}
}
id identityCallback = ^(MPIdentityApiResult *_Nullable apiResult, NSError *_Nullable error) {
if (apiResult) {
// IDSync request succeeded, mutate attributes or query for the MPID as needed
[apiResult.user setUserAttribute:@"example attribute key"
value:@"example attribute value"];
} else {
NSLog(@"%@", error.userInfo);
switch (error.code) {
case MPIdentityErrorResponseCodeClientNoConnection:
case MPIdentityErrorResponseCodeClientSideTimeout:
// Retry the IDSync request
break;
case MPIdentityErrorResponseCodeRequestInProgress:
case MPIdentityErrorResponseCodeRetry:
// Inspect your implementation if this occurs frequently;
// otherwise retry the IDSync request
break;
default:
// Inspect error.userInfo to determine why the request failed
// This typically means an implementation issue
break;
}
}
};
ステータスコードステータスコード への直接リンク
IDSyncコールバックブロックが失敗で呼び出された場合、原因を特定するためにcodeプロパティを調べることができます。このプロパティは、それぞれのiOS SDK+ IDSync APIの呼び出し結果を説明することを目的としています。クライアント側で生成された値、または実際のHTTPステータスコードを含む場合があります。
クライアント側コードクライアント側コード への直接リンク
NSErrorコードプロパティは、MPIdentityErrorResponseCode列挙型内で定義された次のクライアント側コードを含む場合があります:
| MPIdentityErrorResponseCode | 説明 |
|---|---|
MPIdentityErrorResponseCodeRequestInProgress | 既にIDSync HTTPリクエストが進行中のため、IDSync HTTPリクエストは実行されませんでした |
MPIdentityErrorResponseCodeClientSideTimeout | TCP接続のタイムアウトにより、IDSync HTTPリクエストが失敗しました。 |
MPIdentityErrorResponseCodeClientNoConnection | ネットワークカバレッジの欠如により、IDSync HTTPリクエストが失敗しました。 |
MPIdentityErrorResponseCodeSSLError | SSL設定の問題により、IDSync HTTPリクエストが失敗しました。SDK+はmParticle SSL証明書をピン留めしており、無効化するにはMPNetworkOptions APIを介したカスタム初期化が必要です。 |
MPIdentityErrorResponseCodeOptOut | オプトアウトによりSDK+が無効化されているため、IDSync HTTPリクエストは実行されませんでした。 |
MPIdentityErrorResponseCodeUnknown | 不明なエラーにより、IDSync HTTPリクエストが失敗しました。これは稀であり、アプリが不良メモリ状態にある可能性があります。 |
HTTPステータスコードHTTPステータスコード への直接リンク
NSErrorコードプロパティは、サーバー側で生成された次のHTTPステータスコードを含む場合があります。これらの一部は、利便性のためにMPIdentityErrorResponseCode列挙型内で定義されています:
| 値 | 説明 |
|---|---|
| 400 | 無効なリクエストボディにより、IDSync HTTPコールが失敗しました。詳細については、error.userInfoオブジェクトを確認してください。 |
| 401 | 認証エラーにより、IDSync HTTPコールが失敗しました。APIキーが正しいことを確認してください。 |
| 403 | この操作がアカウントに対してプロビジョニングされていないため、IDSync HTTPコールが失敗しました。有効化するにはRoktアカウントマネージャーに連絡してください。 |
| 429 | IDSync HTTPコールがスロットルされ、再試行する必要があります。これは、ユーザーの「ホットキー」または予想以上のIDSyncリクエスト量を引き起こす不正な実装を示している可能性があります。 |
| 5xx | Roktサーバー側の問題により、IDSync HTTPコールが失敗しました。追加情報については、アカウント担当者に連絡してください。 |
UIApplication デリゲートプロキシUIApplication デリゲートプロキシ への直接リンク
デフォルトでは、mParticle SDK は UIApplication.delegate を独自の NSProxy 実装で置き換え、リモート通知、ローカル通知、通知アクションとのインタラクション、アプリケーションの起動の処理を容易にし、簡素化します。時間が経つにつれて、これは他の SDK が行うメソッドスウィズリングよりも侵襲性が低いことがわかっていますが、クライアントがサードパーティのフレームワークを使用している場合には複雑さを引き起こす可能性があります。
新しい統合では、proxyAppDelegate を無効にし、以下の SceneDelegate メソッド を使用してライフサイクルイベントを手動で mParticle に転送することをお勧めします。将来のメジャーリリースでは、proxyAppDelegate のデフォルトは false になります。
プロキシを無効にするには、proxyAppDelegate フラグを MParticleOptions オブジェクトで設定します。これを行うと、使用する各キットがどの UIApplication API を必要とするかを個別に監査する必要があります。必要なメソッドは mParticle で手動で呼び出し、mParticle がそれらの API を各キットに転送できるようにします。
- Swift
- Objective-C
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.proxyAppDelegate = false
MParticle.sharedInstance().start(with: options)
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.proxyAppDelegate = NO;
[[MParticle sharedInstance] startWithOptions:options];
プロキシが無効な場合の AppDelegate メソッドプロキシが無効な場合の AppDelegate メソッド への直接リンク
proxyAppDelegate が無効な場合、以下のメソッドを AppDelegate から mParticle に手動で転送する必要があります。これらのメソッドは、リモートまたはローカル通知機能を持つキット、およびプッシュ通知の登録に mParticle を使用するために必要です。
- Swift
- Objective-C
// MARK: - Remote Notification Registration
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
MParticle.sharedInstance().didRegisterForRemoteNotifications(withDeviceToken: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: any Error) {
MParticle.sharedInstance().didFailToRegisterForRemoteNotificationsWithError(error)
}
// MARK: - UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
MParticle.sharedInstance().userNotificationCenter(center, willPresent: notification)
if #available(iOS 14, *) {
completionHandler([.list, .banner])
} else {
completionHandler(.alert)
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
MParticle.sharedInstance().userNotificationCenter(center, didReceive: response)
completionHandler()
}
#pragma mark - Remote Notification Registration
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[MParticle sharedInstance] didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
[[MParticle sharedInstance] didFailToRegisterForRemoteNotificationsWithError:error];
}
#pragma mark - UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
[[MParticle sharedInstance] userNotificationCenter:center willPresentNotification:notification];
if (@available(iOS 14.0, *)) {
completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner);
} else {
completionHandler(UNNotificationPresentationOptionAlert);
}
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
[[MParticle sharedInstance] userNotificationCenter:center didReceiveNotificationResponse:response];
completionHandler();
}
SceneDelegate サポート (iOS 13+)SceneDelegate サポート (iOS 13+) への直接リンク
iOS 13で導入されたモダンなライフサイクルである UISceneDelegate を使用するアプリの場合、mParticleはURLコンテキストとユーザーアクティビティを処理するための専用メソッドを提供しています。これらはすべてのインテグレーションに推奨されるアプローチです。
URLコンテキストの処理URLコンテキストの処理 への直接リンク
SceneDelegate でディープリンクやカスタムURLスキームを処理するには、handleURLContext: メソッドを使用します:
- Swift
- Objective-C
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
MParticle.sharedInstance().handleURLContext(urlContext)
}
}
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
for (UIOpenURLContext *urlContext in URLContexts) {
[[MParticle sharedInstance] handleURLContext:urlContext];
}
}
ユーザーアクティビティ(ユニバーサルリンク)の処理ユーザーアクティビティ(ユニバーサルリンク)の処理 への直接リンク
SceneDelegate でユニバーサルリンクを処理するには、handleUserActivity: メソッドを使用します:
- Swift
- Objective-C
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
MParticle.sharedInstance().handleUserActivity(userActivity)
}
- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity {
[[MParticle sharedInstance] handleUserActivity:userActivity];
}
付録 D: ウェブからネイティブへのセッションIDの引き渡し付録 D: ウェブからネイティブへのセッションIDの引き渡し への直接リンク
ユーザージャーニーがウェブとネイティブプラットフォームの両方にまたがる場合、Web SDK+からiOS SDK+にセッションIDを引き渡すことで、一貫したRoktセッションを維持できます。これは、ユーザーがWebView(支払いページなど)でアクションを完了し、確認のためにネイティブアプリに戻るハイブリッドフローに役立ちます。
Web SDK+からセッションIDを取得するWeb SDK+からセッションIDを取得する への直接リンク
selectPlacementsを呼び出した後、セッションIDは選択コンテキストで利用可能です:
const selection = await launcher.selectPlacements({
identifier: "checkout",
attributes: {
email: "user@example.com",
// ... other attributes
}
});
const sessionId = await selection.context.sessionId;
The session ID is a unique GUID assigned to the current user journey. It is useful for debugging and for correlating a user's activity across your web and native surfaces.
ディープリンクを介してネイティブアプリに渡すディープリンクを介してネイティブアプリに渡す への直接リンク
ディープリンクを使用して、セッションIDをネイティブアプリに渡します:
const deepLink = `myapp://confirmation?sessionId=${encodeURIComponent(sessionId)}`;
window.location.href = deepLink;
セッションIDの設定セッションIDの設定 への直接リンク
ディープリンクからセッションIDを抽出し、selectPlacementsを呼び出す前にSDK+に渡します。
func handleDeepLink(url: URL) {
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
if let sessionId = components?.queryItems?.first(where: { $0.name == "sessionId" })?.value {
MParticle.sharedInstance().rokt.setSessionId(sessionId: sessionId)
}
// Proceed with your confirmation flow
}
- (void)handleDeepLink:(NSURL *)url {
NSURLComponents *components =
[NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
for (NSURLQueryItem *item in components.queryItems) {
if ([item.name isEqualToString:@"sessionId"]) {
[[[MParticle sharedInstance] rokt] setSessionIdWithSessionId:item.value];
break;
}
}
// Proceed with your confirmation flow
}
注意事項注意事項 への直接リンク
- セッションが使用されることを確実にするために、
setSessionIdをselectPlacementsの前に呼び出します - 空の文字列は無視され、セッションを更新しません
- クエリパラメータとして渡す際は、常にセッションIDをURLエンコードしてください
付録 E: Shoppable Adsの支払い設定付録 E: Shoppable Adsの支払い設定 への直接リンク
Shoppable Adsを使用していない場合、このステップはスキップしてください。
iOS上のShoppable Adsには登録済みのRoktPaymentExtensionが必要で、複数の支払い方法をサポートしています。リダイレクトベースの方法のみを提供する場合でも、すべてのShoppable Adsのプレースメントに対して拡張機能の登録が必須です。登録スニペットはステップ2の初期化コードに含まれています — MParticle.sharedInstance().start()の後、selectShoppableAdsの前に登録してください。
| 方法 | iOS設定 |
|---|---|
| Apple Pay | Apple PayのマーチャントIDをapplePayMerchantIdとしてRoktPaymentExtensionに渡します。オプションです。 |
| PayPal | Rokt SDK+に組み込まれています — 追加の拡張設定は不要です。リダイレクトURLの転送が必要です(以下参照)。 |
| Afterpay / Clearpay | Info.plistに登録されたカスタムURLスキーム + urlSchemeに一致するRoktPaymentExtension + リダイレクトURLの転送(以下参照)。 |
| カード転送 | パートナー支払い共有API + partnerpaymentreference / last4digits属性をselectShoppableAdsで使用します。 |
mParticle Rokt kit の設定で stripePublishableKey を設定します。このキーは自動的に Rokt に転送されます。Apple Pay はオプションです — Shoppable Ads は Apple Pay マーチャント ID なしでも、内蔵の PayPal およびカード転送をサポートしています。拡張機能を作成する際には、applePayMerchantId または urlScheme のいずれかを必ず提供する必要があります。
RoktPaymentExtension は Swift タイプであるため、Swift で作成および登録されます(Step 2 の Swift タブを参照)。Objective-C アプリの場合、小さな Swift ファイルからこれを行います。残りのフロー(selectShoppableAds, handleURLCallback)は Objective-C から利用可能です。
Apple Pay(オプション)Apple Pay(オプション) への直接リンク
Apple Pay を提供するには、Apple Pay マーチャント ID を作成し、Xcode プロジェクトを設定し、Payment Processing Certificate を生成します。Apple Pay — iOS setup の手順に従い、applePayMerchantId としてマーチャント ID を RoktPaymentExtension 作成時に渡します。
Afterpay / Clearpay(オプション)Afterpay / Clearpay(オプション) への直接リンク
Afterpay および Clearpay はリダイレクトベースです。これらを有効にするには:
- アプリの
Info.plistにCFBundleURLTypesの下で URL スキームを登録します(例:myapp)。 RoktPaymentExtension作成時に一致するurlSchemeを渡します(例:"myapp")。SDK は内部でリターン URL を構築します。- リダイレクト URL を Rokt に転送します — 以下を参照。
リダイレクト URL の転送リダイレクト URL の転送 への直接リンク
Afterpay、Clearpay、および PayPal は、顧客を Web ビューに送り、登録された URL スキームを介してアプリにリダイレクトします。既存の mParticle URL ハンドリングに加えて、handleURLCallback を使用して Rokt に受信 URL を転送します。
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
if MParticle.sharedInstance().rokt.handleURLCallback(with: urlContext.url) {
return
}
MParticle.sharedInstance().handleURLContext(urlContext)
}
}
WindowGroup {
ContentView()
.onOpenURL { url in
_ = MParticle.sharedInstance().rokt.handleURLCallback(with: url)
}
}
8. Test Your Integration#
SDK+ が正しく初期化され、イベントが正しくログに記録されることを確認するには:
1Enable verbose SDK+ logging#
初期化前に詳細な SDK+ ロギングを有効にして、送信されている内容を確認します。
Rokt.setLoggingEnabled(enable: true)
2Build and run against a development key#
開発キーでアプリをビルドして実行し、environment = .development(または MPEnvironmentDevelopment)を使用します。
3Trigger selectPlacements#
配置がレンダリングされるべき画面で selectPlacements をトリガーし、配置が読み込まれることを確認します。
4Verify events#
イベントがログに記録され、identifyRequest 呼び出しが成功することを確認します。
トラブルシューティングトラブルシューティング への直接リンク
配置がレンダリングされない、またはイベントが表示されない場合は、Xcode コンソールで Rokt SDK+ のエラーを確認してください。一般的な問題は以下の通りです:
初期化エラー初期化エラー への直接リンク
keyとsecretが Rokt アカウントマネージャーからの値と一致していることを確認してください。MParticle.sharedInstance().start(with: options)がselectPlacementsやlogEventの呼び出しの前に実行されていることを確認してください。- ショッパブル広告の場合、
RoktPaymentExtensionがstart()の後、selectShoppableAdsの前に登録されていることを確認してください。PayPal または Afterpay / Clearpay を使用している場合は、handleURLCallbackが URL ハンドラーに組み込まれていることを確認してください。
アイデンティティエラーアイデンティティエラー への直接リンク
onIdentifyComplete またはアイデンティティコールバックがエラーで発火し、ユーザーが返されない場合は、エラーハンドリング を参照して MPIdentityErrorResponseCode の値と再試行ガイダンスを確認してください。エラーハンドリングがないと、大規模なデータ整合性の問題が発生する可能性があります。
配置がレンダリングされない配置がレンダリングされない への直接リンク
- 配置の
identifier(例:RoktExperience)が Rokt アカウントマネージャーが設定したものと一致していることを確認してください。 - 埋め込み配置の場合、埋め込みビュー識別子(例:
RoktEmbedded1)がレイアウト設定と一致していることを確認してください。 - 属性辞書に少なくとも
email、firstname、lastname、billingzipcode、confirmationrefが含まれていることを確認してください。
プロキシ使用時のSSLハンドシェイクエラープロキシ使用時のSSLハンドシェイクエラー への直接リンク
開発環境でテスト中に、Charles や Proxyman などの HTTP デバッグプロキシが実行されている場合、または企業ネットワークプロキシの背後にいる場合、SSL ハンドシェイクエラーが発生することがあります。SDK+ が現在のユーザーを識別しようとすると、これは MPIdentityErrorResponseCodeSSLError として報告されます(エラーハンドリング を参照)。これは予期された動作です:SDK+ はその SSL 証明書をピン留めしており、プロキシは独自の証明書を提示することで HTTPS を傍受し、ピン留めに失敗します。
プロキシが SDK+ トラフィックを検査できるようにするには、pinningDisabledInDevelopment を MPNetworkOptions に設定して開発ビルドでピン留めを無効にします。SDK+ 初期化スクリプト を参照してください。
let networkOptions = MPNetworkOptions()
// Only takes effect in the development environment; production builds stay pinned.
networkOptions.pinningDisabledInDevelopment = true
options.networkOptions = networkOptions