コード例 #1
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            PaymentGateway paymentGateway = (PaymentGateway)value;

            if (paymentGateway == PaymentGateway.Stripe)
            {
                writer.WriteValue("$stripe");
            }

            if (paymentGateway == PaymentGateway.Braintree)
            {
                writer.WriteValue("$braintree");
            }

            if (paymentGateway == PaymentGateway.Paypal)
            {
                writer.WriteValue("$paypal");
            }

            if (paymentGateway == PaymentGateway.AmazonPayments)
            {
                writer.WriteValue("$amazon_payments");
            }

            if (paymentGateway == PaymentGateway.Authorizenet)
            {
                writer.WriteValue("$authorizenet");
            }
        }
コード例 #2
0
        protected void Page_Init(object sender, EventArgs e)
        {
            // REDIRECT IF NO PROVIDER AVAILABLE
            _PaymentGatewayId = AlwaysConvert.ToInt(Request.QueryString["PaymentGatewayId"]);
            _PaymentGateway   = PaymentGatewayDataSource.Load(_PaymentGatewayId);
            if (_PaymentGateway == null)
            {
                Response.Redirect("Gateways.aspx");
            }
            _ProviderInstance = _PaymentGateway.GetInstance();
            if (_ProviderInstance == null)
            {
                Response.Redirect("Gateways.aspx");
            }

            // INITIALIZE THE FORM
            Caption.Text = string.Format(Caption.Text, _ProviderInstance.Name);

            // DETERMINE IF PAYMENT METHODS SHOULD SHOW FOR THIS PROVIDER
            if (ShowPaymentMethods(_PaymentGateway))
            {
                LoadPaymentMethods();
            }
            else
            {
                trPaymentMethods.Visible = false;
            }
        }
コード例 #3
0
        public void ProcessValidPayment()
        {
            var paymentRequest = new PaymentRequest
            {
                CardNumber     = "1234123412341234",
                CardHolderName = "JOHN DOE",
                ExpiryDate     = "10/20",
                Amount         = 123.12,
                Currency       = "GBP",
                CVV            = "123"
            };

            var paymentGateway = new PaymentGateway(new MockedBankInstitution(), new MemoryStorage());
            var response       = paymentGateway.ProcessPayment(paymentRequest);

            Assert.IsType <Guid>(response.Id);
            Assert.Equal(Status.Authorized, response.Status);


            var savedResponse = paymentGateway.RetrievePaymentInfo(response.Id);

            Assert.Equal(response.GetHashCode(), savedResponse.Response.GetHashCode());
            Assert.Equal(paymentRequest.Amount, savedResponse.Request.Amount);
            Assert.Equal(paymentRequest.MaskCardNumber(), savedResponse.Request.CardNumber);
        }
コード例 #4
0
        protected void RemoveCardButton_Click(object sender, EventArgs e)
        {
            int profileId = AlwaysConvert.ToInt(PreferedCreditCard.SelectedValue);

            if (profileId > 0)
            {
                var profile = GatewayPaymentProfileDataSource.Load(profileId);
                if (profile.Subscriptions.Count == 0)
                {
                    int            gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(profile.GatewayIdentifier);
                    PaymentGateway gateway   = PaymentGatewayDataSource.Load(gatewayId);
                    if (gateway != null)
                    {
                        var provider = gateway.GetInstance();
                        try
                        {
                            var rsp = provider.DoDeletePaymentProfile(new CommerceBuilder.Payments.Providers.DeletePaymentProfileRequest(AbleContext.Current.User, profile.CustomerProfileId, profile.PaymentProfileId));
                            if (rsp.Successful || rsp.ResponseCode == "E00040")
                            {
                                profile.Delete();
                                BindPayments();
                            }
                        }
                        catch (Exception exp)
                        {
                            Logger.Error(exp.Message);
                        }
                    }
                }
            }
        }
コード例 #5
0
        public void WhenCalledPaymentGateway_ReturnsPaymentIsSuccessful()
        {
            var mockHandler = new Mock <HttpMessageHandler>();
            var requestUri  = "http://www.google.com/search?q=7.0";
            var response    = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK
            };

            mockHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(),
                                                 ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(response);

            var httpClient     = new HttpClient(mockHandler.Object);
            var paymentGateway = new PaymentGateway(httpClient);
            var retrievedPosts = paymentGateway.GetAsync(requestUri);

            Assert.NotNull(retrievedPosts);

            mockHandler.Protected().Verify(
                "SendAsync",
                Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(req => req.Method == HttpMethod.Get),
                ItExpr.IsAny <CancellationToken>());
        }
