public async Task <ActionResult> ResourceMapping()
        {
            string token2 = await GetGraphAccessToken(new string[] { "https://management.core.windows.net//user_impersonation" });



            // Construct the query
            HttpClient         client   = new HttpClient();
            HttpRequestMessage request2 = new HttpRequestMessage(HttpMethod.Get, Globals.MicrosoftGraphSubscriptionApi);

            request2.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token2);

            // Ensure a successful response
            HttpResponseMessage response2 = await client.SendAsync(request2);

            response2.EnsureSuccessStatusCode();

            // Populate the data store with the first page of groups
            string json2 = await response2.Content.ReadAsStringAsync();

            SubscriptionResponse result2 = JsonConvert.DeserializeObject <SubscriptionResponse>(json2);


            dynamic data = JObject.Parse(json2);


            ViewBag.sublist = new SelectList(data.value, "subscriptionId", "displayName");

            return(View());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Subscribes to DataChanged events for the provided items.
        /// </summary>
        /// <param name="items">List of Identity instances to subscribe to.</param>
        private static async Task SubscribeDataChanged(List <Identity> items)
        {
            if (items.Any())
            {
                LogResult();
            }
            else
            {
                Console.WriteLine("Unsubscribe all DataChanged subscriptions.");
            }

            SubscriptionResponse subscriptionResponse = await _client.SubscribeAsync(EnumSubscriptionType.DataChanged, items);

            if (subscriptionResponse.Error != null)
            {
                Console.WriteLine(string.Format("An error has occurred : {0}", subscriptionResponse.Error?.First().Message));
            }
            else
            {
                foreach (ItemValue itemValue in subscriptionResponse.Data)
                {
                    Console.WriteLine("ItemValue: {0}", itemValue);
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 3
0
        public SubscriptionResponse Unsubscribe(SubscriptionRequest request)
        {
            Subscription         subscription = request.Subscription;
            SubscriptionResponse response     = new SubscriptionResponse();

            try
            {
                repository.DeleteSubscription(subscription);
            }
            catch (DataException ex)
            {
                Log(ex.Message, ex.StackTrace);
                response.Status  = StatusCode.DatabaseError;
                response.Message = "An error occurred while processing the transaction";
                return(response);
            }
            catch (Exception ex)
            {
                Log(ex.Message, ex.StackTrace);
                response.Status  = StatusCode.InternalError;
                response.Message = "An error has occurred, please try again later";
                return(response);
            }

            response.Status  = StatusCode.Success;
            response.Message = subscription.EmailAddress + " has unsubscribed.";

            return(response);
        }
Exemplo n.º 4
0
    static void EstablishInitialMockSetups()
    {
        subscription_policies
        .SetupGet(_ => _.Connecting)
        .Returns(() =>
        {
            var policy = new Mock <IAsyncPolicy>();
            policy.Setup(_ => _.ExecuteAsync(Moq.It.IsAny <Func <CancellationToken, Task> >(), Moq.It.IsAny <CancellationToken>()))
            .Returns <Func <CancellationToken, Task>, CancellationToken>((callback, cancellationToken) => Task.Run(async() =>
            {
                while (!policy_cts.Token.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        await callback(cancellationToken).ConfigureAwait(false);
                    }
                    catch
                    { }
                    await Task.Delay(10).ConfigureAwait(false);
                }
            }));
            return(policy.Object);
        });

        event_horizon_connection = new Mock <IEventHorizonConnection>();
        event_horizon_connection_factory
        .Setup(_ => _.Create(producer_microservice_address, execution_context))
        .Returns(event_horizon_connection.Object);
        event_horizon_connection
        .Setup(_ => _.Connect(subscription_id, Moq.It.IsAny <StreamPosition>(), Moq.It.IsAny <CancellationToken>()))
        .Returns(Task.FromResult(SubscriptionResponse.Succeeded(consent)));

        get_next_event
        .Setup(_ => _.GetNextEventToReceiveFor(subscription_id, Moq.It.IsAny <CancellationToken>()))
        .Returns(Task.FromResult(subscription_stream_position));

        stream_processor = new Mock <IStreamProcessor>();
        stream_processor_factory
        .Setup(_ => _.Create(Moq.It.IsAny <ConsentId>(), subscription_id, execution_context, Moq.It.IsAny <EventsFromEventHorizonFetcher>()))
        .Returns(stream_processor.Object);

        stream_processor
        .Setup(_ => _.StartAndWait(Moq.It.IsAny <CancellationToken>()))
        .Returns <CancellationToken>(cancellationToken => Task.Run(async() =>
        {
            while (!stream_processor_cts.Token.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(50).ConfigureAwait(false);
            }
        }));
        event_horizon_connection
        .Setup(_ => _.StartReceivingEventsInto(Moq.It.IsAny <AsyncProducerConsumerQueue <StreamEvent> >(), Moq.It.IsAny <CancellationToken>()))
        .Returns <AsyncProducerConsumerQueue <StreamEvent>, CancellationToken>((_, cancellationToken) => Task.Run(async() =>
        {
            while (!event_horizon_connection_cts.Token.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(50).ConfigureAwait(false);
            }
        }));
    }
Exemplo n.º 5
0
        public void CanFetchAndDeserializeCorrectly()
        {
            var expected = new SubscriptionResponse
            {
                Amount          = 44.0m,
                IntervalLength  = 1,
                IntervalUnit    = "month",
                CreatedAt       = DateTimeOffset.Parse("2011-09-12T13:51:30Z"),
                Currency        = "GBP",
                Name            = "London Gym Membership",
                Description     = "Entitles you to use all of the gyms around London",
                ExpiresAt       = null,
                Id              = "1580",
                MerchantId      = "WOQRUJU9OH2HH1",
                Status          = "cancelled",
                UserId          = "638",
                Uri             = "https://gocardless.com/api/v1/subscriptions/1580",
                SubResourceUris =
                {
                    Bills = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/bills?source_id=1580"
                }
            };

            DeepAssertHelper.AssertDeepEquality(expected, new ApiClient("asdf").CancelSubscription("1580"));
        }
Exemplo n.º 6
0
        public async Task CanUpdateSubscription()
        {
            // Given
            string customerId = await GetFirstCustomerWithValidMandate();

            ListResponse <SubscriptionResponse> subscriptions = await SubscriptionClient.GetSubscriptionListAsync(customerId);

            // When
            if (subscriptions.Count > 0)
            {
                string subscriptionId             = subscriptions.Items.First().Id;
                SubscriptionUpdateRequest request = new SubscriptionUpdateRequest()
                {
                    Description = $"Updated subscription {Guid.NewGuid()}"
                };
                SubscriptionResponse response = await SubscriptionClient.UpdateSubscriptionAsync(customerId, subscriptionId, request);

                // Then
                Assert.AreEqual(request.Description, response.Description);
            }
            else
            {
                Assert.Inconclusive("No subscriptions found that could be cancelled");
            }
        }
Exemplo n.º 7
0
        public void SubscribeSuccess()
        {
            var mockServiceClient = new Mock <INewsletterService>();
            SubscriptionResponse getSubscriptionResponse = new SubscriptionResponse();

            getSubscriptionResponse.Status  = StatusCode.RecordNotFound;
            getSubscriptionResponse.Message = "Subscription not found";

            mockServiceClient.Setup(service => service.GetSubscription(It.IsAny <SubscriptionRequest>())).Returns(getSubscriptionResponse);

            SubscriptionResponse subscribeResponse = new SubscriptionResponse();

            subscribeResponse.Status       = StatusCode.Success;
            subscribeResponse.Message      = "Subscribed successfully";
            subscribeResponse.Subscription = CreateServiceSubscription();

            mockServiceClient.Setup(service => service.Subscribe(It.IsAny <SubscriptionRequest>())).Returns(subscribeResponse);

            HomeController    controller = new HomeController(mockServiceClient.Object);
            SubscriptionModel model      = CreateModelData();
            ViewResult        result     = controller.Subscribe(model) as ViewResult;

            Assert.IsNotNull(result);
            Assert.IsTrue(controller.ModelState.IsValid);
            Assert.IsTrue(model.Subscribed);
            Assert.AreEqual(model.Message, subscribeResponse.Message);
        }
Exemplo n.º 8
0
        public async Task CanCreateSubscription()
        {
            // Given
            string customerId = await GetFirstCustomerWithValidMandate();

            SubscriptionRequest subscriptionRequest = new SubscriptionRequest
            {
                Amount      = new Amount(Currency.EUR, "100.00"),
                Times       = 5,
                Interval    = "1 month",
                Description = $"Subscription {Guid.NewGuid()}", // Subscriptions must have a unique name
                WebhookUrl  = "http://www.google.nl",
                StartDate   = DateTime.Now.AddDays(1)
            };

            // When
            SubscriptionResponse subscriptionResponse = await SubscriptionClient.CreateSubscriptionAsync(customerId, subscriptionRequest);

            // Then
            Assert.AreEqual(subscriptionRequest.Amount.Value, subscriptionResponse.Amount.Value);
            Assert.AreEqual(subscriptionRequest.Amount.Currency, subscriptionResponse.Amount.Currency);
            Assert.AreEqual(subscriptionRequest.Times, subscriptionResponse.Times);
            Assert.AreEqual(subscriptionRequest.Interval, subscriptionResponse.Interval);
            Assert.AreEqual(subscriptionRequest.Description, subscriptionResponse.Description);
            Assert.AreEqual(subscriptionRequest.WebhookUrl, subscriptionResponse.WebhookUrl);
            Assert.AreEqual(subscriptionRequest.StartDate.Value.Date, subscriptionResponse.StartDate);
        }
Exemplo n.º 9
0
        public async Task CanCreateSubscription()
        {
            // Given
            string customerId = await this.GetFirstCustomerWithValidMandate();

            SubscriptionRequest subscriptionRequest = new SubscriptionRequest();

            subscriptionRequest.Amount      = 100;
            subscriptionRequest.Times       = 5;
            subscriptionRequest.Interval    = "1 month";
            subscriptionRequest.Description = $"Subscription {DateTime.Now}"; // Subscriptions must have a unique name
            subscriptionRequest.WebhookUrl  = "http://www.google.nl";
            subscriptionRequest.StartDate   = DateTime.Now.AddDays(1);

            // When
            SubscriptionResponse subscriptionResponse = await this._subscriptionClient.CreateSubscriptionAsync(customerId, subscriptionRequest);

            // Then
            Assert.AreEqual(subscriptionRequest.Amount, subscriptionResponse.Amount);
            Assert.AreEqual(subscriptionRequest.Times, subscriptionResponse.Times);
            Assert.AreEqual(subscriptionRequest.Interval, subscriptionResponse.Interval);
            Assert.AreEqual(subscriptionRequest.Description, subscriptionResponse.Description);
            Assert.AreEqual(subscriptionRequest.WebhookUrl, subscriptionResponse.Links.WebhookUrl);
            Assert.AreEqual(subscriptionRequest.StartDate.Value.Date, subscriptionResponse.StartDate);
        }
Exemplo n.º 10
0
        public SubscriptionResponse GetSubscription(SubscriptionRequest request)
        {
            Subscription         subscription = request.Subscription;
            SubscriptionResponse response     = new SubscriptionResponse();

            try
            {
                response.Subscription = repository.GetSubscriptionByEmail(subscription.EmailAddress);
            }
            catch (DataException ex)
            {
                Log(ex.Message, ex.StackTrace);
                response.Status  = StatusCode.DatabaseError;
                response.Message = "An error occurred while processing the transaction";
                return(response);
            }
            catch (Exception ex)
            {
                Log(ex.Message, ex.StackTrace);
                response.Status  = StatusCode.InternalError;
                response.Message = "An error has occurred, please try again later";
                return(response);
            }

            if (response.Subscription == null)
            {
                response.Status  = StatusCode.RecordNotFound;
                response.Message = subscription + " is not subscribed to this newsletter.";
                return(response);
            }

            response.Status  = StatusCode.Success;
            response.Message = response.Subscription.EmailAddress + " subscribed to this newsletter on " + response.Subscription.SubscriptionDate.ToShortDateString();
            return(response);
        }
Exemplo n.º 11
0
        public SubscriptionResponse Subscribe(string mobileNumber, InputMechanisms inputMechanism, string keyword, string shortCode, int reference)
        {
            SubscriptionResponse response = new SubscriptionResponse
            {
                MobileNumber = mobileNumber,
                Service      = this.service,
                NetworkID    = CUtility.GetNetworkID(mobileNumber)
            };

            if (IsSubscribed(mobileNumber, this.service.ID))
            {
                response.Status = ServiceMessages.AlreadySubscribed;
                return(response);
            }

            response.SubscriptionID = AddSubscription(service.ID, mobileNumber, response.NetworkID, reference, shortCode, keyword);
            SendSubscribeResponse(service, response.SubscriptionID, mobileNumber, reference, CSubscriptionEngineCapsule.RequestResults.Success);

            AddSubscriptionInteraction(response.SubscriptionID, (int)inputMechanism, InteractionTypes.Subscribe);
            AddSubscriptionInteraction(response.SubscriptionID, (int)inputMechanism, InteractionTypes.Confirmation);

            PaymentWrapper.WrapperResponse paymentResponse = null;
            bool result = Execute(service.PaymentSystemClientID, service.ID, response.SubscriptionID, mobileNumber, response.NetworkID, service.BillingAmount, true, reference, out paymentResponse);

            if (!result)
            {
                response.Exception = string.Format("{0}: {1}", paymentResponse.statusDescription, paymentResponse.Exception);
                response.Status    = ServiceMessages.FailedBillings;
                return(response);
            }

            response.Status = ServiceMessages.SubscriptionActivated;

            return(response);
        }
Exemplo n.º 12
0
        internal void unsubscribe(string subject, string ackInbox)
        {
            IConnection lnc;

            lock (mu)
            {
                lnc = this.nc;
                subMap.Remove(ackInbox);
            }

            UnsubscribeRequest usr = new UnsubscribeRequest();

            usr.ClientID = clientID;
            usr.Subject  = subject;
            usr.Inbox    = ackInbox;
            byte[] b = ProtocolSerializer.marshal(usr);

            var r = lnc.Request(unsubRequests, b, 2000);

            SubscriptionResponse sr = new SubscriptionResponse();

            ProtocolSerializer.unmarshal(r.Data, sr);
            if (!string.IsNullOrEmpty(sr.Error))
            {
                throw new StanException(sr.Error);
            }
        }
Exemplo n.º 13
0
        public void ConfirmSubscription(string key)
        {
            var provider = new SubscriptionProvider(_subscriptionRepositoryFactory());
            SubscriptionResponse response = provider.Confirm(key);
            var mail = EmailComposer.GetSubscriptionConfirmedMail(response);

            EmailSender.SendEmail(mail);
        }
Exemplo n.º 14
0
        public void Subscribe(SubscriptionInfo subscription)
        {
            var provider = new SubscriptionProvider(_subscriptionRepositoryFactory());
            SubscriptionResponse response = provider.Add(subscription);
            var emailMessage = EmailComposer.GetConfirmSubscriptionMail(response);

            EmailSender.SendEmail(emailMessage);
        }
Exemplo n.º 15
0
        public void OnPost()
        {
            SubscriptionId = id;
            var res = SubscriptionResponse.SubscriptionGet(SubscriptionId);

            GetStatus = res.StatusCode.ToString();
            GetResult = res.Content;
        }
Exemplo n.º 16
0
        public async Task <PartialCollectionResponse <SubscriptionResponse> > Get(CollectionPageRequest request)
        {
            var subscriptions = await(from subscriber in _readContext.Subscriptions
                                      join project in _readContext.Projects on subscriber.ProjectId equals project.Id
                                      select SubscriptionResponse.Create(subscriber, project))
                                .GetPageAsync(request.Offset, request.Count);

            return(subscriptions.ToPartialCollectionResponse());
        }
Exemplo n.º 17
0
        public void OnGet()
        {
            //SubscriptionId = "I-N564KWVKM523";
            SubscriptionId = "I-FXM4J9UWR6XL";
            var res = SubscriptionResponse.SubscriptionGet(SubscriptionId);

            Status = res.StatusCode.ToString();
            Result = res.Content;
        }
        private bool HandleObjectMessage(string msg)
        {
            var gmessage = GenesysMessage.Parse(msg);

            return
                (PongResponse.TryHandle(gmessage, Streams.PongSubject) ||
                 HeartbeatResponse.TryHandle(gmessage, Streams.HeartbeatsSubject) ||
                 SocketClosingResponse.TryHandle(gmessage, Streams.SocketClosingSubject) ||
                 SubscriptionResponse.TryHandle(gmessage, Streams.SubscriptionsSubject, _subscriptions));
        }
Exemplo n.º 19
0
        private static async Task <bool> TrySharePaymentWithReferrer(BitcornContext dbContext,
                                                                     SubscriptionResponse output,
                                                                     SubRequest subRequest,
                                                                     Subscription subInfo,
                                                                     SubscriptionTier requestedTierInfo,
                                                                     User user,
                                                                     int subscriptionPaymentRecipientId,
                                                                     decimal cost,
                                                                     SubscriptionState previousSubState,
                                                                     SubTx subTx)
        {
            //if (previousSubState != SubscriptionState.None) return false;
            //if subscription referrar share is defined and its between 0 and 1
            //get subscriber userreferral info
            var userReferral = await dbContext.UserReferral.FirstOrDefaultAsync(r => r.UserId == user.UserId);

            if (userReferral != null && userReferral.ReferralId != 0)
            {
                //get info of the person who referred the subscriber
                var referrer = await dbContext.Referrer.FirstOrDefaultAsync(u => u.ReferralId == userReferral.ReferralId);

                //check if referrer can get rewards
                if (ReferralUtils.IsValidReferrer(referrer))
                {
                    var referrerUser = await dbContext.JoinUserModels().FirstOrDefaultAsync(u => u.UserId == referrer.UserId);

                    if (referrerUser != null && !referrerUser.IsBanned)
                    {
                        bool success = false;
                        if (subInfo.ReferrerPercentage != null && subInfo.ReferrerPercentage > 0 && subInfo.ReferrerPercentage <= 1)
                        {
                            //get the user who received the subscription payment
                            var subscriptionPaymentRecipient = await dbContext.JoinUserModels().FirstOrDefaultAsync(u => u.UserId == subscriptionPaymentRecipientId);

                            success = await ShareSubscriptionPaymentWithReferrer(dbContext,
                                                                                 subInfo,
                                                                                 cost,
                                                                                 subTx,
                                                                                 referrer,
                                                                                 referrerUser,
                                                                                 subscriptionPaymentRecipient);
                        }

                        if (previousSubState == SubscriptionState.None && subInfo.Name == "BITCORNFarms")
                        {
                            await ReferralUtils.BonusPayout(dbContext, userReferral, referrer, user, referrerUser, referrerUser.UserStat);
                        }

                        return(success);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 20
0
        private static void ProcessEvent(WebSocketMessage msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    ClientLoginResponse = loginResp;
                }

                DoLog(string.Format("Client successfully logged with token {0}", loginResp.JsonWebToken));
                //3- Once Logged we request the security master record. We set the request timestamp for timeout calculation
                SecurityMasterRecordRequestStartTime = DateTime.Now;
                SubscriptionTAFinished = false;
                RequestSecurityMasterList();

                //3.1- We launch the thread that will process all the securities once everything is available
                Thread processSecurityMasterRecordThread = new Thread(ProcessSecurityMasterRecordThread);
                processSecurityMasterRecordThread.Start();
            }
            else if (msg is SubscriptionResponse)
            {
                SubscriptionResponse subscrResp = (SubscriptionResponse)msg;
                if (subscrResp.Service == "TA")
                {
                    SubscriptionTAFinished = true;
                }
            }
            else if (msg is SecurityMasterRecord)
            {
                SecurityMasterRecord security = (SecurityMasterRecord)msg;
                //4-Every time we get a security, if the arrival time is less than timeout time, we update the list that hold
                //all the securities
                TimeSpan elapsed = DateTime.Now - SecurityMasterRecordRequestStartTime;
                if (elapsed.TotalSeconds < _SECURITY_MASTER_RECORD_TIMOUT_IN_SECONDS && !SubscriptionTAFinished)
                {
                    SecurityMasterRecords.Add(security);
                }
                else
                {
                    //4.1- Here the security arrive after the timeout. We have to set some warning in the logs to check
                    //     if we have to recalibrate the timeout threshold
                    if (SubscriptionTAFinished)
                    {
                        DoLog(string.Format("TC1-Security Master Record arrived afte subscription response succesfull received!:{0}", security.Symbol));
                    }
                    else if (elapsed.TotalSeconds > _SECURITY_MASTER_RECORD_TIMOUT_IN_SECONDS)
                    {
                        DoLog(string.Format("TC2-Security Master Record arrived after timeout expiration!:{0}", security.Symbol));
                    }
                }
            }
        }
Exemplo n.º 21
0
        private async Task SendSubscriptionEntry()
        {
            var response = new SubscriptionResponse()
            {
                Mode         = SubscriptionMode.Paid,
                TrialEndDate = null,
                ManageSubscriptionsRefreshHash = SubscriptionsRefreshHashString,
            };

            await _connection.SendJsonAsync(response);
        }
Exemplo n.º 22
0
        private IRestResponse CreateSubscription(string planid)
        {
            var subscription = new Subscription()
            {
                PlanId         = planid,
                StartTime      = "2020-03-01T06:00:00Z",
                ShippingAmount = new Currency
                {
                    Value        = "10.00",
                    CurrencyCode = "USD"
                },
                Subscriber = new Subscriber()
                {
                    Name = new Name
                    {
                        GivenName = "John",
                        Surname   = "Doe"
                    },
                    EmailAddress    = "*****@*****.**",
                    ShippingAddress = new ShippingAddress
                    {
                        Name = new FullName
                        {
                            Fullname = "John Doe"
                        },
                        Address = new Address
                        {
                            AddressLine1 = "2211 N First Street",
                            AddressLine2 = "Building 17",
                            AdminArea2   = "San Jose",
                            AdminArea1   = "CA",
                            PostalCode   = "95131",
                            CountryCode  = "US"
                        }
                    }
                },
                ApplicationContext = new ApplicationContext()
                {
                    BrandName          = "Walmart",
                    Locale             = "en-US",
                    ShippingPreference = ApplicationContextShippingPreferenceEnum.SET_PROVIDED_ADDRESS,
                    UserAction         = ApplicationContextUserActionEnum.SUBSCRIBE_NOW,
                    PaymentMethod      = new PaymentMethod()
                    {
                        PayerSelected  = "PAYPAL",
                        PayeePreferred = "IMMEDIATE_PAYMENT_REQUIRED"
                    },
                    ReturnUrl = "https://example.com/returnUrl",
                    CancelUrl = "https://example.com/cancelUrl"
                }
            };

            return(SubscriptionResponse.SubscriptionCreate(subscription, "representation", "SUBSCRIPTION-my-testing03"));
        }
Exemplo n.º 23
0
        public void OnPostUpdatePlan()
        {
            SubscriptionId = id;
            var res = PatchSubscription(SubscriptionId);

            UpdateStatus = res.StatusCode.ToString();
            if (res.StatusCode.ToString() == "NoContent")
            {
                var res1 = SubscriptionResponse.SubscriptionGet(SubscriptionId);
                UpdateResult = res1.Content;
            }
        }
Exemplo n.º 24
0
        public void OnPost()
        {
            var res = SubscriptionResponse.SubscriptionActivate(SubscriptionId);

            ActivateStatus = res.StatusCode.ToString();
            Error          = res.ErrorMessage + ", " + res.ErrorException;
            if (ActivateStatus == "NoContent")
            {
                var res1 = SubscriptionResponse.SubscriptionGet(SubscriptionId);
                ActivateResult = res1.Content;
            }
        }
Exemplo n.º 25
0
        public async Task <bool> CreateSubscriptionAsync(string customerId, string customerName, string iban, PaymentMethod paymentMethod, string description, DateTime startDate, decimal amount, string interval, int?times, string webhookUrl)
        {
            var result = false;

            var mandateClient = GetMandateClient();

            // Create "mandate" via Mollie to be able to create a customer subscription.
            // Mandates allow you to charge a customer’s credit card or bank account recurrently.
            var mandateRequest = new MandateRequest
            {
                ConsumerName    = customerName,
                ConsumerAccount = iban,
                Method          = paymentMethod
            };

            MandateResponse mandateResponse = await mandateClient.CreateMandateAsync(customerId, mandateRequest);

            if (mandateResponse.Status == MandateStatus.Valid)
            {
                // Create your customer payment record here

                var mollieSettings = _configuration.GetSection("Mollie");
                var currency       = mollieSettings.GetValue <string>("DefaultCurrency");

                var subscriptionRequest = new SubscriptionRequest
                {
                    Amount = new Amount
                    {
                        Currency = currency,
                        Value    = amount.ToString()
                    },
                    Description = description,
                    StartDate   = startDate,
                    Method      = paymentMethod,
                    Interval    = interval,  // Interval to wait between charges like 1 month(s) or 14 days
                    Times       = times,     // Total number of charges for the subscription to complete. Leave empty for an on-going subscription
                    WebhookUrl  = webhookUrl // The url that Mollie calls with the payment id when the payment status changes.
                };

                var subscriptionClient = GetSubscriptionClient();

                SubscriptionResponse subscriptionResponse = await subscriptionClient.CreateSubscriptionAsync(customerId, subscriptionRequest);

                if (subscriptionResponse.Status == SubscriptionStatus.Active)
                {
                    // Update your customer payment record here with new subscription Id

                    result = true;
                }
            }

            return(result);
        }
Exemplo n.º 26
0
        /////////////////////////////////////////////////////////////////
        ///// Subscription operations
        ////////////////////////////////////////////////////////////////

        /// <summary>
        /// Creates the Subscription.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public SubscriptionResponse CreateSubscription(SubscriptionRequest request)
        {
            AbstractRestRequestStrategy <SubscriptionRequest, Subscription, SdkError> requestStrategy =
                new CreateSubscriptionStrategy(request);

            requestStrategy.SendRequest();

            SubscriptionResponse response = new SubscriptionResponse();

            response.Subscription = requestStrategy.RestResponse.Data;
            response.Error        = requestStrategy.RestResponse.Error;

            return((SubscriptionResponse)PrepareComposeResponse(response));
        }
Exemplo n.º 27
0
        private IRestResponse PatchSubscription(string subId)
        {
            var patches = new List <PatchObject>()
            {
                new PatchObject()
                {
                    Op    = "replace",
                    Path  = "/status_change_note",
                    Value = "Item out of stock"
                }
            };

            return(SubscriptionResponse.SubscriptionPatch(subId, patches));
        }
Exemplo n.º 28
0
        protected void ProcessSubscriptionResponse(IWebSocketConnection socket, string service, string serviceKey, string UUID, bool success = true, string msg = "")
        {
            SubscriptionResponse resp = new SubscriptionResponse()
            {
                Message    = msg,
                Success    = success,
                Service    = service,
                ServiceKey = serviceKey,
                UUID       = UUID,
                Msg        = "SubscriptionResponse"
            };

            DoLog(string.Format("SubscriptionResponse UUID:{0} Service:{1} ServiceKey:{2} Success:{3}", resp.UUID, resp.Service, resp.ServiceKey, resp.Success), MessageType.Information);
            DoSend <SubscriptionResponse>(socket, resp);
        }
Exemplo n.º 29
0
        public static MailMessage GetSubscriptionConfirmedMail(SubscriptionResponse subscription)
        {
            MailMessage mail = new MailMessage();

            mail.From = new MailAddress(mailFrom);
            mail.To.Add(new MailAddress(subscription.Email));
            mail.IsBodyHtml = true;
            mail.Subject    = SubscriptionConfirmedSubject;
            mail.IsBodyHtml = true;
            mail.Body       = string.Format(
                "Подписка подтверждена. Теперь вы будете получать уведомления когда дождь будет собираться идти в: {0}.<br>" +
                "Если вы хотите отписаться от уведомлений, нажмите на <a href=\"{1}{2}?key={3}\">эту ссылку</a>. <br>",
                subscription.AddressText, domainName, unsobscribeApi, subscription.Key);
            return(mail);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Deletes the Subscription.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public SubscriptionResponse DeleteSubscription(SubscriptionRequest request)
        {
            base.Validate <Subscription, SubscriptionRequest>(request, ValidatorContext.DELETE);

            AbstractRestRequestWithAlternativeDataStrategy <SubscriptionRequest, Subscription, SdkError, CommonResponse> requestStrategy =
                new DeleteSubscriptionStrategy(request);

            requestStrategy.SendRequest();

            SubscriptionResponse response = new SubscriptionResponse();

            response.Subscription = requestStrategy.RestResponse.Data;
            response.Error        = requestStrategy.RestResponse.Error;

            return((SubscriptionResponse)PrepareComposeResponse(response));
        }