/// <summary> Purchases an item - returns true if successful </summary>
        /// <param name="productId"></param>
        /// <param name="payload"></param>
        /// <returns></returns>
        public async void Purchase(String productId, Action <Boolean> onComplete, String payload = "")
        {
            Boolean success = false;

            if (!_Connected)
            {
                Connect(null);
            }
            if (_Connected)
            {
                try
                {
                    InAppBillingPurchase purchase = await CrossInAppBilling.Current.PurchaseAsync(productId, ItemType.InAppPurchase, payload);

                    if (purchase != null)
                    {
#if __IOS__
                        success = true;
#else
                        success = await Consume(purchase);
#endif
                    }
                }
                catch (Exception e)
                {
                }
            }
            onComplete?.Invoke(success);
        }
Пример #2
0
        /// <summary>
        /// Purchase a specific product or subscription
        /// </summary>
        /// <param name="productId">Sku or ID of product</param>
        /// <param name="itemType">Type of product being requested</param>
        /// <param name="payload">Developer specific payload</param>
        /// <param name="verifyPurchase">Verify purchase implementation</param>
        /// <returns></returns>
        /// <exception cref="InAppBillingPurchaseException">If an error occurs during processing</exception>
        public override async Task <InAppBillingPurchase> PurchaseAsync(string productId, ItemType itemType, string payload, IInAppBillingVerifyPurchase verifyPurchase = null)
        {
            //var licinfo = CurrentApp.LicenseInformation;
            // Get purchase result from store or simulator
            var purchaseResult = await CurrentAppMock.RequestProductPurchaseAsync(InTestingMode, productId);

            var recStr = await CurrentAppMock.GetProductReceiptAsync(InTestingMode, productId);



            //await GetPurchasesAsync(ItemType.InAppPurchase, null, null);
            if (purchaseResult == null)
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(purchaseResult.ReceiptXml))
            {
                return(null);
            }

            // Transform it to InAppBillingPurchase
            InAppBillingPurchase purchase = purchaseResult.ReceiptXml.ToInAppBillingPurchase(purchaseResult.Status).FirstOrDefault();

            if (verifyPurchase == null)
            {
                return(purchase);
            }

            var validated = await verifyPurchase.VerifyPurchase(purchaseResult.ReceiptXml, string.Empty, purchase.ProductId, purchase.Id);

            return(validated ? purchase : null);
        }
        public static async Task BuyProduct(string productId)
        {
            InAppBillingPurchase purchase = await InAppPurchase.Buy(productId, true);

            string message = purchase == null ? LN.PurchaseFailed : LN.ThanksForYourSupport;
            await Shell.Current.CurrentPage.DisplayToastAsync(message);
        }
Пример #4
0
        /// <summary>
        /// Read purchase data out of the UWP Receipt XML
        /// </summary>
        /// <param name="xml">Receipt XML</param>
        /// <param name="status">Status of the purchase</param>
        /// <returns>A list of purchases, the user has done</returns>
        public static IEnumerable <InAppBillingPurchase> ToInAppBillingPurchase(this string xml, ProductPurchaseStatus status)
        {
            var purchases = new List <InAppBillingPurchase>();

            var xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.LoadXml(xml);
            }
            catch
            {
                //Invalid XML, we haven't finished this transaction yet.
            }

            // Iterate through all ProductReceipt elements
            var xmlProductReceipts = xmlDoc.GetElementsByTagName("ProductReceipt");

            for (var i = 0; i < xmlProductReceipts.Count; i++)
            {
                var xmlProductReceipt = xmlProductReceipts[i];

                // Create new InAppBillingPurchase with values from the xml element
                var purchase = new InAppBillingPurchase()
                {
                    Id = xmlProductReceipt.Attributes["Id"].Value,
                    TransactionDateUtc = Convert.ToDateTime(xmlProductReceipt.Attributes["PurchaseDate"].Value),
                    ProductId          = xmlProductReceipt.Attributes["ProductId"].Value,
                    AutoRenewing       = false               // Not supported by UWP yet
                };
                purchase.PurchaseToken = purchase.Id;
                // Map native UWP status to PurchaseState
                switch (status)
                {
                case ProductPurchaseStatus.AlreadyPurchased:
                case ProductPurchaseStatus.Succeeded:
                    purchase.State = PurchaseState.Purchased;
                    break;

                case ProductPurchaseStatus.NotFulfilled:
                    purchase.State = PurchaseState.Deferred;
                    break;

                case ProductPurchaseStatus.NotPurchased:
                    purchase.State = PurchaseState.Canceled;
                    break;

                default:
                    purchase.State = PurchaseState.Unknown;
                    break;
                }

                // Add to list of purchases
                purchases.Add(purchase);
            }

            return(purchases);
        }
 public static SubscriptionPurchasedEventArgs ToEventArgs(this InAppBillingPurchase purchase)
 {
     return(new SubscriptionPurchasedEventArgs
     {
         ProductId = purchase.ProductId,
         TransactionId = purchase.Id,
         TransactionDate = purchase.TransactionDateUtc,
         PurchaseToken = purchase.PurchaseToken
     });
 }