コード例 #6
0
        /// <summary>
        ///    This method will store the credit card and return a token that can be used outside the billing system
        /// </summary>
        /// <param name="billingAccountId"></param>
        /// <param name="creditCard"></param>
        /// <param name="expirationDate"></param>
        /// <returns></returns>
        public string StoreCreditCard(int billingAccountId, string creditCard, int expirationMonth, int expirationYear)
        {
            CreditCardPaymentValidator.Validate(billingAccountId.ToString(), creditCard, expirationMonth, expirationYear);

            //Method name must be business specific.

            //Create a tokenNumber for the end user.
            var tokenNumber = TokenProvider.GenerateToken();

            //Store Billing account and token.


            //I could put the rest on the queue for processing because I can't do anything else
            //Then the other process will update DC and get the PEC and handle failures.
            //That would give me autmatice retry.  Would need to encrypt CC# for that.

            //Get the PEC from the billing providere
            var pec = PaymentGateway.StoreCreditCardAtTokenProviders(creditCard, expirationMonth, expirationYear);

            //Need to expect a specific exception and catch and handle it.


            //What do I do if the payment gateway is down.



            //Store both the tokenNumber the PEC in the billing system
            //BillingGateway.CreateCreditCardBillingPaymentMethod(billingAccountId, pec, tokenNumber);

            //Now that I have a pec save it to the db with a new tokenNumber
            DataFacade.CreateToken(new Token(pec, tokenNumber));
            return(tokenNumber);
        }
コード例 #7
0
        public void ProcessInvalidPayment3()
        {
            var paymentGateway = new PaymentGateway(new MockedBankInstitution(), new MemoryStorage());
            var response       = paymentGateway.ProcessPayment(null);

            Assert.Null(response);
        }
