fix:1、接入外部sdk

This commit is contained in:
2026-05-20 14:29:11 +08:00
parent aca0e4d1af
commit d8b41f25ba
890 changed files with 45707 additions and 1095 deletions
+2 -7
View File
@@ -10,24 +10,19 @@ namespace AppsFlyerSDK
}
/// <summary>
//
/// Purchase details class matching Android SDK AFPurchaseDetails
/// </summary>
public class AFPurchaseDetailsAndroid
{
public AFPurchaseType purchaseType { get; private set; }
public string purchaseToken { get; private set; }
public string productId { get; private set; }
public string price { get; private set; }
public string currency { get; private set; }
public AFPurchaseDetailsAndroid(AFPurchaseType type, String purchaseToken, String productId, String price, String currency)
public AFPurchaseDetailsAndroid(AFPurchaseType type, String purchaseToken, String productId)
{
this.purchaseType = type;
this.purchaseToken = purchaseToken;
this.productId = productId;
this.price = price;
this.currency = currency;
}
}
+15 -8
View File
@@ -4,26 +4,33 @@ using System.Collections.Generic;
namespace AppsFlyerSDK
{
/// <summary>
//
/// Purchase type enum matching iOS SDK AFSDKPurchaseType
/// </summary>
public enum AFSDKPurchaseType
{
Subscription,
OneTimePurchase
}
/// <summary>
/// Purchase details class matching iOS SDK AFSDKPurchaseDetails
/// </summary>
public class AFSDKPurchaseDetailsIOS
{
public string productId { get; private set; }
public string price { get; private set; }
public string currency { get; private set; }
public string transactionId { get; private set; }
public AFSDKPurchaseType purchaseType { get; private set; }
private AFSDKPurchaseDetailsIOS(string productId, string price, string currency, string transactionId)
private AFSDKPurchaseDetailsIOS(string productId, string transactionId, AFSDKPurchaseType purchaseType)
{
this.productId = productId;
this.price = price;
this.currency = currency;
this.transactionId = transactionId;
this.purchaseType = purchaseType;
}
public static AFSDKPurchaseDetailsIOS Init(string productId, string price, string currency, string transactionId)
public static AFSDKPurchaseDetailsIOS Init(string productId, string transactionId, AFSDKPurchaseType purchaseType)
{
return new AFSDKPurchaseDetailsIOS(productId, price, currency, transactionId);
return new AFSDKPurchaseDetailsIOS(productId, transactionId, purchaseType);
}
}
+21 -7
View File
@@ -6,7 +6,7 @@ namespace AppsFlyerSDK
{
public class AppsFlyer : MonoBehaviour
{
public static readonly string kAppsFlyerPluginVersion = "6.16.21";
public static readonly string kAppsFlyerPluginVersion = "6.17.91";
public static string CallBackObjectName = null;
private static EventHandler onRequestResponse;
private static EventHandler onInAppResponse;
@@ -768,6 +768,11 @@ namespace AppsFlyerSDK
}
}
/// <summary>
/// [Deprecated] Validates an in-app purchase on iOS.
/// Use the V2 overload with AFSDKPurchaseDetailsIOS instead.
/// </summary>
[System.Obsolete("This method is deprecated. Use validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject) instead.")]
public static void validateAndSendInAppPurchase(string productIdentifier, string price, string currency, string transactionId, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject)
{
if (instance != null && instance is IAppsFlyerIOSBridge)
@@ -777,16 +782,23 @@ namespace AppsFlyerSDK
}
}
// V2
public static void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary<string, string> extraEventValues, MonoBehaviour gameObject)
/// <summary>
/// Validates an in-app purchase on iOS using the V2 API.
/// </summary>
public static void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject)
{
if (instance != null && instance is IAppsFlyerIOSBridge)
{
IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance;
appsFlyeriOSInstance.validateAndSendInAppPurchase(details, extraEventValues, gameObject);
appsFlyeriOSInstance.validateAndSendInAppPurchase(details, purchaseAdditionalDetails, gameObject);
}
}
/// <summary>
/// [Deprecated] Validates an in-app purchase on Android.
/// Use the V2 overload with AFPurchaseDetailsAndroid instead.
/// </summary>
[System.Obsolete("This method is deprecated. Use validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject) instead.")]
public static void validateAndSendInAppPurchase(string publicKey, string signature, string purchaseData, string price, string currency, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject)
{
if (instance != null && instance is IAppsFlyerAndroidBridge)
@@ -796,13 +808,15 @@ namespace AppsFlyerSDK
}
}
// V2
public static void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject)
/// <summary>
/// Validates an in-app purchase on Android using the V2 API.
/// </summary>
public static void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject)
{
if (instance != null && instance is IAppsFlyerAndroidBridge)
{
IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance;
appsFlyerAndroidInstance.validateAndSendInAppPurchase(details, additionalParameters, gameObject);
appsFlyerAndroidInstance.validateAndSendInAppPurchase(details, purchaseAdditionalDetails, gameObject);
}
}
+6 -5
View File
@@ -484,7 +484,7 @@ namespace AppsFlyerSDK
}
/// <summary>
/// API for server verification of in-app purchases.
/// [Deprecated] API for server verification of in-app purchases - please use V2 with AFPurchaseDetailsAndroid instead.
/// An af_purchase event with the relevant values will be automatically sent if the validation is successful.
/// </summary>
/// <param name="publicKey">License Key obtained from the Google Play Console.</param>
@@ -493,6 +493,7 @@ namespace AppsFlyerSDK
/// <param name="price">Purchase price, should be derived from <code>skuDetails.getStringArrayList("DETAILS_LIST")</code></param>
/// <param name="currency">Purchase currency, should be derived from <code>skuDetails.getStringArrayList("DETAILS_LIST")</code></param>
/// <param name="additionalParameters">additionalParameters Freehand parameters to be sent with the purchase (if validated).</param>
[System.Obsolete("This method is deprecated. Use validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject) instead.")]
public void validateAndSendInAppPurchase(string publicKey, string signature, string purchaseData, string price, string currency, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject)
{
#if !UNITY_EDITOR
@@ -501,15 +502,15 @@ namespace AppsFlyerSDK
}
/// <summary>
/// API for server verification of in-app purchases.
/// V2 - API for server verification of in-app purchases.
/// An af_purchase event with the relevant values will be automatically sent if the validation is successful.
/// </summary>
/// <param name="details">AFPurchaseDetailsAndroid instance.</param>
/// <param name="additionalParameters">additionalParameters Freehand parameters to be sent with the purchase (if validated).</param>
public void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject)
/// <param name="purchaseAdditionalDetails">purchaseAdditionalDetails Freehand parameters to be sent with the purchase (if validated).</param>
public void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject)
{
#if !UNITY_EDITOR
appsFlyerAndroid.CallStatic("validateAndTrackInAppPurchaseV2", (int)details.purchaseType, details.purchaseToken, details.productId, details.price, details.currency, convertDictionaryToJavaMap(additionalParameters), gameObject ? gameObject.name : null);
appsFlyerAndroid.CallStatic("validateAndTrackInAppPurchaseV2", (int)details.purchaseType, details.purchaseToken, details.productId, convertDictionaryToJavaMap(purchaseAdditionalDetails), gameObject ? gameObject.name : null);
#endif
}
+7 -7
View File
@@ -335,13 +335,14 @@ public void startSDK(bool shouldCallback, string CallBackObjectName)
}
/// <summary>
/// To send and validate in app purchases you can call this method from the processPurchase method - please use v2.
/// [Deprecated] To send and validate in app purchases - please use V2 with AFSDKPurchaseDetailsIOS instead.
/// </summary>
/// <param name="productIdentifier">The product identifier.</param>
/// <param name="price">The product price.</param>
/// <param name="currency">The product currency.</param>
/// <param name="transactionId">The purchase transaction Id.</param>
/// <param name="additionalParameters">The additional param, which you want to receive it in the raw reports.</param>
[System.Obsolete("This method is deprecated. Use validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject) instead.")]
public void validateAndSendInAppPurchase(string productIdentifier, string price, string currency, string transactionId, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject)
{
#if !UNITY_EDITOR
@@ -350,15 +351,14 @@ public void startSDK(bool shouldCallback, string CallBackObjectName)
}
/// <summary>
/// V2
/// To send and validate in app purchases you can call this method from the processPurchase method.
/// V2 - To send and validate in app purchases you can call this method from the processPurchase method.
/// </summary>
/// <param name="details">The AFSDKPurchaseDetailsIOS instance.</param>
/// <param name="extraEventValues">The extra params, which you want to receive it in the raw reports.</param>
public void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary<string, string> extraEventValues, MonoBehaviour gameObject)
/// <param name="purchaseAdditionalDetails">The additional params, which you want to receive it in the raw reports.</param>
public void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject)
{
#if !UNITY_EDITOR
_validateAndSendInAppPurchaseV2(details.productId, details.price, details.currency, details.transactionId, AFMiniJSON.Json.Serialize(extraEventValues), gameObject ? gameObject.name : null);
_validateAndSendInAppPurchaseV2(details.productId, details.transactionId, (int)details.purchaseType, AFMiniJSON.Json.Serialize(purchaseAdditionalDetails), gameObject ? gameObject.name : null);
#endif
}
@@ -843,7 +843,7 @@ public void startSDK(bool shouldCallback, string CallBackObjectName)
#elif UNITY_STANDALONE_OSX
[DllImport("AppsFlyerBundle")]
#endif
private static extern void _validateAndSendInAppPurchaseV2(string product, string price, string currency, string transactionId, string extraEventValues, string objectName);
private static extern void _validateAndSendInAppPurchaseV2(string product, string transactionId, int purchaseType, string purchaseAdditionalDetails, string objectName);
#if UNITY_IOS
[DllImport("__Internal")]
@@ -2,17 +2,15 @@
<dependencies>
<androidPackages>
<androidPackage spec="com.appsflyer:af-android-sdk:6.16.2">
</androidPackage>
<androidPackage spec="com.appsflyer:unity-wrapper:6.16.21">
</androidPackage>
<androidPackage spec="com.android.installreferrer:installreferrer:2.1">
</androidPackage>
<androidPackage spec="com.appsflyer:af-android-sdk:6.17.6"></androidPackage>
<androidPackage spec="com.appsflyer:unity-wrapper:6.17.91"></androidPackage>
<androidPackage spec="com.android.installreferrer:installreferrer:2.1"></androidPackage>
<androidPackage spec="com.appsflyer:purchase-connector:2.2.0"></androidPackage>
</androidPackages>
<iosPods>
<iosPod name="AppsFlyerFramework" version="6.16.2" minTargetSdk="12.0">
</iosPod>
<iosPod name="AppsFlyerFramework" version="6.17.9" minTargetSdk="12.0"></iosPod>
<iosPod name="PurchaseConnector" version="6.17.9" minTargetSdk="12.0"></iosPod>
</iosPods>
</dependencies>
@@ -31,7 +31,7 @@ public class AppsFlyerObjectEditor : Editor
{
serializedObject.Update();
GUILayout.Box((Texture)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(AssetDatabase.FindAssets("appsflyer_logo")[0]), typeof(Texture)), new GUILayoutOption[] { GUILayout.Width(600) });
DrawLogo();
EditorGUILayout.Separator();
EditorGUILayout.HelpBox("Set your devKey and appID to init the AppsFlyer SDK and start tracking. You must modify these fields and provide:\ndevKey - Your application devKey provided by AppsFlyer.\nappId - For iOS only. Your iTunes Application ID.\nUWP app id - For UWP only. Your application app id \nMac OS app id - For MacOS app only.", MessageType.Info);
@@ -80,5 +80,25 @@ public class AppsFlyerObjectEditor : Editor
serializedObject.ApplyModifiedProperties();
}
private void DrawLogo()
{
var guids = AssetDatabase.FindAssets("appsflyer_logo");
if (guids.Length == 0) return;
Texture logo = (Texture)AssetDatabase.LoadAssetAtPath(
AssetDatabase.GUIDToAssetPath(guids[0]),
typeof(Texture));
if (logo == null) return;
float maxWidth = Mathf.Min(200, EditorGUIUtility.currentViewWidth - 40);
float aspect = (float)logo.height / logo.width;
float height = maxWidth * aspect;
Rect rect = GUILayoutUtility.GetRect(maxWidth, height, GUILayout.ExpandWidth(false));
rect.x = (EditorGUIUtility.currentViewWidth - maxWidth) * 0.5f;
rect.width = maxWidth;
GUI.DrawTexture(rect, logo, ScaleMode.ScaleToFit);
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 7.0 KiB

+1 -1
View File
@@ -22,7 +22,7 @@ namespace AppsFlyerSDK
string getAttributionId();
void handlePushNotifications();
void validateAndSendInAppPurchase(string publicKey, string signature, string purchaseData, string price, string currency, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject);
void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject);
void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject);
void setCollectOaid(bool isCollect);
void setDisableAdvertisingIdentifiers(bool disable);
void setDisableNetworkData(bool disable);
+1 -1
View File
@@ -14,7 +14,7 @@ namespace AppsFlyerSDK
void setUseReceiptValidationSandbox(bool useReceiptValidationSandbox);
void setUseUninstallSandbox(bool useUninstallSandbox);
void validateAndSendInAppPurchase(string productIdentifier, string price, string currency, string transactionId, Dictionary<string, string> additionalParameters, MonoBehaviour gameObject);
void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary<string, string> extraEventValues, MonoBehaviour gameObject);
void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary<string, string> purchaseAdditionalDetails, MonoBehaviour gameObject);
void registerUninstall(byte[] deviceToken);
void handleOpenUrl(string url, string sourceApplication, string annotation);
void waitForATTUserAuthorizationWithTimeoutInterval(int timeoutInterval);
@@ -0,0 +1,79 @@
import Foundation
import StoreKit
#if canImport(PurchaseConnector)
import PurchaseConnector
@available(iOS 15.0, *)
@objc
public class AFUnityStoreKit2Bridge: NSObject {
@objc
public static func fetchAFSDKTransactionSK2(withTransactionId transactionId: String, completion: @escaping (AFSDKTransactionSK2?) -> Void) {
guard let transactionIdUInt64 = UInt64(transactionId) else {
print("Invalid transaction ID format.")
completion(nil)
return
}
Task {
for await result in StoreKit.Transaction.all {
if case .verified(let transaction) = result, transaction.id == transactionIdUInt64 {
let afTransaction = AFSDKTransactionSK2(transaction: transaction)
DispatchQueue.main.async {
completion(afTransaction)
}
return
}
}
DispatchQueue.main.async {
completion(nil)
}
}
}
@objc
public static func extractSK2ProductInfo(_ products: [AFSDKProductSK2]) -> NSArray {
var result: [[String: Any]] = []
for product in products {
if let swiftProduct = Mirror(reflecting: product).children.first(where: { $0.label == "product" })?.value {
let productId = (swiftProduct as? NSObject)?.value(forKey: "id") as? String ?? ""
let title = (swiftProduct as? NSObject)?.value(forKey: "displayName") as? String ?? ""
let desc = (swiftProduct as? NSObject)?.value(forKey: "description") as? String ?? ""
let price = (swiftProduct as? NSObject)?.value(forKey: "price") as? NSDecimalNumber ?? 0
result.append([
"productIdentifier": productId,
"localizedTitle": title,
"localizedDescription": desc,
"price": price
])
}
}
return result as NSArray
}
@objc
public static func extractSK2TransactionInfo(_ transactions: [AFSDKTransactionSK2]) -> NSArray {
var result: [[String: Any]] = []
for txn in transactions {
guard let mirrorChild = Mirror(reflecting: txn).children.first(where: { $0.label == "transaction" }),
let swiftTxn = mirrorChild.value as? StoreKit.Transaction else {
continue
}
let transactionId = "\(swiftTxn.id)"
let date = NSNumber(value: swiftTxn.purchaseDate.timeIntervalSince1970)
result.append([
"transactionIdentifier": transactionId,
"transactionState": "verified", // or skip this line
"transactionDate": date
])
}
return result as NSArray
}
}
#endif
@@ -0,0 +1,42 @@
fileFormatVersion: 2
guid: 5652805602a6b4273a6e527b00aea272
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
- first:
VisionOS: VisionOS
second:
enabled: 1
settings: {}
- first:
iPhone: iOS
second:
enabled: 1
settings: {}
- first:
tvOS: tvOS
second:
enabled: 1
settings: {}
userData:
assetBundleName:
assetBundleVariant:
+16 -8
View File
@@ -34,14 +34,22 @@ static const char* stringFromdictionary(NSDictionary* dictionary) {
static NSDictionary* dictionaryFromNSError(NSError* error) {
if(error){
NSInteger code = [error code];
NSString *localizedDescription = [error localizedDescription];
NSDictionary *errorDictionary = @{
@"code" : @(code) ?: @(-1),
@"localizedDescription" : localizedDescription,
};
return errorDictionary;
NSMutableDictionary *errorDictionary = [NSMutableDictionary dictionary];
errorDictionary[@"code"] = @(error.code);
errorDictionary[@"localizedDescription"] = error.localizedDescription ?: @"";
// Include userInfo fields for enhanced error reporting (iOS SDK 6.17.8+)
if (error.userInfo[@"error_code"]) {
errorDictionary[@"error_code"] = error.userInfo[@"error_code"];
}
if (error.userInfo[@"error_message"]) {
errorDictionary[@"error_message"] = error.userInfo[@"error_message"];
}
if (error.userInfo[@"invalid_fields"]) {
errorDictionary[@"invalid_fields"] = error.userInfo[@"invalid_fields"];
}
return errorDictionary;
}
return nil;
@@ -10,15 +10,30 @@
#import "AppsFlyerAttribution.h"
#if __has_include(<AppsFlyerLib/AppsFlyerLib.h>)
#import <AppsFlyerLib/AppsFlyerLib.h>
#import "AppsFlyerLib/AppsFlyerLib-Swift.h"
#else
#import "AppsFlyerLib.h"
#import "AppsFlyerLib-Swift.h"
#endif
#if __has_include(<PurchaseConnector/PurchaseConnector.h>)
#import <PurchaseConnector/PurchaseConnector.h>
#else
#import "PurchaseConnector.h"
#endif
#import <PurchaseConnector/PurchaseConnector-Swift.h>
// Add StoreKit 2 support
#if __has_include(<StoreKit/StoreKit.h>)
#import <StoreKit/StoreKit.h>
#endif
@interface AppsFlyeriOSWarpper : NSObject <AppsFlyerLibDelegate, AppsFlyerDeepLinkDelegate>
@interface AppsFlyeriOSWarpper : NSObject <AppsFlyerLibDelegate, AppsFlyerDeepLinkDelegate, AppsFlyerPurchaseRevenueDelegate, AppsFlyerPurchaseRevenueDataSource, AppsFlyerPurchaseRevenueDataSourceStoreKit2>
+ (BOOL) didCallStart;
+ (void) setDidCallStart:(BOOL)val;
// Add StoreKit 2 methods
- (void)setStoreKitVersion:(int)storeKitVersion;
- (void)logConsumableTransaction:(id)transaction;
@end
@@ -50,3 +65,7 @@ static NSString* startRequestObjectName = @"";
static NSString* inAppRequestObjectName = @"";
static NSString* onDeeplinkingObjectName = @"";
static const char* PURCHASE_REVENUE_VALIDATION_CALLBACK = "didReceivePurchaseRevenueValidationInfo";
static const char* PURCHASE_REVENUE_ERROR_CALLBACK = "didReceivePurchaseRevenueError";
static NSString* onPurchaseValidationObjectName = @"";
@@ -6,7 +6,22 @@
//
#import "AppsFlyeriOSWrapper.h"
#import <objc/runtime.h>
#import <StoreKit/StoreKit.h>
#import "UnityFramework/UnityFramework-Swift.h"
#if __has_include(<PurchaseConnector/PurchaseConnector-Swift.h>)
#import <PurchaseConnector/PurchaseConnector-Swift.h>
#elif __has_include("PurchaseConnector-Swift.h")
#import "PurchaseConnector-Swift.h"
#endif
#if __has_include(<UnityFramework/UnityFramework-Swift.h>)
#import <UnityFramework/UnityFramework-Swift.h>
#elif __has_include("UnityFramework-Swift.h")
#import "UnityFramework-Swift.h"
#endif
static void unityCallBack(NSString* objectName, const char* method, const char* msg) {
if(objectName){
@@ -18,7 +33,7 @@ extern "C" {
const void _startSDK(bool shouldCallback, const char* objectName) {
[[AppsFlyerLib shared] setPluginInfoWith: AFSDKPluginUnity
pluginVersion:@"6.16.21"
pluginVersion:@"6.17.91"
additionalParams:nil];
startRequestObjectName = stringFromChar(objectName);
AppsFlyeriOSWarpper.didCallStart = YES;
@@ -273,21 +288,19 @@ extern "C" {
}];
}
const void _validateAndSendInAppPurchaseV2 (const char* product, const char* price, const char* currency, const char* transactionId, const char* extraEventValues, const char* objectName) {
const void _validateAndSendInAppPurchaseV2 (const char* product, const char* transactionId, int purchaseType, const char* purchaseAdditionalDetails, const char* objectName) {
validateAndLogObjectName = stringFromChar(objectName);
AFSDKPurchaseDetails *details = [[AFSDKPurchaseDetails alloc] initWithProductId:stringFromChar(product) price:stringFromChar(price) currency:stringFromChar(currency) transactionId:stringFromChar(transactionId)];
AFSDKPurchaseDetails *details = [[AFSDKPurchaseDetails alloc] initWithProductId:stringFromChar(product) transactionId:stringFromChar(transactionId) purchaseType:(AFSDKPurchaseType)purchaseType];
[[AppsFlyerLib shared]
validateAndLogInAppPurchase:details
extraEventValues:dictionaryFromJson(extraEventValues)
completionHandler:^(AFSDKValidateAndLogResult * _Nullable result) {
if (result.status == AFSDKValidateAndLogStatusSuccess) {
unityCallBack(validateAndLogObjectName, VALIDATE_AND_LOG_V2_CALLBACK, stringFromdictionary(result.result));
} else if (result.status == AFSDKValidateAndLogStatusFailure) {
unityCallBack(validateAndLogObjectName, VALIDATE_AND_LOG_V2_CALLBACK, stringFromdictionary(result.errorData));
purchaseAdditionalDetails:dictionaryFromJson(purchaseAdditionalDetails)
completion:^(NSDictionary * _Nullable response, NSError * _Nullable error) {
if (error) {
unityCallBack(validateAndLogObjectName, VALIDATE_AND_LOG_V2_ERROR_CALLBACK, stringFromdictionary(dictionaryFromNSError(error)));
} else {
unityCallBack(validateAndLogObjectName, VALIDATE_AND_LOG_V2_ERROR_CALLBACK, stringFromdictionary(dictionaryFromNSError(result.error)));
unityCallBack(validateAndLogObjectName, VALIDATE_AND_LOG_V2_CALLBACK, stringFromdictionary(response));
}
}];
@@ -337,6 +350,97 @@ extern "C" {
[AppsFlyerLib shared].disableIDFVCollection = isDisabled;
}
// Purchase connector
const void _startObservingTransactions() {
[[PurchaseConnector shared] startObservingTransactions];
}
const void _stopObservingTransactions() {
[[PurchaseConnector shared] stopObservingTransactions];
}
const void _setIsSandbox(bool isSandBox) {
[[PurchaseConnector shared] setIsSandbox:isSandBox];
}
const void _setPurchaseRevenueDelegate() {
if (_AppsFlyerdelegate== nil) {
_AppsFlyerdelegate = [[AppsFlyeriOSWarpper alloc] init];
}
[[PurchaseConnector shared] setPurchaseRevenueDelegate:_AppsFlyerdelegate];
}
const void _setAutoLogPurchaseRevenue(int option) {
[[PurchaseConnector shared] setAutoLogPurchaseRevenue:option];
}
const void _initPurchaseConnector(const char* objectName) {
if (_AppsFlyerdelegate == nil) {
_AppsFlyerdelegate = [[AppsFlyeriOSWarpper alloc] init];
}
onPurchaseValidationObjectName = stringFromChar(objectName);
}
const void _setPurchaseRevenueDataSource(const char* objectName) {
if (_AppsFlyerdelegate == nil) {
_AppsFlyerdelegate = [[AppsFlyeriOSWarpper alloc] init];
}
if (strstr(objectName, "StoreKit2") != NULL) {
// Force protocol conformance
Protocol *sk2Protocol = @protocol(AppsFlyerPurchaseRevenueDataSourceStoreKit2);
class_addProtocol([_AppsFlyerdelegate class], sk2Protocol);
if (![_AppsFlyerdelegate conformsToProtocol:@protocol(AppsFlyerPurchaseRevenueDataSourceStoreKit2)]) {
NSLog(@"[AppsFlyer] Warning: SK2 protocol not conformed!");
}
}
[PurchaseConnector shared].purchaseRevenueDataSource = _AppsFlyerdelegate;
}
const void _setStoreKitVersion(int storeKitVersion) {
[[PurchaseConnector shared] setStoreKitVersion:(AFSDKStoreKitVersion)storeKitVersion];
}
const void _logConsumableTransaction(const char* transactionId) {
if (@available(iOS 15.0, *)) {
NSString *transactionIdStr = [NSString stringWithUTF8String:transactionId];
[AFUnityStoreKit2Bridge fetchAFSDKTransactionSK2WithTransactionId:transactionIdStr completion:^(AFSDKTransactionSK2 *afTransaction) {
if (afTransaction) {
[[PurchaseConnector shared] logConsumableTransaction:afTransaction];
} else {
NSLog(@"No AFSDKTransactionSK2 found for id %@", transactionIdStr);
}
}];
}
}
#ifdef __cplusplus
extern "C" {
#endif
typedef const char *(*UnityPurchaseCallback)(const char *, const char *);
UnityPurchaseCallback UnityPurchasesGetAdditionalParamsCallback = NULL;
UnityPurchaseCallback UnityPurchasesGetAdditionalParamsCallbackSK2 = NULL;
__attribute__((visibility("default")))
void RegisterUnityPurchaseRevenueParamsCallback(UnityPurchaseCallback callback) {
UnityPurchasesGetAdditionalParamsCallback = callback;
}
__attribute__((visibility("default")))
void RegisterUnityPurchaseRevenueParamsCallbackSK2(UnityPurchaseCallback callback) {
UnityPurchasesGetAdditionalParamsCallbackSK2 = callback;
}
#ifdef __cplusplus
}
#endif
}
@implementation AppsFlyeriOSWarpper
@@ -378,5 +482,120 @@ static BOOL didCallStart;
unityCallBack(onDeeplinkingObjectName, ON_DEEPLINKING, stringFromdictionary(dict));
}
// Purchase Connector
- (void)didReceivePurchaseRevenueValidationInfo:(NSDictionary *)validationInfo error:(NSError *)error {
if (error != nil) {
unityCallBack(onPurchaseValidationObjectName, PURCHASE_REVENUE_ERROR_CALLBACK, [[error localizedDescription] UTF8String]);
} else {
unityCallBack(onPurchaseValidationObjectName, PURCHASE_REVENUE_VALIDATION_CALLBACK, stringFromdictionary(validationInfo));
}
}
- (NSDictionary *)purchaseRevenueAdditionalParametersForProducts:(NSSet<SKProduct *> *)products
transactions:(NSSet<SKPaymentTransaction *> *)transactions {
NSMutableArray *productsArray = [NSMutableArray array];
for (SKProduct *product in products) {
[productsArray addObject:@{
@"productIdentifier": product.productIdentifier ?: @"",
@"localizedTitle": product.localizedTitle ?: @"",
@"localizedDescription": product.localizedDescription ?: @"",
@"price": [product.price stringValue] ?: @""
}];
}
NSMutableArray *transactionsArray = [NSMutableArray array];
for (SKPaymentTransaction *txn in transactions) {
[transactionsArray addObject:@{
@"transactionIdentifier": txn.transactionIdentifier ?: @"",
@"transactionState": @(txn.transactionState),
@"transactionDate": txn.transactionDate ? [@(txn.transactionDate.timeIntervalSince1970) stringValue] : @""
}];
}
NSDictionary *input = @{
@"products": productsArray,
@"transactions": transactionsArray
};
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:input options:0 error:&error];
if (error || !jsonData) {
NSLog(@"[AppsFlyer] Failed to serialize Unity purchase data: %@", error);
return @{};
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (!jsonString || !UnityPurchasesGetAdditionalParamsCallback) {
NSLog(@"[AppsFlyer] Unity callback not registered");
return @{};
}
const char *resultCStr = UnityPurchasesGetAdditionalParamsCallback([jsonString UTF8String], "");
if (!resultCStr) {
NSLog(@"[AppsFlyer] Unity callback returned null");
return @{};
}
NSString *resultJson = [NSString stringWithUTF8String:resultCStr];
NSData *resultData = [resultJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *parsedResult = [NSJSONSerialization JSONObjectWithData:resultData options:0 error:&error];
if (error || ![parsedResult isKindOfClass:[NSDictionary class]]) {
NSLog(@"[AppsFlyer] Failed to parse Unity response: %@", error);
return @{};
}
return parsedResult;
}
#pragma mark - AppsFlyerPurchaseRevenueDataSourceStoreKit2
- (NSDictionary *)purchaseRevenueAdditionalParametersStoreKit2ForProducts:(NSSet<AFSDKProductSK2 *> *)products transactions:(NSSet<AFSDKTransactionSK2 *> *)transactions {
if (@available(iOS 15.0, *)) {
NSArray *productInfoArray = [AFUnityStoreKit2Bridge extractSK2ProductInfo:[products allObjects]];
NSArray *transactionInfoArray = [AFUnityStoreKit2Bridge extractSK2TransactionInfo:[transactions allObjects]];
NSDictionary *input = @{
@"products": productInfoArray,
@"transactions": transactionInfoArray
};
if (UnityPurchasesGetAdditionalParamsCallbackSK2) {
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:input options:0 error:&error];
if (error || !jsonData) {
NSLog(@"[AppsFlyer] Failed to serialize Unity purchase data: %@", error);
return @{};
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
const char *resultCStr = UnityPurchasesGetAdditionalParamsCallbackSK2([jsonString UTF8String], "");
if (!resultCStr) {
NSLog(@"[AppsFlyer] Unity callback returned null");
return @{};
}
NSString *resultJson = [NSString stringWithUTF8String:resultCStr];
NSData *resultData = [resultJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *parsedResult = [NSJSONSerialization JSONObjectWithData:resultData options:0 error:&error];
if (error || ![parsedResult isKindOfClass:[NSDictionary class]]) {
NSLog(@"[AppsFlyer] Failed to parse Unity response: %@", error);
return @{};
}
return parsedResult;
} else {
NSLog(@"[AppsFlyer] SK2 - Unity callback is NOT registered");
}
} else {
NSLog(@"[AppsFlyer] SK2 - iOS version not supported");
}
return @{};
}
@end
+145 -145
View File
@@ -1,145 +1,145 @@
//#define AFSDK_WIN_DEBUG
//#define UNITY_WSA_10_0
//#define ENABLE_WINMD_SUPPORT
#if UNITY_WSA_10_0
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.ComponentModel;
using UnityEngine;
using System.Threading.Tasks;
#if ENABLE_WINMD_SUPPORT
using AppsFlyerLib;
#endif
namespace AppsFlyerSDK
{
public class AppsFlyerWindows
{
#if ENABLE_WINMD_SUPPORT
static private MonoBehaviour _gameObject = null;
#endif
public static void InitSDK(string devKey, string appId, MonoBehaviour gameObject)
{
#if ENABLE_WINMD_SUPPORT
#if AFSDK_WIN_DEBUG
// Remove callstack
Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
#endif
Log("[InitSDK]: devKey: {0}, appId: {1}, gameObject: {2}", devKey, appId, gameObject == null ? "null" : gameObject.ToString());
AppsFlyerTracker tracker = AppsFlyerTracker.GetAppsFlyerTracker();
tracker.devKey = devKey;
tracker.appId = appId;
// Interface
_gameObject = gameObject;
#endif
}
public static string GetAppsFlyerId()
{
#if ENABLE_WINMD_SUPPORT
Log("[GetAppsFlyerId]");
return AppsFlyerTracker.GetAppsFlyerTracker().GetAppsFlyerUID();
#else
return "";
#endif
}
public static void SetCustomerUserId(string customerUserId)
{
#if ENABLE_WINMD_SUPPORT
Log("[SetCustomerUserId] customerUserId: {0}", customerUserId);
if (customerUserId.Contains("test_device:"))
{
string testDeviceId = customerUserId.Substring(12);
AppsFlyerTracker.GetAppsFlyerTracker().testDeviceId = testDeviceId;
}
AppsFlyerTracker.GetAppsFlyerTracker().customerUserId = customerUserId;
#endif
}
public static void Start()
{
#if ENABLE_WINMD_SUPPORT
Log("[Start]");
AppsFlyerTracker.GetAppsFlyerTracker().TrackAppLaunchAsync(Callback);
#endif
}
#if ENABLE_WINMD_SUPPORT
public static void Callback(AppsFlyerLib.ServerStatusCode code)
{
Log("[Callback]: {0}", code.ToString());
AppsFlyerRequestEventArgs eventArgs = new AppsFlyerRequestEventArgs((int)code, code.ToString());
if (_gameObject != null) {
var method = _gameObject.GetType().GetMethod("AppsFlyerOnRequestResponse");
if (method != null) {
method.Invoke(_gameObject, new object[] { AppsFlyerTracker.GetAppsFlyerTracker(), eventArgs });
}
}
}
#endif
public static void LogEvent(string eventName, Dictionary<string, string> eventValues)
{
#if ENABLE_WINMD_SUPPORT
if (eventValues == null)
{
eventValues = new Dictionary<string, string>();
}
IDictionary<string, object> result = new Dictionary<string, object>();
foreach (KeyValuePair<string, string> kvp in eventValues)
{
result.Add(kvp.Key.ToString(), kvp.Value);
}
Log("[LogEvent]: eventName: {0} result: {1}", eventName, result.ToString());
AppsFlyerTracker tracker = AppsFlyerTracker.GetAppsFlyerTracker();
tracker.TrackEvent(eventName, result);
#endif
}
public static void GetConversionData(string _reserved)
{
#if ENABLE_WINMD_SUPPORT
Task.Run(async () =>
{
AppsFlyerLib.AppsFlyerTracker tracker = AppsFlyerLib.AppsFlyerTracker.GetAppsFlyerTracker();
string conversionData = await tracker.GetConversionDataAsync();
IAppsFlyerConversionData conversionDataHandler = _gameObject as IAppsFlyerConversionData;
if (conversionDataHandler != null)
{
Log("[GetConversionData] Will call `onConversionDataSuccess` with: {0}", conversionData);
conversionDataHandler.onConversionDataSuccess(conversionData);
} else {
Log("[GetConversionData] Object with `IAppsFlyerConversionData` interface not found! Check `InitSDK` implementation");
}
// _gameObject.GetType().GetMethod("onConversionDataSuccess").Invoke(_gameObject, new[] { conversionData });
});
#endif
}
private static void Log(string format, params string[] args)
{
#if AFSDK_WIN_DEBUG
#if ENABLE_WINMD_SUPPORT
Debug.Log("AF_UNITY_WSA_10_0" + String.Format(format, args));
#endif
#endif
}
}
}
#endif
//#define AFSDK_WIN_DEBUG
//#define UNITY_WSA_10_0
//#define ENABLE_WINMD_SUPPORT
#if UNITY_WSA_10_0
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.ComponentModel;
using UnityEngine;
using System.Threading.Tasks;
#if ENABLE_WINMD_SUPPORT
using AppsFlyerLib;
#endif
namespace AppsFlyerSDK
{
public class AppsFlyerWindows
{
#if ENABLE_WINMD_SUPPORT
static private MonoBehaviour _gameObject = null;
#endif
public static void InitSDK(string devKey, string appId, MonoBehaviour gameObject)
{
#if ENABLE_WINMD_SUPPORT
#if AFSDK_WIN_DEBUG
// Remove callstack
Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
#endif
Log("[InitSDK]: devKey: {0}, appId: {1}, gameObject: {2}", devKey, appId, gameObject == null ? "null" : gameObject.ToString());
AppsFlyerTracker tracker = AppsFlyerTracker.GetAppsFlyerTracker();
tracker.devKey = devKey;
tracker.appId = appId;
// Interface
_gameObject = gameObject;
#endif
}
public static string GetAppsFlyerId()
{
#if ENABLE_WINMD_SUPPORT
Log("[GetAppsFlyerId]");
return AppsFlyerTracker.GetAppsFlyerTracker().GetAppsFlyerUID();
#else
return "";
#endif
}
public static void SetCustomerUserId(string customerUserId)
{
#if ENABLE_WINMD_SUPPORT
Log("[SetCustomerUserId] customerUserId: {0}", customerUserId);
if (customerUserId.Contains("test_device:"))
{
string testDeviceId = customerUserId.Substring(12);
AppsFlyerTracker.GetAppsFlyerTracker().testDeviceId = testDeviceId;
}
AppsFlyerTracker.GetAppsFlyerTracker().customerUserId = customerUserId;
#endif
}
public static void Start()
{
#if ENABLE_WINMD_SUPPORT
Log("[Start]");
AppsFlyerTracker.GetAppsFlyerTracker().TrackAppLaunchAsync(Callback);
#endif
}
#if ENABLE_WINMD_SUPPORT
public static void Callback(AppsFlyerLib.ServerStatusCode code)
{
Log("[Callback]: {0}", code.ToString());
AppsFlyerRequestEventArgs eventArgs = new AppsFlyerRequestEventArgs((int)code, code.ToString());
if (_gameObject != null) {
var method = _gameObject.GetType().GetMethod("AppsFlyerOnRequestResponse");
if (method != null) {
method.Invoke(_gameObject, new object[] { AppsFlyerTracker.GetAppsFlyerTracker(), eventArgs });
}
}
}
#endif
public static void LogEvent(string eventName, Dictionary<string, string> eventValues)
{
#if ENABLE_WINMD_SUPPORT
if (eventValues == null)
{
eventValues = new Dictionary<string, string>();
}
IDictionary<string, object> result = new Dictionary<string, object>();
foreach (KeyValuePair<string, string> kvp in eventValues)
{
result.Add(kvp.Key.ToString(), kvp.Value);
}
Log("[LogEvent]: eventName: {0} result: {1}", eventName, result.ToString());
AppsFlyerTracker tracker = AppsFlyerTracker.GetAppsFlyerTracker();
tracker.TrackEvent(eventName, result);
#endif
}
public static void GetConversionData(string _reserved)
{
#if ENABLE_WINMD_SUPPORT
Task.Run(async () =>
{
AppsFlyerLib.AppsFlyerTracker tracker = AppsFlyerLib.AppsFlyerTracker.GetAppsFlyerTracker();
string conversionData = await tracker.GetConversionDataAsync();
IAppsFlyerConversionData conversionDataHandler = _gameObject as IAppsFlyerConversionData;
if (conversionDataHandler != null)
{
Log("[GetConversionData] Will call `onConversionDataSuccess` with: {0}", conversionData);
conversionDataHandler.onConversionDataSuccess(conversionData);
} else {
Log("[GetConversionData] Object with `IAppsFlyerConversionData` interface not found! Check `InitSDK` implementation");
}
// _gameObject.GetType().GetMethod("onConversionDataSuccess").Invoke(_gameObject, new[] { conversionData });
});
#endif
}
private static void Log(string format, params string[] args)
{
#if AFSDK_WIN_DEBUG
#if ENABLE_WINMD_SUPPORT
Debug.Log("AF_UNITY_WSA_10_0" + String.Format(format, args));
#endif
#endif
}
}
}
#endif
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "appsflyer-unity-plugin",
"displayName": "AppsFlyer",
"description": "AppsFlyer Unity plugin",
"version": "6.16.2",
"version": "6.17.91",
"unity": "2019.4",
"license": "MIT"
}