Пример #6
0
        private async void SendPurchaseToServer(InAppBillingPurchase purchase)
        {
            string restMethod = "purchaseAccess";

            System.Uri uri = new System.Uri(string.Format(Constants.RestUrl, restMethod));

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                User user = GetCurrentUser();

                if (user != null)
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
                }
                else
                {
                    return;
                }

                JObject jmessage = new JObject
                {
                    { "id", purchase.Id },
                    { "payload", purchase.Payload },
                    { "purchaseToken", purchase.PurchaseToken },
                    { "state", purchase.State.ToString() }
                };
                string        json    = jmessage.ToString();
                StringContent content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

                HttpResponseMessage response = null;
                response = client.PostAsync(uri, content).Result;

                if (response.IsSuccessStatusCode)
                {
                    string responseMessage = await response.Content.ReadAsStringAsync();

                    ChangeUserAccessStatus(true);

                    await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Успех", "Оплата проведена успешно.", "OK");

                    return;
                }
                else
                {
                    string errorInfo = await response.Content.ReadAsStringAsync();

                    string errorMessage = ParseErrorMessage(errorInfo);

                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Не выполнено", "Произошла ошибка на сервере", "OK"); });
                    return;
                }
            }
        }
        /// <summary> Consumes the given purchase </summary>
        /// <param name="purchase"></param>
        /// <returns></returns>
        public async Task <Boolean> Consume(InAppBillingPurchase purchase)
        {
            InAppBillingPurchase consumedProduct = null;

            try
            {
                consumedProduct = await CrossInAppBilling.Current.ConsumePurchaseAsync(purchase.ProductId, purchase.PurchaseToken);
            }
            catch (Exception e)
            {
            }
            return(consumedProduct != null);
        }
Пример #8
0
        public static async Task <InAppBillingPurchase?> Buy(string productId, bool consume)
        {
            IInAppBilling billing = CrossInAppBilling.Current;

            try
            {
                if (!CrossInAppBilling.IsSupported || !await billing.ConnectAsync())
                {
                    return(null);
                }

                List <InAppBillingPurchase> existingPurchases = (await billing.GetPurchasesAsync(ItemType.InAppPurchase))
                                                                .Where(p => p.ProductId == productId)
                                                                .ToList();
                foreach (var existingPurchase in existingPurchases)
                {
                    await ProcessPurchase(billing, existingPurchase, consume);
                }

                InAppBillingPurchase purchase = await billing.PurchaseAsync(productId, ItemType.InAppPurchase);

                if (purchase != null && purchase.State == PurchaseState.Purchased)
                {
                    await ProcessPurchase(billing, purchase, consume);

                    return(purchase);
                }
            }
            catch (InAppBillingPurchaseException billingEx)
            {
                if (billingEx.PurchaseError != PurchaseError.UserCancelled &&
                    billingEx.PurchaseError != PurchaseError.ServiceUnavailable)
                {
                    billingEx.Data.Add(nameof(billingEx.PurchaseError), billingEx.PurchaseError);
                    billingEx.Data.Add("Product Id", productId);
                    ExceptionService.LogException(billingEx);
                }
            }
            catch (TaskCanceledException) { }
            catch (Exception ex)
            {
                ExceptionService.LogException(ex);
            }
            finally
            {
                // Disconnect, it is okay if we never connected, this will never throw an exception
                await billing.DisconnectAsync();
            }
            return(null);
        }
