Example #1
0
 private void IsTrialDo(InAppBillingServiceConnection service, Action<bool> callback)
 {
     var billing = service.BillingHandler;
     var purchases = billing.GetPurchases(ItemType.Product);
     var purchased = purchases.Any(purchase => purchase.ProductId == PRODUCT_ID);
     var isTrial = !purchased;
     timerFactory.Create(() => callback(isTrial), 1000);
 }
Example #2
0
		void ConnectInAppBilling ()
		{
			string value = Security.Unify (Resources.GetStringArray (Resource.Array.billing_key), new int[] { 0, 1, 2, 3 });

			_serviceConnection = new InAppBillingServiceConnection (this, value);
			if (_serviceConnection != null) {
				_serviceConnection.OnConnected += connected;
				_serviceConnection.Connect ();
			}
		}
Example #3
0
 private void IsTrial(InAppBillingServiceConnection service, Action<bool> callback)
 {
     try
     {
         IsTrialDo(service, callback);
     }
     finally
     {
         service.Disconnect();
     }
 }
Example #4
0
 public static void Disconnect()
 {
     try
     {
         if (toDisconnect != null)
             toDisconnect.Disconnect();
     }
     finally
     {
         toDisconnect = null;
     }
 }
Example #5
0
        private void LoadInAppBilling()
        {
            ServiceConnection = new Xamarin.InAppBilling.InAppBillingServiceConnection(this, _publicKey);
            ServiceConnection.OnInAppBillingError += ServiceConnection_OnInAppBillingError;
            ServiceConnection.OnConnected         += ServiceConnection_OnConnected;

            try
            {
                ServiceConnection.Connect();
            }
            catch (Java.Lang.Exception) { }
            catch (Java.Lang.Throwable) { }
        }
        /// <summary>
        /// Inits the service with an activity;
        /// </summary>
        /// <param name="context">Context.</param>
        public Task <IPurchaseService> Init(object context = null)
        {
            var activity = context as Activity;

            inAppSvc              = new IAB.InAppBillingServiceConnection(activity, publicKey);
            inAppSvc.OnConnected += () =>
            {
                IsStarted = true;
                serviceStatusTask.SetResult(IsStarted);
                serviceStatusTask = null;
                if (inAppSvc?.BillingHandler != null)
                {
                    inAppSvc.BillingHandler.OnProductPurchased         += OnProductPurchased;
                    inAppSvc.BillingHandler.OnProductPurchasedError    += OnProductPurchasedError;
                    inAppSvc.BillingHandler.OnPurchaseConsumed         += OnPurchaseConsumed;
                    inAppSvc.BillingHandler.OnPurchaseConsumedError    += OnPurchaseConsumedError;
                    inAppSvc.BillingHandler.OnProductPurchasedError    += OnProductPurchasedError;
                    inAppSvc.BillingHandler.OnPurchaseFailedValidation += OnPurchaseFailedValidation;
                    inAppSvc.BillingHandler.OnUserCanceled             += OnUserCanceled;
                }
            };

            inAppSvc.OnDisconnected += () =>
            {
                IsStarted = false;
                serviceStatusTask?.SetResult(IsStarted);
                serviceStatusTask = null;
                if (inAppSvc?.BillingHandler != null)
                {
                    inAppSvc.BillingHandler.OnProductPurchased         -= OnProductPurchased;
                    inAppSvc.BillingHandler.OnProductPurchasedError    -= OnProductPurchasedError;
                    inAppSvc.BillingHandler.OnPurchaseConsumed         -= OnPurchaseConsumed;
                    inAppSvc.BillingHandler.OnPurchaseConsumedError    -= OnPurchaseConsumedError;
                    inAppSvc.BillingHandler.OnProductPurchasedError    -= OnProductPurchasedError;
                    inAppSvc.BillingHandler.OnPurchaseFailedValidation -= OnPurchaseFailedValidation;
                    inAppSvc.BillingHandler.OnUserCanceled             -= OnUserCanceled;
                }
            };

            inAppSvc.OnInAppBillingError += (errType, err) =>
            {
                IsStarted = false;
                serviceStatusTask.SetException(new PurchaseError($"{errType.ToString()}:{err}"));
                serviceStatusTask = null;
            };

            return(Task.FromResult(this as IPurchaseService));
        }
		public InAppBillingManager (Activity activity)
		{
			string value = Security.Unify (activity.Resources.GetStringArray (Resource.Array.billing_key), new int[] {
				0,
				1,
				2,
				3
			});

			_productId = activity.Resources.GetString (Resource.String.ads_product_id);

			_serviceConnection = new InAppBillingServiceConnection (activity, value);
			if (_serviceConnection != null) {
				_serviceConnection.OnConnected += OnConnected;
				_serviceConnection.Connect ();
			}
		}
        protected override void OnCreate(Bundle bundle)
        {
            _bundle = bundle;
            base.OnCreate(bundle);

            FrameLayout Layout = new FrameLayout(this);

            _game = new Game1();
            SetContentView(_game.Services.GetService<View>());

            Data.Profile.Settings.Identity = (Settings.Secure.GetString(this.ContentResolver, Settings.Secure.AndroidId));

            UrlProvider.PackageName = ApplicationContext.PackageName;

            SwitchToBrowser = false;

            _game.Run();

            NetManager = (ConnectivityManager)GetSystemService(ConnectivityService);
            BillingServiceConnection = null;
        }
