Exemple #1
0
        private void SetUpAuProjectAndClient()
        {
            BillingClient au = new BillingClient
            {
                BillingClientId = 9,
                Name            = "au",
                AddressLine1    = null,
                AddressLine2    = null,
                CityStateZip    = null,
                Email           = null
            };

            Project vsm = new Project
            {
                ProjectId       = 9,
                Name            = "vsm",
                Start           = null,
                End             = null,
                BillingClientId = 9,
                BillingClient   = au
            };

            database.Projects.Add(vsm);
            database.SaveChanges();
        }
Exemple #2
0
        public void TestShoppingUriBatch()
        {
            var bc     = new BillingClient(true);
            var result = bc.GetPaymentUrls("0", new[] { "12", "13", "14", "0", "-2" });

            Assert.AreEqual(5, result.Count);
        }
Exemple #3
0
        private void createFakeProject()
        {
            var client = new BillingClient
            {
                BillingClientId = 3,
                Name            = null,
                AddressLine1    = null,
                AddressLine2    = null,
                CityStateZip    = null,
                Email           = null
            };

            database.BillingClients.Add(client);

            var project = new Project
            {
                ProjectId       = 6,
                Name            = "proyecto",
                BillingClientId = 3,
                Start           = null,
                End             = DateTime.UtcNow,
                BillingClient   = client
            };

            database.Projects.Add(project);
            database.SaveChanges();
        }
Exemple #4
0
        /// <summary>
        /// Disconnects BillingClient. Needs to be called in the Activity OnDestroy
        /// </summary>
        public Task StopAsync()
        {
            try
            {
                // Reset the Task Source for Billing Client Connection
                _connected?.TrySetCanceled();
                _connected = null;

                if (_billingClient != null && _billingClient.IsReady)
                {
                    _billingClient.EndConnection();
                    _billingClient.Dispose();
                    _billingClient = null;
                }
            }
            catch (Exception ex)
            {
                Log.Debug(_billingTag, $"Unable to EndConnection: {ex.Message}");
            }

            Log.Debug(_billingTag, "Disconnected");

            // Completed Task
            return(Task.CompletedTask);
        }
Exemple #5
0
        /// <summary>
        /// Initializes and Connects to Billing Client. Needs to be called in the Activity OnCreate
        /// </summary>
        public Task StartAsync()
        {
            Log.Debug(_billingTag, "Build BillingClient. connection...");

            // Setup the Task Source to wait for Connection
            if (_connected != null)
            {
                throw new InAppPurchaseException(PurchaseError.DeveloperError, "BillingClient has been already started");
            }

            _connected = new TaskCompletionSource <object>();

            _billingClient = BillingClient.NewBuilder(Application.Context)
                             .SetListener(this)
                             .EnablePendingPurchases()
                             .Build();

            // Attempt to connect to the service
            if (!_billingClient.IsReady)
            {
                Log.Debug(_billingTag, "Start Connection...");
                _billingClient.StartConnection(this);
            }
            else
            {
                // Already connected. Complete the _connected Task Source
                _connected.TrySetResult(null);
            }

            // Return awaitable Task which is signaled when the BillingClient calls OnBillingServiceDisconnected
            return(_connected.Task);
        }
Exemple #6
0
        public static async Task <BillingClient> GetBillingClient()
        {
            // Import config values from appsettings.json into billingClient, or throw an error if not found
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            var tenantId       = Configuration["TenantDomain"];
            var clientId       = Configuration["ClientID"];
            var secret         = Configuration["ClientSecret"];
            var subscriptionId = Configuration["SubscriptionID"];

            if (new List <string> {
                tenantId, clientId, secret, subscriptionId
            }.Any(i => String.IsNullOrEmpty(i)))
            {
                throw new InvalidOperationException("Enter TenantDomain, ClientID, ClientSecret and SubscriptionId in appsettings.json");
            }
            else
            {
                // Build the service credentials and ARM client to call the billing API
                var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);

                var billingClient = new BillingClient(serviceCreds);
                billingClient.SubscriptionId = subscriptionId;
                return(billingClient);
            }
        }
Exemple #7
0
        private void createAuClientAndProject()
        {
            var auClient = new BillingClient
            {
                BillingClientId = 2,
                Name            = "Au",
                AddressLine1    = "123 Street",
                AddressLine2    = "",
                CityStateZip    = "DetroitMI48226",
                Email           = "*****@*****.**"
            };

            database.BillingClients.Add(auClient);

            var vsmProject = new Project
            {
                ProjectId       = 5,
                Name            = "VSM",
                BillingClientId = 2,
                Start           = DateTime.Now,
                End             = DateTime.UtcNow,
                BillingClient   = auClient
            };

            database.Projects.Add(vsmProject);
            database.SaveChanges();
        }
 public DonationHandler(Activity parent)
 {
     parent_activity = parent;
     dispatcher      = MessageDispatcher.GetInstance();
     billingClient   = BillingClient.NewBuilder(Application.Context)
                       .SetListener(this)
                       .EnablePendingPurchases()
                       .Build();
 }