Пример #9
0
        public async Task <InAppBillingPurchase> PurchaseSubscription(string productId, string payload)
        {
            var billing = CrossInAppBilling.Current;
            InAppBillingPurchase purchase = new InAppBillingPurchase();

            try
            {
                var connected = await billing.ConnectAsync(ItemType.Subscription);

                if (!connected)
                {
                    //we are offline or can't connect, don't try to purchase
                    return(null);
                }

                //check purchases
                purchase = await billing.PurchaseAsync(productId, ItemType.Subscription, payload);

                //possibility that a null came through.
                if (purchase == null)
                {
                    //did not purchase
                }
                else
                {
                    //purchased!

                    return(purchase);
                }
            }
            catch (InAppBillingPurchaseException purchaseEx)
            {
                //Billing Exception handle this based on the type
                Debug.WriteLine("Error: " + purchaseEx);
                return(null);
            }
            catch (Exception ex)
            {
                //Something else has gone wrong, log it
                Debug.WriteLine("Issue connecting: " + ex);
                return(null);
            }
            finally
            {
                await billing.DisconnectAsync();
            }
            return(purchase);
        }
Пример #10
0
        /// <summary>
        /// Consumes or Acknowledges the purchase based on consume parameter
        /// </summary>
        private static async Task ProcessPurchase(IInAppBilling billing, InAppBillingPurchase purchase, bool consume)
        {
            if (consume)
            {
                if (purchase.ConsumptionState == ConsumptionState.NoYetConsumed)
                {
                    await billing.ConsumePurchaseAsync(purchase.ProductId, purchase.PurchaseToken);
                }
                return;
            }

            if (purchase.IsAcknowledged == false)
            {
                await billing.AcknowledgePurchaseAsync(purchase.PurchaseToken);
            }
        }
Пример #11
0
        public static async Task <InAppBillingPurchase> Buy(string productId, bool consume)
        {
            try
            {
                if (!await CrossInAppBilling.Current.ConnectAsync())
                {
                    //Couldn't connect to billing, could be offline
                    return(null);
                }

                //try to purchase item
                InAppBillingPurchase purchase = await CrossInAppBilling.Current.PurchaseAsync(productId, ItemType.InAppPurchase, "apppayload");

                if (purchase != null && purchase.State == PurchaseState.Purchased)
                {
                    //Purchased
                    if (consume)
                    {
                        await Consume(purchase);
                    }
                    return(purchase);
                }
            }
            catch (InAppBillingPurchaseException billingEx)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    MessagingCenter.Send(Application.Current, MessageTypes.ExceptionOccurred, billingEx);
                });
            }
            catch (Exception ex)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    MessagingCenter.Send(Application.Current, MessageTypes.ExceptionOccurred, ex);
                });
            }
            finally
            {
                //Disconnect, it is okay if we never connected, this will never throw an exception
                await CrossInAppBilling.Current.DisconnectAsync();
            }
            return(null);
        }
        public static SubscriptionModel GetModelFromIAP(InAppBillingPurchase purchase, AccountModel user, SubscriptionModel previousSub)
        {
            var start = ResolveStartDate(purchase.TransactionDateUtc, previousSub);

            // This is for the case when the last purchase was for the last active month and they have not renewed.
            if (start == null)
            {
                return(null);
            }
            return(new SubscriptionModel()
            {
                PurchaseId = purchase.Id,
                PurchaseToken = purchase.PurchaseToken,
                StartDateTime = start.Value,
                EndDateTime = start.Value.AddMonths(1),
                PurchasedDateTime = purchase.TransactionDateUtc,
                PurchaseSource = Device.RuntimePlatform == Device.Android ? PurchaseSource.GooglePlay : PurchaseSource.AppStore,
                SubscriptionType = GetTypeFromProductId(purchase.ProductId),
                UserId = user.UserId,
                Email = user.Email
            });
        }
Пример #13
0
        public async Task <InAppBillingPurchase> GetPurchasesFirstOrDefaultAsync(ItemType itemType)
        {
            InAppBillingPurchase result = null;

            if (!CrossInAppBilling.IsSupported)
            {
                return(result);
            }

            var billing = CrossInAppBilling.Current;

            try
            {
                var connected = await billing.ConnectAsync(itemType);

                if (!connected)
                {
                    return(result);
                }

                var purchaseItems = await billing.GetPurchasesAsync(itemType);

                result = purchaseItems?.FirstOrDefault();
            }
            catch (InAppBillingPurchaseException)
            {
            }
            catch (Exception)
            {
            }
            finally
            {
                await billing.DisconnectAsync();
            }

            return(result);
        }