Example #9
0
 private void Show(InAppBillingServiceConnection service)
 {
     Disconnect();
     toDisconnect = service;
     var billing = service.BillingHandler;
     var ids = new List<string> { PRODUCT_ID };
     billing.QueryInventoryAsync(ids, ItemType.Product).ContinueWith(continuation =>
     {
         var products = continuation.Result;
         if (products == null)
         {
             Logger.Error("List of items to buy is null.");
             return;
         }
         if (!products.Any())
         {
             Logger.Error("List of items to buy is empty.");
             return;
         }
         var product = products.First();
         var synchronizationContext = Application.SynchronizationContext;
         synchronizationContext.Post(_ => billing.BuyProduct(product), null);
     });
 }
Example #10
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
            base.OnCreate(bundle);
            billingService = new InAppBillingServiceConnection(this,
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvr7MDRR1hINCrRbp/1Uj8eJGiCKnfOU9Q1WCYueuDqPL9B5eIMlyebexeMFIzlf2HwfRVc2SUDzrRbv7EY3ry/vBrOucx2JgjqL72srs7AYkA5WtXMAEZ/tvRx8oa0etl3QmzL0gRHyljDgtchCMhRKkUYX8wg0nysFGOdrnvTqyKCPf1D5hP/TFoQn1ujey8bzYUT7g0W+WvP9K8ObnsOxvWeVqUD/UYaTnizIgqdHawGi2ODiZQR8F593F128FILFipWezhov2VES98EfYq3w3HQ0kiGjroc7l1H/SEqSfeL1DvWaFqUJz9c9NvFhYbbxYhLfAs0YUf3F/Yqx6WwIDAQAB");
            billingService.OnConnected += async () =>
            {

                // Load inventory or available products
                await GetInventory();

                // Load any items already purchased
                LoadPurchasedItems();
            };
            billingService.Connect();

            var appVersion =
                $"{PackageManager.GetPackageInfo(PackageName, 0).VersionName}.{PackageManager.GetPackageInfo(PackageName, 0).VersionCode}";

            var id = Intent.GetStringExtra("id");

            if (string.IsNullOrEmpty(id))
            {
                global::Xamarin.Forms.Forms.Init(this, bundle);
                Xamarin.FormsMaps.Init(this, bundle);
                LoadApplication(new App());
            }
            else
            {
                global::Xamarin.Forms.Forms.Init(this, bundle);
                Xamarin.FormsMaps.Init(this, bundle);
                LoadApplication(new App(int.Parse(id)));
            }
        }
        public void Dispose()
        {
            if (inAppSvc != null)
            {
                if (inAppSvc?.BillingHandler != null)
                {
                    inAppSvc.BillingHandler.OnProductPurchased      -= OnProductPurchased;
                    inAppSvc.BillingHandler.OnProductPurchasedError -= OnProductPurchasedError;
                    inAppSvc.BillingHandler.OnPurchaseConsumed      -= OnPurchaseConsumed;
                    inAppSvc.BillingHandler.OnPurchaseConsumedError -= OnPurchaseConsumedError;
                    inAppSvc.BillingHandler.OnProductPurchasedError -= OnProductPurchasedError;
                    inAppSvc.BillingHandler.OnUserCanceled          -= OnUserCanceled;
                }
                inAppSvc.Disconnect();
                inAppSvc = null;
            }

            currentProduct  = null;
            currentPurchase = null;
            if (currentPurchaseTask != null)
            {
                currentPurchaseTask.SetCanceled();
            }
        }