コード例 #8
0
        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (this.Payment != null && (this.Payment.PaymentStatus == PaymentStatus.Unprocessed || this.Payment.PaymentStatus == PaymentStatus.AuthorizationPending))
            {
                PaymentMethod method = this.Payment.PaymentMethod;
                if (method != null && method.PaymentInstrumentType == PaymentInstrumentType.PayPal)
                {
                    PaymentGateway gateway = CommerceBuilder.Payments.Providers.PayPal.PayPalProvider.GetPayPalPaymentGateway(true);
                    if (gateway != null)
                    {
                        PayPalProvider provider     = (PayPalProvider)gateway.GetInstance();
                        Control        payNowButton = provider.GetPayNowButton(this.Payment.Order, this.Payment.Id);
                        if (payNowButton != null)
                        {
                            phPayNow.Controls.Add(payNowButton);

                            // IF AUTO CLICK IS ENABLED AND PAGE VIEW IS WITHIN 10 SECONDS PERIOD AFTER ORDER PLACEMENT
                            if (AutoClick)
                            {
                                if (this.Payment.Order.OrderDate.AddSeconds(10) >= LocaleHelper.LocalNow)
                                {
                                    ((PayNowButton)payNowButton).AutoClick();
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #9
0
 public AtmViewModel(Atm atm)
 {
     _atm             = atm;
     _repository      = new AtmRepository();
     _paymentGateway  = new PaymentGateway();
     TakeMoneyCommand = new Command <decimal>(x => x > 0, TakeMoney);
 }
コード例 #10
0
        protected void SaveCardButton_Click(object sender, EventArgs e)
        {
            int   profileId             = AlwaysConvert.ToInt(HiddenProfileId.Value);
            Label ProfileSuccessMessage = (Label)PageHelper.RecursiveFindControl(Page, "ProfileSuccessMessage");
            Label ProfileErrorMessage   = (Label)PageHelper.RecursiveFindControl(Page, "ProfileErrorMessage");

            if (profileId > 0)
            {
                var profile = GatewayPaymentProfileDataSource.Load(profileId);
                if (profile != null)
                {
                    int            gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(profile.GatewayIdentifier);
                    PaymentGateway gateway   = PaymentGatewayDataSource.Load(gatewayId);

                    if (gateway != null)
                    {
                        var provider = gateway.GetInstance();
                        try
                        {
                            AccountDataDictionary cardDetails = new AccountDataDictionary();
                            cardDetails["AccountNumber"]   = "XXX" + profile.ReferenceNumber.Replace("x", "X");
                            cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedItem.Value;
                            cardDetails["ExpirationYear"]  = ExpirationYear.SelectedItem.Value;
                            cardDetails["SecurityCode"]    = SecurityCode.Text.Trim();
                            PaymentMethod         method = PaymentMethodDataSource.Load(profile.InstrumentTypeId);
                            PaymentInstrumentData instr  = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
                            var rsp = provider.DoUpdatePaymentProfile(new CommerceBuilder.Payments.Providers.UpdatePaymentProfileRequest(AbleContext.Current.User, instr, profile.CustomerProfileId, profile.PaymentProfileId));
                            if (rsp.Successful || rsp.ResponseCode == "E00040")
                            {
                                int id = profile.Id;
                                profile.Expiry = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedItem.Value), AlwaysConvert.ToInt(ExpirationMonth.SelectedItem.Value), 1));
                                profile.Save();
                                if (ProfileSuccessMessage != null)
                                {
                                    ProfileSuccessMessage.Text    = string.Format("Profile '{0} ending in {1}' updated successfully!", profile.InstrumentType, profile.ReferenceNumber);
                                    ProfileSuccessMessage.Visible = true;
                                    ProfileErrorMessage.Visible   = false;
                                }
                            }
                            else
                            {
                                if (ProfileErrorMessage != null)
                                {
                                    ProfileErrorMessage.Text      = string.Format("Somthing went wrong! Unable to update profile '{0} ending in {1}'", profile.InstrumentType, profile.ReferenceNumber);
                                    ProfileSuccessMessage.Visible = false;
                                    ProfileErrorMessage.Visible   = true;
                                }

                                Logger.Error(rsp.ResponseMessage);
                            }
                        }
                        catch (Exception exp)
                        {
                            Logger.Error(exp.Message);
                        }
                    }
                }
            }
            EditCardInfoPopUp.Hide();
        }
コード例 #11
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            //Capture the payment
            if (CustomerOrder.Transactions == null)
            {
                CustomerOrder.Transactions = new LazyList <Transaction>();
            }

            //pull this order and make sure it's not already transacted/charged
            Order orderCheck = OrderServiceInterface.GetOrder(CustomerOrder.ID);

            decimal amountPaid = 0;

            if (orderCheck.Transactions.Count > 0)
            {
                amountPaid = orderCheck.Transactions.Sum(x => x.Amount);
            }

            if (amountPaid > 0)
            {
                throw new InvalidOperationException("A transaction already exists for this order: " + CustomerOrder.OrderNumber);
            }

            CustomerOrder.Transactions.Add(PaymentGateway.Capture(CustomerOrder));

            return(ActivityExecutionStatus.Closed);
        }
コード例 #12
0
 private async Task <PaymentBill> GetBillAsync(Int32 orderAmount)
 {
     return(await PaymentGateway.GetBillAsync(BillURL, new Amount()
     {
         Value = orderAmount
     }));
 }
コード例 #13
0
ファイル: Order.cs プロジェクト: ProwarenessDevNext/SOLID
        public void ChargeCard(PaymentDetails paymentDetails, Cart cart)
        {
            using (var paymentGateway = new PaymentGateway())
            {
                try
                {
                    paymentGateway.Credentials    = "account credentials";
                    paymentGateway.CardNumber     = paymentDetails.CreditCardNumber;
                    paymentGateway.ExpiresMonth   = paymentDetails.ExpiresMonth;
                    paymentGateway.ExpiresYear    = paymentDetails.ExpiresYear;
                    paymentGateway.NameOnCard     = paymentDetails.CardholderName;
                    paymentGateway.AmountToCharge = cart.TotalAmount;

                    paymentGateway.Charge();
                }
                catch (AvsMismatchException ex)
                {
                    throw new OrderException("The card gateway rejected the card based on the address provided.", ex);
                }
                catch (Exception ex)
                {
                    throw new OrderException("There was a problem with your card.", ex);
                }
            }
        }
コード例 #14
0
        protected void SaveButton_Click(object sender, System.EventArgs e)
        {
            PaymentGateway gateway = new PaymentGateway();

            gateway.ClassId = ProviderClassId;
            gateway.Name    = ProviderInstance.Name;
            gateway.UpdateConfigData(this.GetConfigData());
            gateway.Save();
            ClearSessionKey();
            if (ShowPaymentMethods(ProviderInstance))
            {
                //UPDATE PAYMENT METHODS
                int index = 0;
                foreach (DataListItem item in PaymentMethodList.Items)
                {
                    int           paymentMethodId = AlwaysConvert.ToInt(PaymentMethodList.DataKeys[index]);
                    PaymentMethod method          = GetPaymentMethod(paymentMethodId);
                    if (method != null)
                    {
                        CheckBox cbMethod = (CheckBox)AbleCommerce.Code.PageHelper.RecursiveFindControl(item, "Method");
                        if (cbMethod.Checked)
                        {
                            method.PaymentGateway = gateway;
                        }
                        method.Save();
                    }
                    index++;
                }
            }
            Response.Redirect("Gateways.aspx");
        }
コード例 #15
0
        public IActionResponse <int> Update(PaymentGateway model)
        {
            var response = new ActionResponse <int>();

            var findedPaymentGateway = GetPaymentGateway(model.PaymentGatewayId);

            if (!findedPaymentGateway.IsSuccessful)
            {
                response.Message = findedPaymentGateway.Message;
            }
            else
            {
                findedPaymentGateway.Result.UpdateWith(new
                {
                    model.BankName,
                    model.IsActive,
                    model.MerchantId,
                    model.Name,
                    model.Password,
                    model.Username
                });

                _uow.Entry(findedPaymentGateway.Result).State = EntityState.Modified;

                response.Result       = _uow.SaveChanges();
                response.IsSuccessful = response.Result.ToSaveChangeResult();
                response.Message      = response.Result.ToSaveChangeMessageResult(BusinessMessage.Success, BusinessMessage.Error);
            }
            return(response);
        }
コード例 #16
0
        public void IncorrectCallToPaymentGatewayGivesNegateResultWithReason()
        {
            Result result = new PaymentGateway().Pay(DateTime.Now, "xpaulus");

            Assert.Equal(false, result.IsSuccess);
            Assert.Equal(ErrorType.NoXinNameAllowed.Value, result.ErrorType.Value);
        }
コード例 #17
0
        public void ProcessCreditCard(PaymentDetails paymentDetails, decimal amount)
        {
            using (var paymentGateway = new PaymentGateway())
            {
                try
                {
                    paymentGateway.Credentials = "account credentials";
                    paymentGateway.CardNumber = paymentDetails.CreditCardNumber;
                    paymentGateway.ExpiresMonth = paymentDetails.ExpiresMonth;
                    paymentGateway.ExpiresYear = paymentDetails.ExpiresYear;
                    paymentGateway.NameOnCard = paymentDetails.CardholderName;
                    paymentGateway.AmountToCharge = amount;

                    paymentGateway.Charge();
                }
                catch (AvsMismatchException ex)
                {
                    throw new OrderException("The card gateway rejected the card based on the address provided.", ex);
                }
                catch (Exception ex)
                {
                    throw new OrderException("There was a problem with your card.", ex);
                }
            }
        }
コード例 #18
0
 public static Checkout Create(
     string name,
     decimal amount,
     PaymentGateway paymentGateway,
     PaymentMethod paymentMethod,
     bool useEscrow,
     string customerName,
     string customerPhoneNumber,
     string customerEmail,
     DateTimeOffset virtualBankExpirationTime,
     bool isDigital,
     string returnUrl
     )
 {
     return(new Checkout
     {
         Id = Guid.NewGuid(),
         CreatedTime = DateTimeOffset.UtcNow,
         Name = name,
         Amount = amount,
         PaymentGateway = paymentGateway,
         PaymentMethod = paymentMethod,
         UseEscrow = useEscrow,
         CustomerName = customerName,
         CustomerPhoneNumber = customerPhoneNumber,
         CustomerEmail = customerEmail,
         VirtualBankExpirationTime = virtualBankExpirationTime,
         IsDigital = isDigital,
         ReturnUrl = returnUrl,
     });
 }
コード例 #19
0
 public AtmViewModel(logic.Atms.Atm atm)
 {
     _atm            = atm;
     _repository     = new AtmRepository();
     _paymentGateway = new PaymentGateway();
     //this will be executed only if amount is > 0
     TakeMoneyCommand = new Command <decimal>(x => x > 0, TakeMoney);
 }
コード例 #20
0
        private static string ProcessPayment(Order order)
        {
            PaymentGateway gateway      = new PaymentGateway();
            string         customerName = string.Format("{0} {1}", order.Customer.FirstName, order.Customer.LastName);
            string         response     = gateway.Authorise(order.getTotalValue(), customerName, order.PaymentCard.CardNumber, order.PaymentCard.CVV, order.PaymentCard.ExpiryDate);

            return(response);
        }
コード例 #21
0
 public PaymentsController(PaymentGateway paymentGateway,
                           PaymentRepository paymentRepository,
                           ClaimsPrincipal claimsPrincipal)
 {
     _paymentGateway    = paymentGateway;
     _paymentRepository = paymentRepository;
     _claimsPrincipal   = claimsPrincipal;
 }
コード例 #22
0
        public ActionResult Config(ConfigModel model, FormCollection form)
        {
            var            paymentMethods = _methodRepo.LoadPaymentMethods(_hiddenMethods);
            PaymentGateway gateway        = model.GatewayId.HasValue ? _gatewayRepo.Load(model.GatewayId.Value) : null;

            model.ShowConfirmationMessage = true;
            if (gateway == null)
            {
                string classId  = Misc.GetClassId(typeof(EPProvider));
                var    provider = Activator.CreateInstance(Type.GetType(classId)) as IPaymentProvider;
                gateway         = new PaymentGateway();
                gateway.ClassId = classId;
                gateway.Name    = provider.Name;
                gateway.Store   = AbleContext.Current.Store;
                model.ShowConfirmationMessage = false;
            }

            Dictionary <string, string> configData = new Dictionary <string, string>();

            configData.Add("UseDebugMode", model.UseDebugMode.ToString());
            configData.Add("ExecutionMode", model.ExecutionMode.ToString());
            configData.Add("UseAuthCapture", model.UseAuthCapture.ToString());
            gateway.UpdateConfigData(configData);
            _gatewayRepo.Save(gateway);

            //UPDATE PAYMENT METHODS

            var selectedKeys = form.AllKeys.Where(key => key.ToUpper().StartsWith("METHOD_CHK_",
                                                                                  StringComparison.InvariantCultureIgnoreCase)).ToList();

            foreach (var key in selectedKeys)
            {
                int           paymentMethodId = AlwaysConvert.ToInt(key.Substring(11));
                PaymentMethod method          = paymentMethods.Where(m => m.Id == paymentMethodId).FirstOrDefault();
                if (method != null)
                {
                    if (form[key].Contains("true"))
                    {
                        method.PaymentGateway = gateway;
                    }
                    else if (method.PaymentGateway != null && method.PaymentGateway.Id == gateway.Id)
                    {
                        method.PaymentGateway = null;
                    }

                    _methodRepo.Save(method);
                }
            }

            if (model.SaveOnly.Equals("true"))
            {
                return(Json(new { status = "Success", Id = gateway.Id, showMessage = model.ShowConfirmationMessage }));
            }
            else
            {
                return(Json(new { status = "Redirect", Url = Url.Action("Gateways", "Payments") }));
            }
        }
コード例 #23
0
 public WeiXinUserService(
     WeiXinUserRepository weiXinUserRepository,
     PaymentGateway paymentGateway,
     ValidateCodeService validateCodeService)
 {
     _weiXinUserRepository = weiXinUserRepository;
     _paymentGateway       = paymentGateway;
     _validateCodeService  = validateCodeService;
 }
コード例 #24
0
        public IActionResult ProcessPayment(ProcessPaymentPayload payload)
        {
            if (DateTime.Now > payload.ExpiryDate)
            {
                return(BadRequest("The customers credit card has expired."));
            }

            return(PaymentGateway.ProcessPayment(payload, new BankRequestMock()));
        }
コード例 #25
0
ファイル: PaymentActor.cs プロジェクト: orf53975/BeeHive-1
 public PaymentActor(
     ICollectionStore <Order> orderRepo,
     ICollectionStore <Payment> paymentRepo,
     PaymentGateway paymentGateway)
 {
     _orderRepo      = orderRepo;
     _paymentRepo    = paymentRepo;
     _paymentGateway = paymentGateway;
 }
コード例 #26
0
 public static PaymentGatewayDto MapToDto(PaymentGateway paymentGateway)
 {
     return(new PaymentGatewayDto()
     {
         PaymentGatewayId = paymentGateway.PaymentGatewayId,
         GatewayName = paymentGateway.GatewayName,
         IsActive = paymentGateway.IsActive
     });
 }
コード例 #27
0
        public IActionResponse <string> Verify(PaymentGateway gateway, Transaction model, object responseGateway = null)
        {
            long trackingId    = 0;
            var  paymentVerify = _zarinPal.PaymentVerification(
                MerchantID: gateway.MerchantId,
                Authority: model.Authority.Trim(),
                Amount: model.Price,
                RefID: out trackingId
                );

            //TODO:Uncomment Below
            //if (paymentVerify == 100)
            if (true)//TODO:Remove
            {
                model.IsSuccess  = true;
                model.TrackingId = trackingId.ToString();
                model.Status     = paymentVerify.ToString();
                if (model.OrderId != 0)
                {
                    _orderBusiness.UpdateStatus(model.OrderId);
                }
                _transactionBusiness.Update(model);

                _observerManager.Value.Notify(ConcreteKey.Success_Payment, new ObserverMessage
                {
                    SmsContent = string.Format(LocalMessage.Transaction_Add_Sms, (HttpContext.Current.User as ICurrentUserPrincipal).FullName, model.OrderId),
                    BotContent = string.Format(LocalMessage.Transaction_Add_Bot, (HttpContext.Current.User as ICurrentUserPrincipal).FullName,
                                               model.OrderId, gateway.BankName.GetLocalizeDescription(),
                                               model.Price.ToString("0,0"),
                                               trackingId.ToString()),
                    Key    = nameof(Transaction),
                    UserId = (HttpContext.Current.User as ICurrentUserPrincipal).UserId,
                });

                return(new ActionResponse <string>
                {
                    IsSuccessful = true,
                    Message = "عملیات پرداخت با موفقیت انجام شد",
                    Result = trackingId.ToString()
                });
            }
            else
            {
                model.IsSuccess  = false;
                model.TrackingId = trackingId.ToString();
                model.Status     = paymentVerify.ToString();
                _transactionBusiness.Update(model);

                return(new ActionResponse <string>
                {
                    IsSuccessful = false,
                    Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید",
                    Result = trackingId.ToString()
                });
            }
        }
コード例 #28
0
        public IActionResponse <string> Do(PaymentGateway gateway, TransactionModel model)
        {
            var currentUser = _userBusiness.Find(model.UserId);

            if (currentUser == null)
            {
                return(new ActionResponse <string>()
                {
                    Message = LocalMessage.UsernameIsWrong
                });
            }

            var transaction = _transactionBusiness.Do(new Transaction
            {
                OrderId          = model.OrderId,
                Price            = model.Price,
                PaymentGatewayId = model.PaymentGatewayId,
                Authority        = "100",
                Status           = "100",
                InsertDateMi     = DateTime.Now,
                InsertDateSh     = PersianDateTime.Now.ToString(PersianDateTimeFormat.Date)
            });

            if (!transaction.IsSuccessful)
            {
                return new ActionResponse <string>
                       {
                           IsSuccessful = false,
                           Message      = LocalMessage.Exception
                       }
            }
            ;
            using (HttpClient http = new HttpClient())
            {
                var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

                var response            = http.PostAsync($"https://pay.ir/payment/send?api={gateway.MerchantId.Trim()}&amount={model.Price * 10}&redirect={AppSettings.TransactionRedirectUrl_Pay}&factorNumber={transaction.Result.TransactionId}", content).Result;
                var deserializeResponse = JsonConvert.DeserializeObject <GatewayPayResponseModel>(response.Content.ReadAsStringAsync().Result);

                if (deserializeResponse.status == 1)
                {
                    return(new ActionResponse <string>
                    {
                        IsSuccessful = true,
                        Result = $"https://pay.ir/payment/gateway/{deserializeResponse.transId}"
                    });
                }
                else
                {
                    return(new ActionResponse <string>()
                    {
                        Message = LocalMessage.PaymentConnectionFailed
                    });
                }
            }
        }
コード例 #29
0
        private bool ShowPaymentMethods(PaymentGateway gateway)
        {
            string gcerClassId = Misc.GetClassId(typeof(CommerceBuilder.Payments.Providers.GiftCertificatePaymentProvider));

#pragma warning disable 618
            string gchkClassId = Misc.GetClassId(typeof(CommerceBuilder.Payments.Providers.GoogleCheckout.GoogleCheckout));
#pragma warning restore 618
            bool unassignable = gcerClassId.Equals(gateway.ClassId) || gchkClassId.Equals(gateway.ClassId);
            return(!unassignable);
        }
コード例 #30
0
        public Payment SearchWithAmountOrDueDate(string column, string searchWith)
        {
            PaymentGateway aPaymentGateway = new PaymentGateway();
            Payment        aPayment        = new Payment();

            aPayment = aPaymentGateway.SearchWithAmountOrDueDate(column, searchWith);


            return(aPayment);
        }
コード例 #31
0
 public Gateway(Configuration config)
 {
     this.config           = config;
     this.client           = new Client(config);
     this.recipient        = new RecipientGateway(this);
     this.recipientAccount = new RecipientAccountGateway(this);
     this.balances         = new BalancesGateway(this);
     this.batch            = new BatchGateway(this);
     this.payment          = new PaymentGateway(this);
 }
コード例 #32
0
        private static PaymentGateway GetPaymentGateway(Guid organizationId)
        {
            using (SqlConnection sqlConnection = new SqlConnection(SettingManager.Default.ConnectionString))
            {
                using (SqlCommand sqlCommand = new SqlCommand("dbo.PaymentGateway_Get", sqlConnection))
                {
                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    SqlParameter sqlParameter = sqlCommand.Parameters.Add("@organizationId", SqlDbType.UniqueIdentifier);
                    sqlParameter.Value = organizationId;

                    sqlConnection.Open();
                    using (SqlDataReader reader = sqlCommand.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            PaymentGateway paymentGateway = new PaymentGateway();
                            paymentGateway.MerchantAcctId = (string)reader["MerchantAcctId"];
                            paymentGateway.MerchantKey = (string)reader["MerchantKey"];
                            paymentGateway.OrganizationId = organizationId;
                            return paymentGateway;
                        }
                    }
                }
            }
            return null;
        }
コード例 #33
0
 public PaymentController()
 {
     _gateWay = new PaymentGateway();
 }
コード例 #34
0
    public HttpResponseMessage Put([FromBody]Fund funds, string action)
    {
        try
        {
            //paypal Withdraw
            if (action == "withdrawPP")
            {

                var user = Membership.GetUser(Security.CurrentUser.Identity.Name);
                var localFunds = Fund.GetCurrentFundsInformation((Guid)user.ProviderUserKey);
                if (localFunds.ActiveInUserAccount >= funds.AmountToWithdraw)
                {


                    var mem = SiteCache.GetPublicMemberFull(RDN.Library.Classes.Account.User.GetMemberId());
                    PaymentGateway pg = new PaymentGateway();

                    var f = pg.StartInvoiceWizard()
                        .Initalize(RollinNewsConfig.MERCHANT_ID, "USD", PaymentProvider.Paypal, (PaymentMode)Enum.Parse(typeof(PaymentMode), ConfigurationManager.AppSettings["IsPayPalLive"].ToString()), ChargeTypeEnum.RollinNewsWriterPrePayout)
                        .SetInvoiceId(Guid.NewGuid())
                        .AddWriterPayout(new RDN.Library.Classes.Payment.Classes.Invoice.InvoiceWriterPayout
                        {
                            BasePrice = (decimal)funds.AmountToWithdraw,
                            Name = "Rollin News Payout " + DateTime.UtcNow.ToString("yyyy/MM/dd"),
                            PaymentRequestedDateTime = DateTime.UtcNow,
                            PayoutId = Guid.NewGuid(),
                            UserPaidId = (Guid)user.ProviderUserKey,
                            WhoPaysFees = WhoPaysProcessorFeesEnum.Receiver
                        })
                        .SetInvoiceContactData(new RDN.Library.Classes.Payment.Classes.Invoice.InvoiceContactInfo
                        {
                            Email = user.Email,
                            FirstName = mem.Firstname,
                            LastName = mem.LastName,
                            Phone = mem.PhoneNumber,
                        })
                                            .FinalizeInvoice();
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.NotAcceptable);
                }
            }
            //bitcoinWithdraw
            else if (action == "withdrawBc")
            {

            }
            else if (action == "submitEarnings")
            {
                Security.DemandUserHasRight(Rights.AllowedToSetMonthlyEarnings, false);
                PostRepository repo = new PostRepository();
                var posts = repo.GetPostsAndAuthors();
                List<RDN.Library.Classes.RN.Posts.Classes.Post> PostsTemp = new List<RDN.Library.Classes.RN.Posts.Classes.Post>();
                foreach (var p in posts)
                {
                    try
                    {
                        RDN.Library.Classes.RN.Posts.Classes.Post postTemp = new RDN.Library.Classes.RN.Posts.Classes.Post();
                        postTemp.Id = p.Id;
                        postTemp.AuthorUserId = p.AuthorUserId;
                        PostsTemp.Add(postTemp);
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, GetType());
                    }
                }
                MonthlyStatementsFactory statement = new MonthlyStatementsFactory();
                var state = statement.Initialize(Convert.ToDouble(funds.TotalEarningsForMonth), DateTime.UtcNow)
                    .GetPostsThatHadViews()
                    .SetAuthorsForPosts(PostsTemp)
                    .CalculateAndSavePayouts()
                    .SendEmailsToAuthorsAboutPayouts()
                    .ZeroOutMonthlyViews();


            }
            else
            {
                repository.Update(funds);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (UnauthorizedAccessException)
        {
            return Request.CreateResponse(HttpStatusCode.Unauthorized);
        }
        catch (Exception exception)
        {
            ErrorDatabaseManager.AddException(exception, GetType());
            return Request.CreateResponse(HttpStatusCode.InternalServerError);
        }
    }
コード例 #35
0
 public void SelectPaymentGateway(PaymentGateway paymentGateway)
 {
     UIUtil.DefaultProvider.SelectWithText("ctl00_cphDialog_ddlEventsCustomerMerchantID", StringEnum.GetStringValue(paymentGateway), LocateBy.Id);
 }
コード例 #36
0
 public static Checkout Create(
     string name,
     decimal amount,
     PaymentGateway paymentGateway,
     PaymentMethod paymentMethod,
     bool useEscrow,
     string customerName,
     string customerPhoneNumber,
     string customerEmail,
     DateTimeOffset virtualBankExpirationTime,
     bool isDigital,
     string returnUrl
     )
 {
     return new Checkout
     {
         Id = Guid.NewGuid(),
         CreatedTime = DateTimeOffset.UtcNow,
         Name = name,
         Amount = amount,
         PaymentGateway = paymentGateway,
         PaymentMethod = paymentMethod,
         UseEscrow = useEscrow,
         CustomerName = customerName,
         CustomerPhoneNumber = customerPhoneNumber,
         CustomerEmail = customerEmail,
         VirtualBankExpirationTime = virtualBankExpirationTime,
         IsDigital = isDigital,
         ReturnUrl = returnUrl,
     };
 }
コード例 #37
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="invoice"></param>
        /// <param name="reportInformation"></param>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public static bool HandleDuesPayments(DisplayInvoice invoice, string reportInformation, string customerId = null)
        {
            try
            {
                var duesItem = invoice.DuesItems.FirstOrDefault();
                bool success = Dues.DuesFactory.PayDuesAmount(duesItem.DuesItemId, duesItem.DuesId, (double)duesItem.BasePrice, duesItem.MemberPaidId, "Paid Via Paypal, Invoice:" + invoice.InvoiceId.ToString().Replace("-", ""));
                PaymentGateway pg = new PaymentGateway();
                pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Payment_Successful, customerId);
                if (success)
                {
                    //email people.
                    WebClient client = new WebClient();
                    WebClient client1 = new WebClient();
                    client.DownloadStringAsync(new Uri(ServerConfig.URL_TO_CLEAR_MEMBER_CACHE + duesItem.MemberPaidId));
                    client1.DownloadStringAsync(new Uri(ServerConfig.URL_TO_CLEAR_MEMBER_CACHE_API + duesItem.MemberPaidId));

                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Dues Payment Made", reportInformation);
                    var member = MemberCache.GetMemberDisplay(duesItem.MemberPaidId);
                    var league = MemberCache.GetLeagueOfMember(duesItem.MemberPaidId);
                    var settings = Dues.DuesFactory.GetDuesSettings(duesItem.DuesId);
                    if (settings != null && member != null)
                    {
                        var emailData = new Dictionary<string, string>
                                        {
                                            { "memberName",  member.DerbyName },
                                            { "leagueName", settings.LeagueOwnerName   },
                                            { "invoiceId", invoice.InvoiceId.ToString().Replace("-","")},
                                            { "amountPaid", duesItem.PriceAfterFees.ToString("N2") },
                                            { "baseAmountPaid",duesItem.BasePrice.ToString("N2")  },
                                            { "monthOfDuesPayment",duesItem.PaidForDate.ToShortDateString()},
                                            { "emailForPaypal", settings.PayPalEmailAddress},
                                            { "statusOfPayment",RDN.Portable.Util.Enums.EnumExt.ToFreindlyName( InvoiceStatus.Pending_Payment_From_Paypal)}
                                          };

                        //sends email to user for their payment.
                        if (!String.IsNullOrEmpty(member.UserName))
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, member.UserName, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Receipt", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForUser);
                        else if (!String.IsNullOrEmpty(member.Email))
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, member.Email, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Receipt", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForUser);

                        if (league != null && !String.IsNullOrEmpty(league.Email))
                        {
                            //sends email to league for notification of their payment.
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, league.Email, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Made", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForLeague);
                        }

                        MobileNotificationFactory mnf = new MobileNotificationFactory();
                        mnf.Initialize("Dues Payment Made", "Receipt For Payment", NotificationTypeEnum.DuesPaymentReceipt)
                            .AddId(invoice.InvoiceId)
                            .AddMember(duesItem.MemberPaidId)
                            .SendNotifications();
                    }
                    else
                    {
                        throw new Exception("Settings or Member was null.  Can't send Receipts." + invoice.InvoiceId);
                    }
                }
                else
                {
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Dues Updates Were not successful", reportInformation);
                }
                return true;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: reportInformation);
            }
            return false;
        }