Exemple #9
0
        /// <summary>
        /// Start a connection on billingclient
        /// </summary>
        /// <returns></returns>
        public async Task <bool> ConnectAsync()
        {
            _tcsConnect = new TaskCompletionSource <bool>();

            BillingClient = BillingClient.NewBuilder(CurrentContext).EnablePendingPurchases().SetListener(this).Build();

            BillingClient.StartConnection(this);

            return(await _tcsConnect?.Task);
        }
Exemple #10
0
        /// <summary>
        /// Disconnects from BillingClient
        /// </summary>
        /// <returns></returns>
        public bool Disconnect()
        {
            if (BillingClient != null)
            {
                BillingClient.EndConnection();
                BillingClient = null;
            }

            return(true);
        }
Exemple #11
0
        /// <summary>
        /// Completes the Purchase
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        private async Task <PurchaseResult> DoPurchaseAsync(SkuDetails product)
        {
            if (BillingClient == null || !BillingClient.IsReady)
            {
                await ConnectAsync();
            }
            _tcsPurchase = new TaskCompletionSource <PurchaseResult>();

            BillingFlowParams flowParams   = BillingFlowParams.NewBuilder().SetSkuDetails(product).Build();
            BillingResult     responseCode = BillingClient.LaunchBillingFlow(CrossCurrentActivity.Current.Activity, flowParams);

            return(await _tcsPurchase?.Task ?? default);
        }
Exemple #12
0
        /// <summary>
        /// Completes Consume purchase with Api request
        /// </summary>
        /// <param name="purchaseToken"></param>
        /// <param name="payload"></param>
        /// <returns></returns>
        private async Task <PurchaseResult> CompleteConsume(string purchaseToken, string payload = null)
        {
            _tcsConsume = new TaskCompletionSource <PurchaseResult>();
            var consumeParams = ConsumeParams.NewBuilder().SetPurchaseToken(purchaseToken);

            if (payload != null)
            {
                consumeParams.SetDeveloperPayload(payload);
            }
            BillingClient.ConsumeAsync(consumeParams.Build(), this);

            return(await _tcsConsume?.Task);
        }
Exemple #13
0
        /// <summary>
        /// Get All purchases regardless of status
        /// </summary>
        /// <param name="itemType"></param>
        /// <param name="verifyPurchase"></param>
        /// <returns></returns>
        public async Task <List <PurchaseResult> > GetPurchasesAsync(ItemType itemType, IInAppBillingVerifyPurchase verifyPurchase = null, string verifyOnlyProductId = null)
        {
            if (BillingClient == null || !BillingClient.IsReady)
            {
                await ConnectAsync();
            }

            var prms           = SkuDetailsParams.NewBuilder();
            var type           = itemType == ItemType.InAppPurchase ? BillingClient.SkuType.Inapp : BillingClient.SkuType.Subs;
            var purchaseResult = BillingClient.QueryPurchases(type);
            var purchases      = await GetPurchasesAsync(purchaseResult.PurchasesList);

            return(purchases);
        }
Exemple #14
0
        /// <summary>
        /// Get Purchases with the status information
        /// </summary>
        /// <param name="itemType"></param>
        /// <returns></returns>
        public async Task <List <PurchaseResult> > GetPurchaseHistoryAsync(ItemType itemType)
        {
            if (BillingClient == null || !BillingClient.IsReady)
            {
                await ConnectAsync();
            }

            _tcsPurchaseHistory = new TaskCompletionSource <List <PurchaseResult> >();

            var type = itemType == ItemType.InAppPurchase ? BillingClient.SkuType.Inapp : BillingClient.SkuType.Subs;

            BillingClient.QueryPurchaseHistoryAsync(type, this);

            return(await _tcsPurchaseHistory?.Task ?? default);
        }