Пример #14
0
        private static async Task <bool> Consume(InAppBillingPurchase purchase)
        {
            //Called after we have a successful purchase or later on
            if (CrossDeviceInfo.Current.Platform != Plugin.DeviceInfo.Abstractions.Platform.Android)
            {
                return(true);
            }

            try
            {
                if (!await CrossInAppBilling.Current.ConnectAsync())
                {
                    return(false);
                }

                InAppBillingPurchase consumedItem = await CrossInAppBilling.Current.ConsumePurchaseAsync(purchase.ProductId, purchase.PurchaseToken);

                if (consumedItem != null)
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    MessagingCenter.Send(Application.Current, MessageTypes.ExceptionOccurred, ex);
                });
            }
            finally
            {
                //Disconnect, it is okay if we never connected, this will never throw an exception
                await CrossInAppBilling.Current.DisconnectAsync();
            }
            return(false);
        }
Пример #15
0
        public async Task <InAppBillingPurchase> PurchaseItem(string name, ItemType iapType, string payload)
        {
            if (!SubscriptionUtility.ValidatePurchaseType(name, iapType))
            {
                throw new InvalidOperationException($"The item that is attempting to be purchased does not have the proper IAP type.");
            }
            try
            {
                if (_isPurchasing)
                {
                    throw new InvalidOperationException("A different purchase is already in progress. Please try again.");
                }
                _isPurchasing = true;
                bool connected = false;
                try
                {
                    connected = await _billing.ConnectAsync(iapType);
                }
                catch (Exception ex)
                {
                    var message = $"Error occurred while try to connect to billing service.";
                    _logger.LogError(message, ex, name, payload);
                    throw new InvalidOperationException(message);
                }
                if (!connected)
                {
                    // we are offline or can't connect, don't try to purchase
                    _logger.LogError($"Can't connect to billing service.", null, name, payload);
                    throw new InvalidOperationException($"Can't connect to billing service. Check connection to internet.");
                }

                InAppBillingPurchase purchase = null;
                try
                {
                    //check purchases
                    purchase = await _billing.PurchaseAsync(name, iapType, payload);
                }
                catch (InAppBillingPurchaseException purchaseEx)
                {
                    var errorMsg = "";
                    switch (purchaseEx.PurchaseError)
                    {
                    case PurchaseError.AlreadyOwned:
                        errorMsg = $"Current user already owns this item.";
                        break;

                    case PurchaseError.AppStoreUnavailable:
                        errorMsg = "The App Store is unavailable. Please check your internet connection and try again.";
                        break;

                    case PurchaseError.BillingUnavailable:
                        errorMsg = "The billing service is unavailable. Please check your internet connection and try again.";
                        break;

                    case PurchaseError.DeveloperError:
                        errorMsg = "A configuration error occurred during billing. Please contact Fair Squares support.";
                        break;

                    case PurchaseError.InvalidProduct:
                        errorMsg = "This product was not found. Please contact Fair Squares support.";
                        break;

                    case PurchaseError.PaymentInvalid:
                        errorMsg = "A payment configuration error occurred during billing. Please contact Fair Squares support.";
                        break;

                    case PurchaseError.PaymentNotAllowed:
                        errorMsg = "Current user is not allowed to authorize payments.";
                        break;

                    case PurchaseError.ProductRequestFailed:
                        errorMsg = "The product request failed. Please try again.";
                        break;

                    case PurchaseError.ServiceUnavailable:
                        errorMsg = "The network connection is not available. Please check your internet connection.";
                        break;

                    case PurchaseError.UserCancelled:
                        errorMsg = "The transaction was cancelled by the user.";
                        break;

                    default:
                        errorMsg = "An error occurred while purchasing subscription. Please contact Fair Squares support.";
                        break;
                    }
                    try
                    {
                        if (purchaseEx.PurchaseError != PurchaseError.UserCancelled)
                        {
                            _logger.LogError($"Error type: '{purchaseEx.PurchaseError.ToString()}'. Error Message displayed to user: '******'.",
                                             purchaseEx, name, payload);
                        }
                    }
                    catch { }
                    throw new InvalidOperationException(errorMsg, purchaseEx);
                }
                catch (Exception ex)
                {
                    // Something else has gone wrong, log it
                    _logger.LogError("Failed to purchase subscription.", ex, name);
                    throw new InvalidOperationException(ex.Message, ex);
                }
                finally
                {
                    await _billing.DisconnectAsync();
                }
                if (purchase == null)
                {
                    // did not purchase
                    _logger.LogError($"Failed to purchase {name}.", null, name);
                    throw new InvalidOperationException("Failed to complete purchase. Please contact support.");
                }
                return(purchase);
            }
            catch
            {
                throw;
            }
            finally
            {
                _isPurchasing = false;
            }
        }