Example #12
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            PreferenceManager.SetDefaultValues(this, Resource.Xml.preferences, false);

            _pager = FindViewById<ViewPager>(Resource.Id.pager);
            _pager.Adapter = new SectionsPagerAdapter(SupportFragmentManager);
            _pager.SetOnPageChangeListener(this);

            ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
            ActionBar.AddTab(ActionBar.NewTab().SetText("New").SetTabListener(this).SetTag("New"));
            ActionBar.AddTab(ActionBar.NewTab().SetText("Favorites").SetTabListener(this).SetTag("Favorites"));

            _serviceConnection = new InAppBillingServiceConnection(this, PublicKey);
            _serviceConnection.OnConnected += HandleOnConnected;
            _serviceConnection.Connect();
        }
        private void InitConnectToGoogleStore()
        {
            try
            {
                var key = Xamarin.InAppBilling.Utilities.Security.Unify(new[] {
					GetNumberString (3),
					GetNumberString (6),
					GetNumberString (1),
					GetNumberString (4),
					GetNumberString (2),
					GetNumberString (7),
					GetNumberString (0),
					GetNumberString (5)
				}, new[] { 0, 1, 2, 3, 4, 5, 6, 7 });
                _serviceConnection = new InAppBillingServiceConnection(this, key);
                _serviceConnection.BindErrors();
                _serviceConnection.OnConnected += _serviceConnection_OnConnected;
            }
            catch (Exception exception)
            {
                GaService.TrackAppException(this.Class.Name, "InitConnectToGoogleStore", exception, false);
            }
        }
Example #14
0
        void ConnectToService()
        {
            try
            {
                var key = Xamarin.InAppBilling.Utilities.Security.Unify(new[]
                {
                    GetNumberString(3), 
                    GetNumberString(6), 
                    GetNumberString(1), 
                    GetNumberString(4),
                    GetNumberString(2),
                    GetNumberString(7), 
                    GetNumberString(0),
                    GetNumberString(5)
                },
                 new[] { 0, 1, 2, 3, 4, 5, 6, 7 }
                 );

                _serviceConnection = new InAppBillingServiceConnection(this, key);
                _serviceConnection.OnConnected += HandleOnConnected;
                _serviceConnection.Connect();
            }
            catch (Exception ex)
            {
                GaService.TrackAppException(this.Class, "ConnectToService", ex, false);
            }

        }