コード例 #38
0
        public void HandlePaywallPayments(DisplayInvoice invoice, string additionalReportingInformation = null, string customerId = null)
        {
            try
            {
                PaymentGateway pg = new PaymentGateway();
                //change invoice to ready to be shipped
                pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Payment_Successful, customerId);

                CompileAndSendReceiptsEmailsForPaywall(invoice);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: additionalReportingInformation);
            }
        }
コード例 #39
0
        private Classes.Display.DisplayInvoice PendingPaypalPayment(string invoiceId)
        {
            try
            {
                PaymentGateway pg = new PaymentGateway();
                var invoice = pg.GetDisplayInvoice(new Guid(invoiceId));
                if (invoice != null)
                {
                    if (invoice.Subscription != null)
                    {
                        InvoiceFactory.EmailLeagueAboutSuccessfulSubscription(invoice.Subscription.InternalObject, invoice.InvoiceId, invoice.Subscription.Price, invoice.Subscription.ValidUntil, invoice.InvoiceBilling.Email);

                        RDN.Library.Classes.League.LeagueFactory.UpdateLeagueSubscriptionPeriod(invoice.Subscription.ValidUntil, false, invoice.Subscription.InternalObject);

                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: New Payment Pending!!", invoice.InvoiceId + " Amount:" + invoice.Subscription.Price + CompileReportString());
                        pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Pending_Payment_From_Paypal);
                        WebClient client = new WebClient();
                        client.DownloadDataAsync(new Uri(ServerConfig.URL_TO_CLEAR_LEAGUE_MEMBER_CACHE + invoice.Subscription.InternalObject));
                        WebClient client1 = new WebClient();
                        client1.DownloadDataAsync(new Uri(ServerConfig.URL_TO_CLEAR_LEAGUE_MEMBER_CACHE_API + invoice.Subscription.InternalObject));
                    }
                    else if (invoice.Paywall != null)
                    {
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: New Paywall Payment Pending!!", invoice.InvoiceId + " Amount:" + invoice.Paywall.Price + CompileReportString());
                        pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Pending_Payment_From_Paypal);
                    }
                    else if (invoice.DuesItems.Count > 0)
                        HandleDuesPaymentPending(invoice);
                    else if (invoice.InvoiceItems.Count > 0)
                    {
                        StoreGateway sg = new StoreGateway();
                        sg.HandleStoreItemPaymentPending(invoice, CompileReportString());
                    }
                    else
                    {
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Couldn't Find Subscription", CompileReportString());
                    }
                }
                else
                {
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Couldn't Find Invoice", CompileReportString());
                }
                return invoice;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: CompileReportString());
            }
            return null;
        }