Пример #16
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            clientName = Android.OS.Build.Manufacturer + " " + Android.OS.Build.Model;
            SetContentView(Resource.Layout.premium);

            Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity = this;

            InitElements();

            if (_databaseMethods.UserExists())
            {
                if (!_methods.IsConnected())
                {
                    NoConnectionActivity.ActivityName = this;
                    StartActivity(typeof(NoConnectionActivity));
                    Finish();
                    return;
                }
                var purchaseInfo = await _accounts.AccountAuthorize(_databaseMethods.GetAccessJwt(), clientName);

                //var deserialized_info = JsonConvert.DeserializeObject<AuthorizeRootObject>(purchase_info);
                AuthorizeAfterPurchase(purchaseInfo);
            }

            FindViewById <RelativeLayout>(Resource.Id.backRL).Click += (s, e) => OnBackPressed();

            _monthBn.Click += async(s, e) =>
            {
                if (!_databaseMethods.UserExists())
                {
                    call_login_menu();
                    return;
                }

                if (!_methods.IsConnected())
                {
                    NoConnectionActivity.ActivityName = this;
                    StartActivity(typeof(NoConnectionActivity));
                    Finish();
                    return;
                }

                _monthActivityIndicator.Visibility = ViewStates.Visible;
                _monthBn.Visibility = ViewStates.Gone;

                string productId = "month_auto_subscription";
                InAppBillingService  inAppBillingService = new InAppBillingService();
                InAppBillingPurchase purchase            = new InAppBillingPurchase();

                var authorizeCheck = await _accounts.AccountAuthorize(_databaseMethods.GetAccessJwt(), clientName);

                if (/*res_card_data == Constants.status_code409 ||*/ authorizeCheck == Constants.status_code401)
                {
                    ShowSeveralDevicesRestriction();
                    return;
                }
                var deserialized = JsonConvert.DeserializeObject <AuthorizeRootObject>(authorizeCheck);
                if (deserialized != null)
                {
                    var jsonObj   = JsonConvert.SerializeObject(new { accountID = deserialized.accountID.ToString() });
                    var textBytes = Encoding.UTF8.GetBytes(jsonObj);
                    var base64    = Convert.ToBase64String(textBytes);

                    if (deserialized.accountID != null)
                    {
                        purchase = await inAppBillingService.PurchaseSubscription(productId, base64);
                    }
                }
                //else
                //purchase = await inAppBillingService.PurchaseSubscription(product_id, String.Empty);
                if (purchase != null)
                {
                    Toast.MakeText(this, TranslationHelper.GetString("waitServerSync", _ci), ToastLength.Short).Show();
                    // Inform our server.

                    var notifyServer = await _accounts.AccountSubscribeAndroid(_databaseMethods.GetAccessJwt(),
                                                                               3,
                                                                               purchase.ProductId,
                                                                               purchase.PurchaseToken);

                    //var notify_server = await accounts.AccountSubscribe(
                    //databaseMethods.GetAccessJwt(),
                    //Constants.personalGoogle.ToString(),
                    //purchase,
                    //DateTime.UtcNow.AddDays(1), // ATTENTION with days.
                    //NativeMethods.GetDeviceId()
                    //);

                    var authorizeCheckAfterPurchase = await _accounts.AccountAuthorize(_databaseMethods.GetAccessJwt(), clientName);

                    AuthorizeAfterPurchase(authorizeCheckAfterPurchase);
                    _monthActivityIndicator.Visibility = ViewStates.Gone;
                    Toast.MakeText(this, TranslationHelper.GetString("syncDoneSuccessfully", _ci), ToastLength.Short).Show();
                    return;
                }
                _monthActivityIndicator.Visibility = ViewStates.Gone;
                _monthBn.Visibility = ViewStates.Visible;
            };

            _yearBn.Click += async(s, e) =>
            {
                if (!_databaseMethods.UserExists())
                {
                    call_login_menu();
                    return;
                }

                if (!_methods.IsConnected())
                {
                    NoConnectionActivity.ActivityName = this;
                    StartActivity(typeof(NoConnectionActivity));
                    Finish();
                    return;
                }

                _yearActivityIndicator.Visibility = ViewStates.Visible;
                _yearBn.Visibility = ViewStates.Gone;

                string productId = "year_auto_subscription";
                InAppBillingService  inAppBillingService = new InAppBillingService();
                InAppBillingPurchase purchase            = new InAppBillingPurchase();

                var authorizeCheck = await _accounts.AccountAuthorize(_databaseMethods.GetAccessJwt(), clientName);

                if (/*res_card_data == Constants.status_code409 ||*/ authorizeCheck == Constants.status_code401)
                {
                    ShowSeveralDevicesRestriction();
                    return;
                }
                var deserialized = JsonConvert.DeserializeObject <AuthorizeRootObject>(authorizeCheck);
                if (deserialized != null)
                {
                    var jsonObj   = JsonConvert.SerializeObject(new { accountID = deserialized.accountID.ToString() });
                    var textBytes = Encoding.UTF8.GetBytes(jsonObj);
                    var base64    = Convert.ToBase64String(textBytes);

                    if (deserialized.accountID != null)
                    {
                        purchase = await inAppBillingService.PurchaseSubscription(productId, base64);
                    }
                }
                //else
                //purchase = await inAppBillingService.PurchaseSubscription(product_id, String.Empty);
                if (purchase != null)
                {
                    Toast.MakeText(this, TranslationHelper.GetString("waitServerSync", _ci), ToastLength.Short).Show();
                    // Inform our server.

                    var notifyServer = await _accounts.AccountSubscribeAndroid(_databaseMethods.GetAccessJwt(),
                                                                               3,
                                                                               purchase.ProductId,
                                                                               purchase.PurchaseToken);

                    //var notify_server = await accounts.AccountSubscribe(
                    //databaseMethods.GetAccessJwt(),
                    //Constants.personalGoogle.ToString(),
                    //purchase,
                    //DateTime.UtcNow.AddDays(1), // ATTENTION with days.
                    //NativeMethods.GetDeviceId()
                    //);

                    var authorizeCheckAfterPurchase = await _accounts.AccountAuthorize(_databaseMethods.GetAccessJwt(), clientName);

                    AuthorizeAfterPurchase(authorizeCheckAfterPurchase);
                    _yearActivityIndicator.Visibility = ViewStates.Gone;
                    Toast.MakeText(this, TranslationHelper.GetString("syncDoneSuccessfully", _ci), ToastLength.Short).Show();
                    return;
                }
                _yearActivityIndicator.Visibility = ViewStates.Gone;
                _yearBn.Visibility = ViewStates.Visible;
            };

            _termsBn.Click += (s, e) =>
            {
                var uri = Android.Net.Uri.Parse("https://myqrcards.com/agreement/ru");
                StartActivity(new Intent(Intent.ActionView, uri));
            };
            _politicsBn.Click += (s, e) =>
            {
                var uri = Android.Net.Uri.Parse("https://myqrcards.com/privacy-policy/ru");
                StartActivity(new Intent(Intent.ActionView, uri));
            };
        }