Exemple #15
0
        /// <summary>
        /// Get Product Information with Prices
        /// </summary>
        /// <param name="productIds">Skus of products</param>
        /// <param name="itemType">Subscription or iap product</param>
        /// <returns></returns>
        public async Task <List <InAppBillingProduct> > GetProductsAsync(List <string> productIds, ItemType itemType = ItemType.InAppPurchase)
        {
            if (BillingClient == null || !BillingClient.IsReady)
            {
                await ConnectAsync();
            }

            _tcsProducts = new TaskCompletionSource <List <InAppBillingProduct> >();
            var prms = SkuDetailsParams.NewBuilder();
            var type = itemType == ItemType.InAppPurchase ? BillingClient.SkuType.Inapp : BillingClient.SkuType.Subs;

            prms.SetSkusList(productIds).SetType(type);

            BillingClient.QuerySkuDetailsAsync(prms.Build(), this);

            return(await _tcsProducts?.Task ?? default);
        }
Exemple #16
0
        public async Task <bool> RunDailyTask(bool noEmail = false)
        {
            bool result = true;

            // Check client tool auths
            ResourceClientUtility.CheckExpiringClients(ResourceClientUtility.SelectExpiringClients(), ResourceClientUtility.SelectExpiringEveryone(), noEmail);
            ResourceClientUtility.CheckExpiredClients(ResourceClientUtility.SelectExpiredClients(), ResourceClientUtility.SelectExpiredEveryone(), noEmail);

            using (var bc = new BillingClient())
            {
                BillingProcessResult bpr;

                // Update Data and DataClean tables
                bpr = await bc.BillingProcessDataUpdate(BillingCategory.Tool, true);

                result = result && bpr.Success;

                bpr = await bc.BillingProcessDataUpdate(BillingCategory.Room, true);

                result = result && bpr.Success;

                bpr = await bc.BillingProcessDataUpdate(BillingCategory.Store, true);

                result = result && bpr.Success;

                //2009-08-01 Populate the Billing temp tables
                DateTime ed     = DateTime.Now.Date.AddDays(-1); //must be yesterday
                DateTime period = ed.FirstOfMonth();

                bpr = await bc.BillingProcessStep1(BillingCategory.Tool, period, period.AddMonths(1), 0, 0, true, true);

                result = result && bpr.Success;

                bpr = await bc.BillingProcessStep1(BillingCategory.Room, period, period.AddMonths(1), 0, 0, true, true);

                result = result && bpr.Success;

                bpr = await bc.BillingProcessStep1(BillingCategory.Store, period, period.AddMonths(1), 0, 0, true, true);

                result = result && bpr.Success;
            }

            return(result);
        }
        public async Task <bool> UpdateBilling(UpdateBillingCommand cmd)
        {
            bool isTemp = cmd.StartDate == DateTime.Now.FirstOfMonth();

            using (var bc = new BillingClient())
            {
                LNF.Models.Billing.Process.BillingProcessResult toolDataCleanResult = null;
                LNF.Models.Billing.Process.BillingProcessResult toolDataResult      = null;
                LNF.Models.Billing.Process.BillingProcessResult toolStep1Result     = null;
                LNF.Models.Billing.Process.BillingProcessResult roomDataCleanResult = null;
                LNF.Models.Billing.Process.BillingProcessResult roomDataResult      = null;
                LNF.Models.Billing.Process.BillingProcessResult roomStep1Result     = null;
                LNF.Models.Billing.Process.BillingProcessResult subsidyResult       = null;

                // Tool
                toolDataCleanResult = await bc.BillingProcessDataClean(LNF.Models.Billing.BillingCategory.Tool, cmd.StartDate, cmd.EndDate, cmd.ClientID, 0);

                toolDataResult = await bc.BillingProcessData(LNF.Models.Billing.BillingCategory.Tool, cmd.StartDate, cmd.EndDate, cmd.ClientID, 0);

                toolStep1Result = await bc.BillingProcessStep1(LNF.Models.Billing.BillingCategory.Tool, cmd.StartDate, cmd.EndDate, cmd.ClientID, 0, isTemp, true);

                // Room
                roomDataCleanResult = await bc.BillingProcessDataClean(LNF.Models.Billing.BillingCategory.Room, cmd.StartDate, cmd.EndDate, cmd.ClientID, 0);

                roomDataResult = await bc.BillingProcessData(LNF.Models.Billing.BillingCategory.Room, cmd.StartDate, cmd.EndDate, cmd.ClientID, 0);

                roomStep1Result = await bc.BillingProcessStep1(LNF.Models.Billing.BillingCategory.Room, cmd.StartDate, cmd.EndDate, cmd.ClientID, 0, isTemp, true);

                // Subsidy
                if (!isTemp)
                {
                    subsidyResult = await bc.BillingProcessStep4("subsidy", cmd.StartDate, cmd.ClientID);
                }

                UpdateBillingResult updateResult = new UpdateBillingResult(toolDataCleanResult, toolDataResult, toolStep1Result, roomDataCleanResult, roomDataResult, roomStep1Result, subsidyResult);

                if (updateResult.HasError())
                {
                    throw new Exception(updateResult.GetErrorMessage());
                }

                return(true);
            }
        }