コード例 #40
0
        private Classes.Display.DisplayInvoice FailedPaypalPayment(string invoiceId)
        {
            PaymentGateway pg = new PaymentGateway();

            try
            {
                var invoice = pg.GetDisplayInvoice(new Guid(invoiceId));
                if (invoice != null)
                {
                    if (invoice.Subscription != null)
                    {
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Payment Failed", CompileReportString());

                        InvoiceFactory.EmailLeagueAboutFailedSubscription(invoice.Subscription.InternalObject, invoice.InvoiceId, invoice.Subscription.Price, invoice.Subscription.ValidUntil, invoice.InvoiceBilling.Email);

                        DateTime dateToGoBackTo = invoice.Subscription.ValidUntil.AddDays(-invoice.Subscription.SubscriptionPeriodLengthInDays);
                        pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Failed);

                        RDN.Library.Classes.League.LeagueFactory.UpdateLeagueSubscriptionPeriod(dateToGoBackTo, false, invoice.Subscription.InternalObject);
                    }
                    else if (invoice.Paywall != null)
                    {
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Paywall Payment Failed", CompileReportString());

                        pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Failed);
                    }
                    else
                    {
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal:Failed Payment", CompileReportString());
                    }
                }
                else
                {
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Couldn't Find Invoice", CompileReportString());
                }
                return invoice;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: CompileReportString());
            }
            return null;
        }