Пример #17
0
        public async Task <string> AccountSubscribe(string accountClientJwt, string SubscriptionId, InAppBillingPurchase purchase, DateTime ValidTill, string udid)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accountClientJwt);

                var token = JsonConvert.SerializeObject(new
                {
                    AutoRenewing       = purchase.AutoRenewing,
                    Id                 = purchase.Id,
                    Payload            = purchase.Payload,
                    ProductId          = purchase.ProductId,
                    PurchaseToken      = purchase.PurchaseToken,
                    State              = purchase.State,
                    TransactionDateUtc = purchase.TransactionDateUtc
                });

                var tokenByteArray = System.Text.Encoding.UTF8.GetBytes(token);
                var tokenBase64    = Convert.ToBase64String(tokenByteArray);

                var myContent = JsonConvert.SerializeObject(new
                {
                    //clientName = udid,//UIDevice.CurrentDevice.Name.ToString(),
                    SubscriptionId    = SubscriptionId,
                    SubscriptionToken = tokenBase64,
                    ValidTill         = ValidTill
                });
                var content = new StringContent(myContent.ToString(), Encoding.UTF8, "application/json");
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var res = await client.PostAsync(main_url + "/this/subscribe", content);

                var content_response = await res.Content.ReadAsStringAsync();

                var response_result = content_response;//.Result;
                if (res.StatusCode.ToString().ToLower() == Constants.status_code401)
                {
                    return(Constants.status_code401);
                }
                if (res.StatusCode.ToString().ToLower() == Constants.status_code409)
                {
                    return(Constants.status_code409);
                }
                return(response_result);
            }
        }