Exemple #18
0
        /// <summary>
        /// If you use the Google Play Billing Library version 2.0 or newer, you must acknowledge all purchases within three days.
        /// </summary>
        /// <param name="purchase"></param>
        /// <returns></returns>
        private async Task <bool> NotifyFullFillmentAsync(Purchase purchase)
        {
            if (!purchase.IsAcknowledged)
            {
                if (BillingClient == null || !BillingClient.IsReady)
                {
                    await ConnectAsync();
                }

                _tcsAcknowledge = new TaskCompletionSource <bool>();

                AcknowledgePurchaseParams acknowledgePurchaseParams =
                    AcknowledgePurchaseParams.NewBuilder()
                    .SetPurchaseToken(purchase.PurchaseToken)
                    .Build();
                BillingClient.AcknowledgePurchase(acknowledgePurchaseParams, this);

                return(await _tcsAcknowledge?.Task);
            }
            return(true);
        }
Exemple #19
0
        public static async Task Run()
        {
            BillingClient billingClient = await GetBillingClient();

            // Call the invoices service and expand the downloadURL, this call may take a while'
            // TODO: handle 404 invoice not found
            Write("Calling invoice service for all available invoices...");
            List <Invoice> allInvoices = billingClient.Invoices.List("downloadUrl").ToList();

            Write("{0} invoice(s) received.  Press ENTER to see them.", allInvoices.Count);
            Console.ReadLine();

            allInvoices.ForEach(inv => {
                Write("\tName: {0}", inv.Name);
                Write("\tDate: {0} to {1}", inv.InvoicePeriodStartDate, inv.InvoicePeriodEndDate);
                Write("\tPress ENTER to open PDF in browser");
                Console.ReadLine();
                OpenURL(inv.DownloadUrl.Url);
            });
            Write(Environment.NewLine);
        }
Exemple #20
0
 public BillingClientTest(IConfiguration configuration, IOptionsMonitor <ILog> option)
 {
     billingClient = new BillingClient(configuration, option);
 }
 public BillingClientTest()
 {
     billingClient = new BillingClient();
 }
 public BillingClientTest()
 {
     billingClient = new BillingClient();
 }
 public void TestShoppingUriBatch()
 {
     var bc = new BillingClient(true);
     var result = bc.GetPaymentUrls("0", new[] { "12", "13", "14", "0", "-2" });
 }
Exemple #24
0
        public async Task <bool> RunMonthlyTask(bool noEmail = false)
        {
            try
            {
                bool result = true;

                // This is run at midnight on the 1st of the month. So the period should be the 1st of the previous month.
                DateTime period = DateTime.Now.FirstOfMonth().AddMonths(-1);

                using (var bc = new BillingClient())
                {
                    // This sends apportionment emails to clients
                    await bc.SendUserApportionmentReport(new UserApportionmentReportOptions()
                    {
                        Period  = period,
                        NoEmail = noEmail
                    });

                    // 2008-04-30
                    // Monthly financial report
                    await bc.SendFinancialManagerReport(new FinancialManagerReportOptions()
                    {
                        Period         = period,
                        IncludeManager = !noEmail
                    });

                    // This sends room expiration emails
                    RoomAccessExpirationCheck roomAccessExpirationCheck = new RoomAccessExpirationCheck();
                    int count = await roomAccessExpirationCheck.Run();

                    ////2009-08-01 Populate the BillingTables

                    //first day of last month
                    DateTime sd = period;
                    DateTime ed = period.AddMonths(1);

                    BillingProcessResult bpr;

                    bpr = await bc.BillingProcessStep1(BillingCategory.Tool, sd, ed, 0, 0, false, true);

                    result = result && bpr.Success;

                    bpr = await bc.BillingProcessStep1(BillingCategory.Room, sd, ed, 0, 0, false, true);

                    result = result && bpr.Success;

                    bpr = await bc.BillingProcessStep1(BillingCategory.Store, sd, ed, 0, 0, false, true);

                    result = result && bpr.Success;

                    bpr = await bc.BillingProcessStep4("subsidy", sd, 0);

                    result = result && bpr.Success;
                }

                return(result);
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return(false);
            }
        }