Example #15
0
        public void Initialize()
        {
            // A Licensing and In-App Billing public key is required before an app can communicate with
            // Google Play, however you DON'T want to store the key in plain text with the application.
            // The Unify command provides a simply way to obfuscate the key by breaking it into two or
            // or more parts, specifying the order to reassemlbe those parts and optionally providing
            // a set of key/value pairs to replace in the final string. 
            string value = Security.Unify(
                new string[] { 
                    "Insert part 0",
                    "Insert part 3",
                    "Insert part 2",
                    "Insert part 1" },
                new int[] { 0, 3, 2, 1 });

            // Create a new connection to the Google Play Service
            _serviceConnection = new InAppBillingServiceConnection(MainActivity.Instance, value);
            _serviceConnection.OnConnected += () =>
            {
                this._serviceConnection.BillingHandler.OnProductPurchased += (int response, Purchase purchase, string purchaseData, string purchaseSignature) =>
                {
                    // Record what we purchased
                    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    var purchaseTime = epoch.AddMilliseconds(purchase.PurchaseTime);
                    var newPurchase = new InAppPurchase
                    {
                        OrderId = purchase.OrderId,
                        ProductId = purchase.ProductId,
                        PurchaseTime = purchaseTime
                    };
                    App.ViewModel.Purchases.Add(newPurchase);

                    // Let anyone know who is interested that purchase has completed
                    if (this.OnPurchaseProduct != null)
                    {
                        this.OnPurchaseProduct();
                    }
                };
                this._serviceConnection.BillingHandler.QueryInventoryError += (int responseCode, Bundle skuDetails) =>
                {
                    if (this.OnQueryInventoryError != null)
                    {
                        this.OnQueryInventoryError(responseCode, null);
                    }
                };
                this._serviceConnection.BillingHandler.BuyProductError += (int responseCode, string sku) =>
                {
                    // Note, BillingResult.ItemAlreadyOwned, etc. can be used to determine error

                    if (this.OnPurchaseProductError != null)
                    {
                        this.OnPurchaseProductError(responseCode, sku);
                    }
                };
                this._serviceConnection.BillingHandler.InAppBillingProcesingError += (string message) =>
                {
                    if (this.OnInAppBillingProcesingError != null)
                    {
                        this.OnInAppBillingProcesingError(message);
                    }
                };
                this._serviceConnection.BillingHandler.OnInvalidOwnedItemsBundleReturned += (Bundle ownedItems) =>
                {
                    if (this.OnInvalidOwnedItemsBundleReturned != null)
                    {
                        this.OnInvalidOwnedItemsBundleReturned(null);
                    }
                };
                this._serviceConnection.BillingHandler.OnProductPurchasedError += (int responseCode, string sku) =>
                {
                    if (this.OnPurchaseProductError != null)
                    {
                        this.OnPurchaseProductError(responseCode, sku);
                    }
                };
                this._serviceConnection.BillingHandler.OnPurchaseFailedValidation += (Purchase purchase, string purchaseData, string purchaseSignature) =>
                {
                    if (this.OnPurchaseFailedValidation != null)
                    {
                        this.OnPurchaseFailedValidation(null, purchaseData, purchaseSignature);
                    }
                };
                this._serviceConnection.BillingHandler.OnUserCanceled += () =>
                {
                    if (this.OnUserCanceled != null)
                    {
                        this.OnUserCanceled();
                    }
                };

                this._connected = true;

                // Load inventory or available products
                this.QueryInventory();
            };

            /* Uncomment these if you want to be notified for these events
            _serviceConnection.OnDisconnected += () =>
            {
                System.Diagnostics.Debug.WriteLine("Remove");
            };

            _serviceConnection.OnInAppBillingError += (error, message) =>
                {
                    System.Diagnostics.Debug.WriteLine("Remove");
                };
            */

            // Are we connected to a network?
            ConnectivityManager connectivityManager = (ConnectivityManager)MainActivity.Instance.GetSystemService(MainActivity.ConnectivityService);
            NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
            if ((activeConnection != null) && activeConnection.IsConnected)
            {
                // Ok, carefully attempt to connect to the in-app service
                try
                {

                    _serviceConnection.Connect();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception trying to connect to in app service: " + ex);
                }
            }
        }
		/// <summary>
		/// Starts the setup of this Android application by connection to the Google Play Service
		/// to handle In-App purchases.
		/// </summary>
		public void StartSetup ()
		{
			// A Licensing and In-App Billing public key is required before an app can communicate with
			// Google Play, however you DON'T want to store the key in plain text with the application.
			// The Unify command provides a simply way to obfuscate the key by breaking it into two or
			// or more parts, specifying the order to reassemlbe those parts and optionally providing
			// a set of key/value pairs to replace in the final string. 
			string value = Security.Unify (
				new string[] { "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtpopeFYhDOOsufNhYe2PY97azBQBJoqGSP/XxsgzQgj3M0MQQ0WE0WDwPKoxlo/MIuoadVR5q2ZRs3rTl", 
					"UsH9vYUPr/z0/O8kn5anQHshQkHkeHsA8wbyJGGmwcXqvZr1fnzFOFyHL46s47vOJBLc5x30oieJ02dNxdBcy0oFEJtJS5Ng5sm6YUv9ifgxYOqMr/K61HNw6tP0j", 
					"vi6vLv2ro/KXO0ADVxcDxEg+Pk16xVNKgnei8M09PJCgA9bWNyeSsD+85Jj9+OZGsS/DN7O7nrGuKx8oAg/lE6a2eCQHh9lXxSPlAFAMH2FB8aNxUeJxkByW+6l/S", 
					"yqvVlOeYxAwIDAQAB" }, 
				new int[] { 0,1,2,3 });

			// Create a new connection to the Google Play Service
			_serviceConnection = new InAppBillingServiceConnection (this, value);
			_serviceConnection.OnConnected += () => {
				// Attach to the various error handlers to report issues
				_serviceConnection.BillingHandler.OnGetProductsError += (int responseCode, Bundle ownedItems) => {
					Console.WriteLine("Error getting products");
				};

				_serviceConnection.BillingHandler.OnInvalidOwnedItemsBundleReturned += (Bundle ownedItems) => {
					Console.WriteLine("Invalid owned items bundle returned");
				};

				_serviceConnection.BillingHandler.OnProductPurchasedError += (int responseCode, string sku) => {
					Console.WriteLine("Error purchasing item {0}",sku);
				};

				_serviceConnection.BillingHandler.OnPurchaseConsumedError += (int responseCode, string token) => {
					Console.WriteLine("Error consuming previous purchase");
				};

				_serviceConnection.BillingHandler.InAppBillingProcesingError += (message) => {
					Console.WriteLine("In app billing processing error {0}",message);
				};

				// Load inventory or available products
				GetInventory();

				// Load any items already purchased
				LoadPurchasedItems();
			};

			// Attempt to connect to the service
			_serviceConnection.Connect ();

		}
 private void ConnectToService()
 {
     var key = Xamarin.InAppBilling.Utilities.Security.Unify(new[]
         {
             GetNumberString(3), 
             GetNumberString(6), 
             GetNumberString(1), 
             GetNumberString(4),
             GetNumberString(2),
             GetNumberString(7), 
             GetNumberString(0),
             GetNumberString(5)
         },
      new[] { 0, 1, 2, 3, 4, 5, 6, 7 }
      );
     _serviceConnection = new InAppBillingServiceConnection(this, key);
     _serviceConnection.OnConnected += HandleOnConnected;
     _serviceConnection.OnInAppBillingError += ServiceConnectionOnInAppBillingError;
     _serviceConnection.Connect();
 }