Пример #18
0
        private void BuySubs(string product_id)
        {
            if (!databaseMethods.userExists())
            {
                call_login_menu();
                return;
            }
            activityIndicator.Hidden    = false;
            month_bn.Hidden             = true;
            month_subscriptionTV.Hidden = true;
            year_bn.Hidden             = true;
            year_subscriptionTV.Hidden = true;
            InvokeInBackground(async() =>
            {
                InAppBillingService inAppBillingService = new InAppBillingService();
                //var gkgj = await inAppBillingService.PurchaseItemAsync();
                //var detais = await inAppBillingService.GetProductDetails(product_id);
                //var was_purchased_before = await inAppBillingService.WasItemPurchasedAsync(product_id);
                InAppBillingPurchase purchase = new InAppBillingPurchase();
                //if (!was_purchased_before)
                {
                    InvokeOnMainThread(() =>
                    {
                        activityIndicator.Hidden    = false;
                        month_bn.Hidden             = true;
                        month_subscriptionTV.Hidden = true;
                        InvokeInBackground(async() =>
                        {
                            string authorize_check = null;
                            try
                            {
                                authorize_check = await accounts.AccountAuthorize(databaseMethods.GetAccessJwt(), UDID);
                            }
                            catch
                            {
                                if (!methods.IsConnected())
                                {
                                    InvokeOnMainThread(() =>
                                    {
                                        NoConnectionViewController.view_controller_name = GetType().Name;
                                        this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                                        return;
                                    });
                                }
                                return;
                            }
                            if (/*res_card_data == Constants.status_code409 ||*/ authorize_check == Constants.status_code401)
                            {
                                InvokeOnMainThread(() =>
                                {
                                    ShowSeveralDevicesRestriction();
                                    return;
                                });
                                return;
                            }
                            var deserialized = JsonConvert.DeserializeObject <AuthorizeRootObject>(authorize_check);
                            if (deserialized != null)
                            {
                                var jsonObj   = JsonConvert.SerializeObject(new { accountID = deserialized.accountID.ToString() });
                                var textBytes = Encoding.UTF8.GetBytes(jsonObj);
                                var base64    = Convert.ToBase64String(textBytes);

                                if (deserialized.accountID != null)
                                {
                                    purchase = await inAppBillingService.PurchaseSubscription(product_id, base64);
                                }
                            }
                            //else
                            //purchase = await inAppBillingService.PurchaseSubscription(product_id, String.Empty);
                            if (purchase != null)
                            {
                                InvokeOnMainThread(() =>
                                {
                                    ShowAttentionSyncWaiting();
                                });
                                // Inform our server.
                                var UDID = UIDevice.CurrentDevice.IdentifierForVendor.ToString();
                                string authorize_check_after_purchase = null;
                                try
                                {
                                    var notify_server = await accounts.AccountSubscribe(
                                        databaseMethods.GetAccessJwt(),
                                        Constants.personalApple.ToString(),
                                        purchase,
                                        DateTime.UtcNow.AddDays(1),             // ATTENTION with days.
                                        UDID);

                                    authorize_check_after_purchase = await accounts.AccountAuthorize(databaseMethods.GetAccessJwt(), UDID);
                                }
                                catch
                                {
                                    if (!methods.IsConnected())
                                    {
                                        InvokeOnMainThread(() =>
                                        {
                                            NoConnectionViewController.view_controller_name = GetType().Name;
                                            this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                                            return;
                                        });
                                    }
                                    return;
                                }
                                InvokeOnMainThread(() =>
                                {
                                    AuthorizeAfterPurchase(authorize_check_after_purchase);
                                    ShowSyncSuccessful();
                                });
                            }

                            InvokeOnMainThread(() =>
                            {
                                activityIndicator.Hidden    = true;
                                month_bn.Hidden             = false;
                                month_subscriptionTV.Hidden = false;
                                year_bn.Hidden             = false;
                                year_subscriptionTV.Hidden = false;
                            });
                        });
                    });
                }
            });
        }