Exemple #25
0
        public void Test()
        {
            int createFileIndex = 1;

            string[] allFiles = Directory.GetFiles(path, "*.xlsx");
            foreach (string strFile in allFiles)
            {
                File.Delete(strFile);
            }
            ListBoxItemAdd(this, this.listBox1, "프로그램 시작 합니다. ^_^");
            foreach (int indexChecked in checkedListBox1.CheckedIndices)
            {
                String lineStr = tt[indexChecked].ToString();
                Console.WriteLine(lineStr);
                try
                {
                    string[] sArray = lineStr.Split('	');
                    if (sArray.Count() < 2)                                      //작업완료 판단
                    {
                        break;
                    }

                    Company            = sArray[0];
                    UIN                = sArray[1].Replace(" ", "");
                    SecretIdfromeFile  = sArray[2].Replace(" ", "");
                    SecretKeyfromeFile = sArray[3].Replace(" ", "");
                    SecretKeyfromeFile = sArray[3].Replace(" ", "");
                    CVMRegion          = sArray[4].Replace(" ", "");

                    BeginTime = dateTimePicker1.Value.ToString("yyyy-MM-01 00:00:00");
                    EndTime   = dateTimePicker1.Value.ToString("yyyy-MM-01 00:00:01");
                    months    = dateTimePicker1.Value.ToString("yyyy년MM월");
                    Console.WriteLine(Company);
                    Console.WriteLine(UIN);
                    Console.WriteLine(SecretIdfromeFile);
                    Console.WriteLine(SecretKeyfromeFile);
                    Console.WriteLine(BeginTime);
                    Console.WriteLine(EndTime);
                    Thread.Sleep(1000);
                    ListBoxItemAdd(this, this.listBox1, "======<< 업체명 : " + Company + " >>=====");

                    fileName = createFileIndex + "-" + Company + "-" + months + ".xlsx";   //파일생성
                    WriteExel(fileName, 1, 1, "TotalCost");
                    WriteExel("모든업체-" + months + ".xlsx", allCompanyIndex, 1, Company);

                    Credential cred = new Credential
                    {
                        SecretId  = SecretIdfromeFile,
                        SecretKey = SecretKeyfromeFile
                    };

                    ClientProfile clientProfile = new ClientProfile();
                    HttpProfile   httpProfile   = new HttpProfile();
                    httpProfile.Endpoint      = ("billing.tencentcloudapi.com");
                    clientProfile.HttpProfile = httpProfile;
                    BillingClient client = new BillingClient(cred, CVMRegion, clientProfile);
                    DescribeBillSummaryByProductRequest req = new DescribeBillSummaryByProductRequest();
                    string strParams = "{\"PayerUin\":\"" + UIN + "\",\"BeginTime\":\"" + BeginTime + "\",\"EndTime\":\"" + EndTime + "\"}";
                    req = DescribeBillSummaryByProductRequest.FromJsonString <DescribeBillSummaryByProductRequest>(strParams);
                    DescribeBillSummaryByProductResponse resp = client.DescribeBillSummaryByProduct(req).ConfigureAwait(false).GetAwaiter().GetResult();
                    //  Console.WriteLine(AbstractModel.ToJsonString(resp));
                    String ttt = AbstractModel.ToJsonString(resp);

                    String total = GetSummaryTotal(ttt);
                    WriteExel(fileName, 1, 2, total);
                    WriteExel("모든업체-" + months + ".xlsx", allCompanyIndex, 2, total);
                    allCompanyIndex++;

                    ListBoxItemAdd(this, this.listBox1, "Total : =》  " + total);

                    Dictionary <string, string> Overview = GetSummaryOverview(ttt);
                    exelIndex = 2;
                    foreach (var item in Overview)
                    {
                        Console.WriteLine(item.Key + item.Value);
                        WriteExel(fileName, exelIndex, 1, item.Key);
                        WriteExel(fileName, exelIndex, 2, item.Value);
                        exelIndex++;
                        ListBoxItemAdd(this, this.listBox1, item.Key + "  --->    " + item.Value);
                    }
                    createFileIndex++;
                    Thread.Sleep(100);
                }
                catch (Exception e)
                {
                    //WriteExel(fileName, exelIndex, 1, Company);
                    WriteExel("모든업체-" + months + ".xlsx", allCompanyIndex, 2, "에러");
                    createFileIndex++;
                    ListBoxItemAdd(this, this.listBox1, "<< 업체명 : " + Company + " >> 요금 실패~~");
                }
                ListBoxItemAdd(this, this.listBox1, " ");
                ListBoxItemAdd(this, this.listBox1, " ");
            }
        }
 internal void Init(PBChannel channel)
 {
     m_BillingClient = new BillingClient(channel, this);
 }