Example #18
0
        /*
        "premium_upgrade",
        ReservedTestProductIDs.Purchased,
        ReservedTestProductIDs.Canceled,
        ReservedTestProductIDs.Refunded,
        ReservedTestProductIDs.Unavailable,
        */

        /// <summary>
        /// See parent.
        /// </summary>
        /// <param name="bundle"></param>
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Create the interface used to interact with Google Play.
            mGooglePlayClient = new GamesClient.Builder(this, this, this)
                .SetGravityForPopups((int)(GravityFlags.Bottom | GravityFlags.CenterHorizontal))
                .Create();

            pGooglePlayClient.RegisterConnectionCallbacks (this);
            pGooglePlayClient.IsConnectionFailedListenerRegistered (this);

            // Create a new connection to the Google Play Service
            mBillingConnection = new InAppBillingServiceConnection (this, InAppBillingKey.Key);
            pBillingConnection.OnConnected += async () => {

                // Clear out the test purchase so that it can be tested again. Remove this 
                // to test starting with test purchase already completed.
                //bool response = pBillingConnection.BillingHandler.ConsumePurchase("inapp:"+ PackageName +":android.test.purchased");

                // Attach to the various error handlers to report issues
                pBillingConnection.BillingHandler.OnGetProductsError += (int responseCode, Bundle ownedItems) => {
                    Console.WriteLine("Error getting products");
                };

                pBillingConnection.BillingHandler.OnInvalidOwnedItemsBundleReturned += (Bundle ownedItems) => {
                    Console.WriteLine("Invalid owned items bundle returned");
                };

                pBillingConnection.BillingHandler.OnProductPurchasedError += (int responseCode, string sku) => {
                    Console.WriteLine("Error purchasing item {0}",sku);
                };

                pBillingConnection.BillingHandler.OnPurchaseConsumedError += (int responseCode, string token) => {
                    Console.WriteLine("Error consuming previous purchase");
                };

                pBillingConnection.BillingHandler.InAppBillingProcesingError += (message) => {
                    Console.WriteLine("In app billing processing error {0}",message);
                };

                // Load inventory or available products
                await GetInventory();

                // Load any items already purchased
                UpdatePurchasedItems();
            };

			// Create our OpenGL view, and display it
			Game1.Activity = this;
			var g = new Game1 ();
			SetContentView (g.Window);
			g.Run ();
        }
        public override void Activate()
        {
            _returnToGame = NextSceneParameters.Get<bool>("return-to-game");

            Type[] types = Assembly.GetExecutingAssembly().GetTypes();
            List<string> providers = new List<string>();
            Dictionary<string, string> lookups = new Dictionary<string, string>();
            foreach (Type t in types)
            {
                PropertyInfo pi = t.GetProperty(Bopscotch.Definitions.KeyChain, BindingFlags.NonPublic | BindingFlags.Static);
                if (pi != null)
                {
                    providers.Add(t.FullName);
                    lookups.Add(t.FullName, pi.GetValue(null).ToString());
                }
            }
            providers = providers.OrderBy(x => x.LastIndexOf('.')).ToList();

            string sk = "";
            foreach (string p in providers)
            {
                sk = sk + lookups[p];
            }

            _connection = new InAppBillingServiceConnection(Bopscotch.Game1.Activity, sk);
            _connection.OnConnected += LoadProducts;

            MainActivity.BillingServiceConnection = _connection;

            base.Activate();

            MusicManager.StopMusic();

            ActivateDialog("loading-store");
        }
Example #20
0
 private void WithService(Action<InAppBillingServiceConnection> action)
 {
     var activityHolder = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();
     var activity = activityHolder.Activity;
     if (activity == null)
     {
         Logger.Error("No current activity.");
         return;
     }
     var service = new InAppBillingServiceConnection(activity, PUBLIC_KEY);
     service.OnInAppBillingError += (error, message) => Logger.Error($"{error} - {message}");
     service.OnConnected += () =>
     {
         var billing = service.BillingHandler;
         billing.BuyProductError += (code, sku) => Logger.Error($"Error {code} while buying {sku}");
         billing.InAppBillingProcesingError += Logger.Error;
         billing.OnGetProductsError += (code, items) => Logger.Error($"Error {code} when getting items {items}");
         billing.OnProductPurchasedError += (code, sku) => Logger.Error($"Error {code} after purchased {sku}");
         billing.OnPurchaseConsumedError += (code, token) => Logger.Error($"Error {code} consuming {token}");
         billing.QueryInventoryError += (code, skus) => Logger.Error($"Error {code} getting inventory {skus}");
         action(service);
     };
     service.Connect();
 }