I am using a non-consumable product to switch off ads for good, after purchasing.
When users buy pro everything works fine. Ads are switched off, also autorenewal in google store works fine after the user reinstalls the app.
My problem starts when the user wants a refund. After all, will be processed by Google and the customer will get his money. I don't know how where to subscribe to my function to turn off the pro version again on the users' app.
I am using IAPManager:
public class IAPManager : MonoBehaviour, IStoreListener
{
public List<Product> ProductList = new List<Product>();
public const string Pro = "pro";
private const string _androidPostFix = "_android";
[SerializeField] I18NText purchaseProBtnText;
public IAPManager Instance;
private void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
Init();
EventManager.PurchaseProduct += PurchaseProduct;
EventManager.GetProLocalizedPriceString += GetProLocalPriceString;
}
private void OnDestroy()
{
EventManager.PurchaseProduct -= PurchaseProduct;
EventManager.GetProLocalizedPriceString -= GetProLocalPriceString;
}
public List<Product> AllProducts { get { return m_Controller.products.all.ToList(); } }
private IStoreController m_Controller;
private ITransactionHistoryExtensions m_TransactionHistoryExtensions;
private IGooglePlayStoreExtensions m_GooglePlayStoreExtensions;
private bool m_IsGooglePlayStoreSelected;
private bool m_PurchaseInProgress;
#if RECEIPT_VALIDATION
private CrossPlatformValidator validator;
#endif
private string GetProLocalPriceString()
{
#if UNITY_ANDROID && !UNITY_EDITOR
foreach (Product product in ProductList)
{
if (product.metadata.localizedTitle == Pro)
{
return product.metadata.localizedPriceString;
}
}
return null;
#elif UNITY_EDITOR
foreach (Product product in ProductList)
{
if (product.metadata.localizedTitle == "Fake title for pro")
{
return product.metadata.localizedPriceString;
}
}
return null;
#endif
}
public void Init()
{
var module = StandardPurchasingModule.Instance();
module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;
var builder = ConfigurationBuilder.Instance(module);
// Set this to true to enable the Microsoft IAP simulator for local testing.
builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = false;
m_IsGooglePlayStoreSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.GooglePlay;
#if AGGRESSIVE_INTERRUPT_RECOVERY_GOOGLEPLAY
// For GooglePlay, if we have access to a backend server to deduplicate purchases, query purchase history
// when attempting to recover from a network-interruption encountered during purchasing. Strongly recommend
// deduplicating transactions across app reinstallations because this relies upon the on-device, deletable
// TransactionLog database.
builder.Configure<IGooglePlayConfiguration>().aggressivelyRecoverLostPurchases = true;
// Use purchaseToken instead of orderId for all transactions to avoid non-unique transactionIDs for a
// single purchase; two ProcessPurchase calls for one purchase, differing only by which field of the receipt
// is used for the Product.transactionID. Automatically true if aggressivelyRecoverLostPurchases is enabled
// and this API is not called at all.
builder.Configure<IGooglePlayConfiguration>().UsePurchaseTokenForTransactionId(true);
#endif
//builder.AddProduct(Pro, ProductType.NonConsumable);
builder.AddProduct(Pro, ProductType.NonConsumable, new IDs
{
{Pro, GooglePlay.Name},
//{Pro+_iosPostFix, AppleAppStore.Name}
}
);
#if INTERCEPT_PROMOTIONAL_PURCHASES
// On iOS and tvOS we can intercept promotional purchases that come directly from the App Store.
// On other platforms this will have no effect; OnPromotionalPurchase will never be called.
builder.Configure<IAppleConfiguration>().SetApplePromotionalPurchaseInterceptorCallback(OnPromotionalPurchase);
Debug.Log("Setting Apple promotional purchase interceptor callback");
#endif
#if RECEIPT_VALIDATION
string appIdentifier;
#if UNITY_5_6_OR_NEWER
appIdentifier = Application.identifier;
#else
appIdentifier = Application.bundleIdentifier;
#endif
try
{
validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), appIdentifier);
}
catch (NotImplementedException exception)
{
Debug.Log("Cross Platform Validator Not Implemented: " + exception);
}
#endif
// Now we're ready to initialize Unity IAP.
UnityPurchasing.Initialize(this, builder);
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
m_Controller = controller;
m_TransactionHistoryExtensions = extensions.GetExtension<ITransactionHistoryExtensions>();
m_GooglePlayStoreExtensions = extensions.GetExtension<IGooglePlayStoreExtensions>();
#if SUBSCRIPTION_MANAGER
Dictionary<string, string> introductory_info_dict = m_AppleExtensions.GetIntroductoryPriceDictionary();
#endif
// Sample code for expose product sku details for apple store
//Dictionary<string, string> product_details = m_AppleExtensions.GetProductDetails();
Debug.Log("Available items:");
foreach (var item in controller.products.all)
{
if (item.availableToPurchase)
{
Debug.Log(string.Join(" - ",
new[]
{
item.metadata.localizedTitle,
item.metadata.localizedDescription,
item.metadata.isoCurrencyCode,
item.metadata.localizedPrice.ToString(),
item.metadata.localizedPriceString,
item.transactionID,
item.receipt
}));
ProductList.Add(item);
#if INTERCEPT_PROMOTIONAL_PURCHASES
// Set all these products to be visible in the user's App Store according to Apple's Promotional IAP feature
// https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/PromotingIn-AppPurchases/PromotingIn-AppPurchases.html
m_AppleExtensions.SetStorePromotionVisibility(item, AppleStorePromotionVisibility.Show);
#endif
#if SUBSCRIPTION_MANAGER
// this is the usage of SubscriptionManager class
if (item.receipt != null) {
if (item.definition.type == ProductType.Subscription) {
if (checkIfProductIsAvailableForSubscriptionManager(item.receipt)) {
string intro_json = (introductory_info_dict == null || !introductory_info_dict.ContainsKey(item.definition.storeSpecificId)) ? null : introductory_info_dict[item.definition.storeSpecificId];
SubscriptionManager p = new SubscriptionManager(item, intro_json);
SubscriptionInfo info = p.getSubscriptionInfo();
Debug.Log("product id is: " + info.getProductId());
Debug.Log("purchase date is: " + info.getPurchaseDate());
Debug.Log("subscription next billing date is: " + info.getExpireDate());
Debug.Log("is subscribed? " + info.isSubscribed().ToString());
Debug.Log("is expired? " + info.isExpired().ToString());
Debug.Log("is cancelled? " + info.isCancelled());
Debug.Log("product is in free trial peroid? " + info.isFreeTrial());
Debug.Log("product is auto renewing? " + info.isAutoRenewing());
Debug.Log("subscription remaining valid time until next billing date is: " + info.getRemainingTime());
Debug.Log("is this product in introductory price period? " + info.isIntroductoryPricePeriod());
Debug.Log("the product introductory localized price is: " + info.getIntroductoryPrice());
Debug.Log("the product introductory price period is: " + info.getIntroductoryPricePeriod());
Debug.Log("the number of product introductory price period cycles is: " + info.getIntroductoryPricePeriodCycles());
} else {
Debug.Log("This product is not available for SubscriptionManager class, only products that are purchase by 1.19+ SDK can use this class.");
}
} else {
Debug.Log("the product is not a subscription product");
}
} else {
Debug.Log("the product should have a valid receipt");
}
#endif
}
}
}
public void Restore()
{
m_GooglePlayStoreExtensions.RestoreTransactions(OnTransactionsRestored);
Debug.Log("Restore method");
}
private void OnTransactionsRestored(bool success)
{
Debug.Log("Transactions restored." + success);
}
public void OnPurchaseFailed(Product item, PurchaseFailureReason r)
{
Debug.Log("Purchase failed: " + item.definition.id);
Debug.Log(r);
// Detailed debugging information
Debug.Log("Store specific error code: " + m_TransactionHistoryExtensions.GetLastStoreSpecificPurchaseErrorCode());
if (m_TransactionHistoryExtensions.GetLastPurchaseFailureDescription() != null)
{
Debug.Log("Purchase failure description message: " +
m_TransactionHistoryExtensions.GetLastPurchaseFailureDescription().message);
}
m_PurchaseInProgress = false;
}
public void OnInitializeFailed(InitializationFailureReason error)
{
Debug.Log("Billing failed to initialize!");
switch (error)
{
case InitializationFailureReason.AppNotKnown:
Debug.LogError("Is your App correctly uploaded on the relevant publisher console?");
break;
case InitializationFailureReason.PurchasingUnavailable:
// Ask the user if billing is disabled in device settings.
Debug.Log("Billing disabled!");
break;
case InitializationFailureReason.NoProductsAvailable:
// Developer configuration error; check product metadata.
Debug.Log("No products available for purchase!");
break;
}
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
{
Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
Debug.Log("Receipt: " + e.purchasedProduct.receipt);
m_PurchaseInProgress = false;
#if RECEIPT_VALIDATION // Local validation is available for GooglePlay, and Apple stores
if (m_IsGooglePlayStoreSelected ||
Application.platform == RuntimePlatform.IPhonePlayer ||
Application.platform == RuntimePlatform.OSXPlayer ||
Application.platform == RuntimePlatform.tvOS) {
try {
var result = validator.Validate(e.purchasedProduct.receipt);
Debug.Log("Receipt is valid. Contents:");
foreach (IPurchaseReceipt productReceipt in result) {
Debug.Log(productReceipt.productID);
Debug.Log(productReceipt.purchaseDate);
Debug.Log(productReceipt.transactionID);
GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
if (null != google) {
Debug.Log(google.purchaseState);
Debug.Log(google.purchaseToken);
}
AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
if (null != apple) {
Debug.Log(apple.originalTransactionIdentifier);
Debug.Log(apple.subscriptionExpirationDate);
Debug.Log(apple.cancellationDate);
Debug.Log(apple.quantity);
}
// For improved security, consider comparing the signed
// IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data
// embedded in the signed receipt objects to the data which the game is using
// to make this purchase.
}
}
catch (IAPSecurityException ex)
{
Debug.Log("Invalid receipt, not unlocking content. " + ex);
return PurchaseProcessingResult.Complete;
}
catch (NotImplementedException exception)
{
Debug.Log("Cross Platform Validator Not Implemented: " + exception);
}
}
#endif
// Unlock content from purchases here.
if (e.purchasedProduct.definition.id == Pro)
{
//PlayerPrefs.SetInt("pro", 1);
Debug.Log("PURCHASED PRODUCT!");
//AdsManager.Instance.ProActive = true;
AdsManager.Instance.HideAdsPro();
//EventBroker.CallOnProBought();
}
#if USE_PAYOUTS
if (e.purchasedProduct.definition.payouts != null) {
Debug.Log("Purchase complete, paying out based on defined payouts");
foreach (var payout in e.purchasedProduct.definition.payouts) {
Debug.Log(string.Format("Granting {0} {1} {2} {3}", payout.quantity, payout.typeString, payout.subtype, payout.data));
}
}
#endif
#if DELAY_CONFIRMATION
StartCoroutine(ConfirmPendingPurchaseAfterDelay(e.purchasedProduct));
return PurchaseProcessingResult.Pending;
#else
return PurchaseProcessingResult.Complete;
#endif
}
/// <summary>
/// Call this method to start purchase product.
/// </summary>
/// <param name="productID">Product ID from products on Google Dev Dashboard</param>
public void PurchaseProduct(string productID)
{
Debug.Log("PurchaseProduct");
if (m_PurchaseInProgress == true)
{
Debug.Log("Please wait, purchase in progress");
return;
}
if (m_Controller == null)
{
Debug.LogError("Purchasing is not initialized");
return;
}
if (m_Controller.products.WithID(productID) == null)
{
Debug.LogError("No product has id " + productID);
return;
}
m_PurchaseInProgress = true;
m_Controller.InitiatePurchase(m_Controller.products.WithID(productID), "developerPayload");
}
}
I found a solution myself.
I checked product.hasRecipt to get info if the product is bought.
So the receipt disappears after a successful revoke process in the google app store.
And every time the app is restarted this bool is sent to the app during IAP initialization.
Related
When I directly insert the apk file into an android mobile device
MobileAds.Initialize(initStatus => { });
code works fine.
However, when I use it in an internal test version with aab file,
it does not work. How can I debug this in internal testing version?
public class BottomBanner : MonoBehaviour
{
public static BottomBanner instance;
private BannerView bannerView;
public TextMeshProUGUI FailMSG;
public AdRequest request;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
}
FailMSG.text += "\n is awake Ok "+ "\n version : " + GameStartManager.instance.version + "\n Test : " + GameStartManager.instance.isTest;
}
public void Start()
{
FailMSG.text += "\n Start 000 ";
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(initStatus => { });
FailMSG.text += "\n Start 111 ";
this.RequestBanner();
FailMSG.text += "\n Start 222 ";
}
private void RequestBanner()
{
#if UNITY_ANDROID
string adUnitId = null;
if (GameStartManager.instance.isTest)
{
adUnitId = "ca-app-pub-3940256099942544/6300978111";
}
else
{
adUnitId = "ca-app-pub-0000000000000000/1111111111"; // bannerID
}
#elif UNITY_IPHONE
string adUnitId = "unexpected_platform";
#else
string adUnitId = "unexpected_platform";
#endif
// Clean up banner ad before creating a new one.
if (this.bannerView != null)
{
this.bannerView.Destroy();
}
AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);
this.bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Bottom);
// Create an empty ad request.
request = new AdRequest.Builder().Build();
// Load the banner with the request.
this.bannerView.LoadAd(request);
SceneManager.LoadScene(1);
}
public void ToggleBannerAd(bool b){
if (b) bannerView.Show();
else bannerView.Hide();
}
}
I am using Unity IAP 4.1.4.
As you know there are 4 different test cards on purchase testing. My question is what should I do when payment is slow? If user quits the game before payment validated I can't approve the payment and purchase is pending. Is there any way to handle slow payments?
This is the script.
public class IAPManager : MonoBehaviour
{
private string coin250k = "//";
private string coin500k = "//";
public void OnPurchaseComplete(Product product)
{
var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),AppleTangle.Data(), Application.identifier);
bool ValidPurchase = false;
try
{
// On Google Play, result has a single product ID.
// On Apple stores, receipts contain multiple products.
var result = validator.Validate(product.receipt);
// For informational purposes, we list the receipt(s)
Debug.Log("Receipt is valid. Contents:");
foreach (IPurchaseReceipt productReceipt in result)
{
Debug.Log(productReceipt.productID);
Debug.Log(productReceipt.purchaseDate);
Debug.Log(productReceipt.transactionID);
GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
if (null != google)
{
// This is Google's Order ID.
// Note that it is null when testing in the sandbox
// because Google's sandbox does not provide Order IDs.
ValidPurchase = true;
Debug.Log(" google transaction" + google.transactionID);
Debug.Log(" google transaction" + google.purchaseState);
Debug.Log(" google transaction" + google.purchaseToken);
}
AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
if (null != apple)
{
ValidPurchase = true;
Debug.Log(" apple transaction1" + apple.originalTransactionIdentifier);
Debug.Log(" apple transaction2" + apple.subscriptionExpirationDate);
Debug.Log(" apple transaction3" + apple.cancellationDate);
Debug.Log(" apple transaction4" + apple.quantity);
}
}
}
catch (IAPSecurityException)
{
Debug.Log("Invalid receipt, not unlocking content");
ValidPurchase = false;
}
//product.receipt;
if (ValidPurchase)
{
if (product.definition.id == coin250k)
{
//
}
else if (product.definition.id == coin500k)
{
//
}
}
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason reason)
{
Debug.Log(product.definition.id + " failed because: "+ reason);
}
}
lets to the point, so i want to make some configuration with my game to show Ads but I avoid to update game version too much, because of that I choose firebase remote config with this I can update setting/configuration without update the game version.
there is document for this but not very clear for newbie like me, you can check it here https://firebase.google.com/docs/remote-config/use-config-unity
I already make the script like on doc, but I don't understand how its work on show data because error string format, which is what I know on this firebase console is int format
the script like this :
public static _FirebaseRemoteConfig instance;
private void Awake()
{
instance = this;
}
Firebase.DependencyStatus dependencyStatus = Firebase.DependencyStatus.UnavailableOther;
// Use this for initialization
void Start()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
InitializeFirebase();
}
else
{
Debug.LogError(
"Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
public void InitializeFirebase()
{
System.Collections.Generic.Dictionary<string, object> defaults =
new System.Collections.Generic.Dictionary<string, object>();
defaults.Add("config_test_string", "default local string");
defaults.Add("config_test_int", 1);
defaults.Add("config_test_float", 1.0);
defaults.Add("config_test_bool", false);
Firebase.RemoteConfig.FirebaseRemoteConfig.SetDefaults(defaults);
Debug.Log("Remote config ready!");
}
public void FetchFireBase()
{
FetchDataAsync();
}
public void ShowData()
{
Debug.Log("maxCountToShowAdmob: " +
Firebase.RemoteConfig.FirebaseRemoteConfig.GetValue("MaxCountShowIntersitialAds").LongValue);
}
// Start a fetch request.
public Task FetchDataAsync()
{
Debug.Log("Fetching data...");
System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.FetchAsync(
TimeSpan.Zero);
return fetchTask.ContinueWith(FetchComplete);
}
void FetchComplete(Task fetchTask)
{
if (fetchTask.IsCanceled)
{
Debug.Log("Fetch canceled.");
}
else if (fetchTask.IsFaulted)
{
Debug.Log("Fetch encountered an error.");
}
else if (fetchTask.IsCompleted)
{
Debug.Log("Fetch completed successfully!");
}
var info = Firebase.RemoteConfig.FirebaseRemoteConfig.Info;
switch (info.LastFetchStatus)
{
case Firebase.RemoteConfig.LastFetchStatus.Success:
Firebase.RemoteConfig.FirebaseRemoteConfig.ActivateFetched();
Debug.Log(String.Format("Remote data loaded and ready (last fetch time {0}).",
info.FetchTime));
break;
case Firebase.RemoteConfig.LastFetchStatus.Failure:
switch (info.LastFetchFailureReason)
{
case Firebase.RemoteConfig.FetchFailureReason.Error:
Debug.Log("Fetch failed for unknown reason");
break;
case Firebase.RemoteConfig.FetchFailureReason.Throttled:
Debug.Log("Fetch throttled until " + info.ThrottledEndTime);
break;
}
break;
case Firebase.RemoteConfig.LastFetchStatus.Pending:
Debug.Log("Latest Fetch call still pending.");
break;
}
}
I have an application in AppGallery available also for the older Huawei phones such as P8 or P9. I noticed that the old phones sometimes catch crash because of outdated HMS Core. I read that HMS Core can update itself automatically but I want do it immediately after I run the app.
It is possible to call it when you use map (I have it on the second screen) but I want inform user about outdated HMS Core as soon as possible.
Is there any sample how to manually call HMS Core version check?
To manually upgrade HMS Core (APK) on a Huawei phone, call the sample code provided below to check whether the version number is earlier than 5.0.0.300.
If so, the HMS Core download screen on AppGallery will appear.
Besides, remember to replace channelId in the URI.
Defined channelId as needed to identify channel data. channelId is the ID of a level-1 channel, that is, the channel from which the user comes.
public static void checkUpdate(Context context){
String version = "5.0.0.300";
String pkg = "com.huawei.hwid";
if (version.compareTo(getVersionCode(pkg, context)) > 0) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("hiapplink://com.huawei.appmarket?appId=C10132067&channelId=xxxxx&referrer=&detailType=0"));
context.startActivity(intent);
}
}
private static String getVersionCode(String packageName, Context context) {
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
return packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return "";
}
}
Yes, it is possible. Here is the provided solution. Everything is based on variable baseVersion. If it's value is higher than your HMS Core version code then you will get mentioned dialog.
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.util.Log;
import com.huawei.hms.adapter.AvailableAdapter;
import com.huawei.hms.adapter.internal.AvailableCode;
import com.huawei.hms.api.ConnectionResult;
/**
* Check for HMS Update
*/
public class HmsUpdateUtil {
private static final String TAG = "HmsUpdateUtil";
private static boolean isInitialized = false;
private static int versionCheckResult = 12;
/**
* Check if HMS needs update
*
* #param context context
* #return result,0 Available, 1 not Available
*/
public static int isHmsAvailable(Context context) {
if (versionCheckResult == ConnectionResult.SUCCESS ) {
return ConnectionResult.SUCCESS;
}
Log.d(TAG, "isInitialized is:" + isInitialized);
if (isInitialized) {
return 1;
}
// minimum HMS version, if less than this version, result will not be 0
int baseVersion = 50000300;
AvailableAdapter availableAdapter = new AvailableAdapter(baseVersion);
int result = availableAdapter.isHuaweiMobileServicesAvailable(context);
Log.i(TAG, "HMS update result is: " + result);
isInitialized = true;
if (result == ConnectionResult.SUCCESS) {
Log.i(TAG, "HMS is avaiable");
} else {
if (availableAdapter.isUserResolvableError(result)) {
resolution(availableAdapter, context);
} else {
Log.e(TAG, "HMS is not avaiable " + AvailableCode.ERROR_NO_ACTIVITY);
}
}
versionCheckResult = result;
return result;
}
private static void resolution(AvailableAdapter availableAdapter, Context context) {
Log.i(TAG, "HMS update start :");
Activity activity = findActivity(context);
if (activity == null) {
Log.e(TAG, "HMS is not available" + AvailableCode.ERROR_NO_ACTIVITY);
return;
}
// this method will be call upgrade dialog box.
availableAdapter.startResolution(activity, new AvailableAdapter.AvailableCallBack() {
#Override
public void onComplete(int result) {
if (result == AvailableCode.SUCCESS) {
versionCheckResult = result;
Log.i(TAG, "HMS update start success");
} else {
Log.e(TAG, "HMS update failed: " + result);
isInitialized = false;
}
}
});
}
/**
* Get Activity by Context
* #param context context
* #return Activity
*/
public static Activity findActivity(Context context) {
Activity activity = null;
if (context instanceof Activity) {
return (Activity) context;
}
if (context instanceof ContextWrapper) {
ContextWrapper wrapper = (ContextWrapper) context;
return findActivity(wrapper.getBaseContext());
} else {
return activity;
}
}
}
I notice that Parse Unity support still doesn't provide push notification for iOS.
Has anyone implemented a Unity plugin or another solution to support iOS Push Notifications via Parse?
(Cross posted on Unity Answers.)
It's actually possible now, using a ParseObject to mock up the ParseInstallation object.
Gist here: https://gist.github.com/gfosco/a3d092651c32ba3385e6
Explanation in the Parse Google Group: https://groups.google.com/d/msg/parse-developers/ku8-r91_o6s/6ioQ9T2TP7wJ
Attach this script to a GameObject, replace the important parts with your own:
using UnityEngine;
using System.Collections;
using Parse;
public class PushBehaviorScript : MonoBehaviour {
bool tokenSent = false;
public ParseObject currentInstallation = null;
void Start () {
if (PlayerPrefs.HasKey ("currentInstallation")) {
string objId = PlayerPrefs.GetString ("currentInstallation");
currentInstallation = ParseObject.CreateWithoutData ("_Installation", objId);
}
if (currentInstallation == null) {
#if UNITY_IPHONE && !UNITY_EDITOR
NotificationServices.RegisterForRemoteNotificationTypes (RemoteNotificationType.Alert | RemoteNotificationType.Badge | RemoteNotificationType.Sound);
#endif
}
}
void FixedUpdate () {
if (!tokenSent && currentInstallation == null) {
#if UNITY_IPHONE && !UNITY_EDITOR
byte[] token = NotificationServices.deviceToken;
if(token != null) {
tokenSent = true;
string tokenString = System.BitConverter.ToString(token).Replace("-", "").ToLower();
Debug.Log ("OnTokenReived");
Debug.Log (tokenString);
ParseObject obj = new ParseObject("_Installation");
obj["deviceToken"] = tokenString;
obj["appIdentifier"] = "com.parse.unitypush";
obj["deviceType"] = "ios";
obj["timeZone"] = "UTC";
obj["appName"] = "UnityPushTest";
obj["appVersion"] = "1.0.0";
obj["parseVersion"] = "1.3.0";
obj.SaveAsync().ContinueWith(t =>
{
if (obj.ObjectId != null) {
PlayerPrefs.SetString ("currentInstallation", obj.ObjectId);
}
});
}
#endif
}
}
}
To implement iOS push with parse.com You need to get the token from apple first. Then save Current instalation
Unity does have this functionality build in now.
//push notification
bool tokenSent = false;
void RegisterForPush()
{
Debug.Log("Register for push");
tokenSent = false;
#if UNITY_IOS
UnityEngine.iOS.NotificationServices.RegisterForNotifications(NotificationType.Alert |
NotificationType.Badge |
NotificationType.Sound, true);
#endif
}
void Update () {
if (!tokenSent) {
byte[] token = UnityEngine.iOS.NotificationServices.deviceToken;
if (token != null) {
// send token to a provider
tokenSent = true;
string hexToken = "%" + System.BitConverter.ToString(token).Replace('-', '%');
#if UNITY_IOS
ParseManager.instance.RegisterForPush(hexToken);
#endif
}
}
}
And inside ParseManager (or whatever class you use to manage parse>client communication)
public void RegisterForPush(string token) {
Debug.Log("Parse updating instalation");
ParseInstallation instalation = ParseInstallation.CurrentInstallation;
instalation["deviceToken"] = token;
instalation["user"] = ParseUser.CurrentUser.ObjectId;
instalation["timeZoneOffset"] = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
instalation.SaveAsync();
}
Tested on Unity 5.1.2 and iOS 8.4