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;
            }
        }
        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();
                                }
                            }
                        }
                    }
                }
            }
        }
 private void SaveGateWay()
 {
     _PaymentGateway.UpdateConfigData(this.GetConfigData());
     _PaymentGateway.Save();
     _ProviderInstance = _PaymentGateway.GetInstance();
     if (ShowPaymentMethods(_PaymentGateway))
     {
         //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 = PaymentGatewayDataSource.Load(_PaymentGatewayId);
                 }
                 else if (method.PaymentGateway != null && method.PaymentGateway.Id == _PaymentGatewayId)
                 {
                     method.PaymentGateway = null;
                 }
                 method.Save();
             }
             index++;
         }
     }
 }
        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);
                        }
                    }
                }
            }
        }
        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();
        }
Esempio n. 6
0
        public static PayPalProvider GetPayPalProvider()
        {
            int gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(Misc.GetClassId(typeof(PayPalProvider)));

            if (gatewayId != 0)
            {
                PaymentGateway gateway = PaymentGatewayDataSource.Load(gatewayId);
                return((PayPalProvider)gateway.GetInstance());
            }
            return(null);
        }
Esempio n. 7
0
        public static GoogleCheckout GetInstance()
        {
            int gwID = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(Utility.Misc.GetClassId(typeof(GoogleCheckout)));

            if (gwID == 0)
            {
                return(null);
            }
            else
            {
                PaymentGateway gateway          = PaymentGatewayDataSource.Load(gwID);
                GoogleCheckout _GatewayInstance = (GoogleCheckout)gateway.GetInstance();
                return(_GatewayInstance);
            }
        }
Esempio n. 8
0
        protected bool IsPartialCaptureSupported()
        {
            Transaction lastAuth = _Payment.Transactions.GetLastAuthorization();

            if (lastAuth != null)
            {
                PaymentGateway gateway = lastAuth.PaymentGateway;
                if (gateway != null)
                {
                    IPaymentProvider instance = gateway.GetInstance();
                    return((instance.SupportedTransactions & SupportedTransactions.PartialCapture) == SupportedTransactions.PartialCapture);
                }
            }
            return(false);
        }
Esempio n. 9
0
        protected void CardsList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DELETE_PROFILE")
            {
                int profileId = AlwaysConvert.ToInt(e.CommandArgument);
                if (profileId > 0 && CanBeDeleted(profileId))
                {
                    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")
                                {
                                    int id = profile.Id;
                                    profile.Delete();
                                    BindCards();
                                }
                                else
                                {
                                    DeleteMessage.Text = string.Format("Somthing went wrong! Unable to remove profile '{0} ending in {1}'", profile.InstrumentType, profile.ReferenceNumber);
                                    Logger.Error(rsp.ResponseMessage);
                                }
                            }
                            catch (Exception exp)
                            {
                                Logger.Error(exp.Message);
                            }
                        }
                    }
                }
            }

            if (e.CommandName == "EDIT_PROFILE")
            {
                Response.Redirect(string.Format("~/Members/EditPaymentType.aspx?ProfileId={0}", e.CommandArgument));
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Gets the payment provider instance for the given payment, if available.
        /// </summary>
        /// <param name="payment">The payment to identify the provider for.</param>
        /// <returns>The IPaymentProvider instance for the payment, or null if none is available.</returns>
        private static IPaymentProvider GetPaymentProvider(Payment payment)
        {
            if (payment == null)
            {
                return(null);
            }
            PaymentMethod paymentMethod = payment.PaymentMethod;

            if (paymentMethod == null)
            {
                return(null);
            }
            PaymentGateway gateway = paymentMethod.PaymentGateway;

            if (gateway == null)
            {
                return(null);
            }
            return(gateway.GetInstance());
        }
 protected void UpdateButton_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         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"]   = _profile.ReferenceNumber.PadLeft(8, 'x').ToUpper();
                 cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedValue;
                 cardDetails["ExpirationYear"]  = ExpirationYear.SelectedValue;
                 cardDetails["SecurityCode"]    = SecurityCode.Text;
                 PaymentInstrumentData instr = PaymentInstrumentData.CreateInstance(cardDetails, _profile.InstrumentType, null);
                 var rsp = provider.DoUpdatePaymentProfile(new CommerceBuilder.Payments.Providers.UpdatePaymentProfileRequest(AbleContext.Current.User, instr, _profile.CustomerProfileId, _profile.PaymentProfileId));
                 if (rsp.Successful || rsp.ResponseCode == "E00040")
                 {
                     _profile.Expiry = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedValue), AlwaysConvert.ToInt(ExpirationMonth.SelectedValue), 1));
                     _profile.Save();
                     SuccessMessage.Text    = string.Format(SuccessMessage.Text, LocaleHelper.LocalNow);
                     SuccessMessage.Visible = true;
                 }
                 else
                 {
                     ErrorMessage.Visible = true;
                     Logger.Error(rsp.ResponseMessage);
                 }
             }
             catch (Exception exp)
             {
                 Logger.Error(exp.Message);
             }
         }
     }
 }
Esempio n. 12
0
        public bool ShowButton(string buttonName, object dataItem)
        {
            Payment          payment  = (Payment)dataItem;
            PaymentMethod    method   = payment.PaymentMethod;
            PaymentGateway   gateway  = method == null ? null : method.PaymentGateway;
            IPaymentProvider provider = null;

            if (gateway != null)
            {
                provider = gateway.GetInstance();
            }

            SupportedTransactions supportedTransactions = SupportedTransactions.None;

            if (provider != null)
            {
                supportedTransactions = provider.SupportedTransactions;
            }

            switch (buttonName.ToUpperInvariant())
            {
            case "RETRYAUTH":
                if (provider != null)
                {
                    if (!(((supportedTransactions & SupportedTransactions.Authorize) == SupportedTransactions.Authorize) || ((supportedTransactions & SupportedTransactions.AuthorizeCapture) == SupportedTransactions.AuthorizeCapture)))
                    {
                        return(false);
                    }
                }

                // DISABLE FOR PHONE CALL PAYMENT METHOD
                if (payment.PaymentMethod != null && payment.PaymentMethod.PaymentInstrumentType == PaymentInstrumentType.PhoneCall)
                {
                    return(false);
                }
                return(payment.PaymentStatus == PaymentStatus.AuthorizationFailed);

            case "RETRYCAPTURE":
                if (provider != null)
                {
                    if (!(((supportedTransactions & SupportedTransactions.Authorize) == SupportedTransactions.Authorize) || ((supportedTransactions & SupportedTransactions.AuthorizeCapture) == SupportedTransactions.AuthorizeCapture)))
                    {
                        return(false);
                    }
                }

                // DISABLE FOR PHONE CALL PAYMENT METHOD
                if (payment.PaymentMethod != null && payment.PaymentMethod.PaymentInstrumentType == PaymentInstrumentType.PhoneCall)
                {
                    return(false);
                }
                return(payment.PaymentStatus == PaymentStatus.CaptureFailed);

            case "RECEIVED":
                return(payment.PaymentStatus == PaymentStatus.Unprocessed);

            case "AUTHORIZE":
                if (provider != null)
                {
                    if (!(((supportedTransactions & SupportedTransactions.Authorize) == SupportedTransactions.Authorize) || ((supportedTransactions & SupportedTransactions.AuthorizeCapture) == SupportedTransactions.AuthorizeCapture)))
                    {
                        return(false);
                    }
                }

                // DISABLE FOR PHONE CALL PAYMENT METHOD
                if (payment.PaymentMethod != null && payment.PaymentMethod.PaymentInstrumentType == PaymentInstrumentType.PhoneCall)
                {
                    return(false);
                }
                return(payment.PaymentStatus == PaymentStatus.Unprocessed);

            case "VOID":
                if (provider != null)
                {
                    if (!((supportedTransactions & SupportedTransactions.Void) == SupportedTransactions.Void))
                    {
                        return(false);
                    }
                }

                //Disable Void for Google Checkout AND PHONE CALL PAYMENT METHOD
                if (payment.PaymentMethod != null && (payment.PaymentMethod.PaymentInstrumentType == PaymentInstrumentType.GoogleCheckout || payment.PaymentMethod.PaymentInstrumentType == PaymentInstrumentType.PhoneCall))
                {
                    return(false);
                }
                else
                {
                    //VOID SHOULD ONLY BE SHOWN IF THE PAYMENT IS UNPROCESSED OR IN AN AUTHORIZED STATE
                    return(payment.PaymentStatus == PaymentStatus.Unprocessed ||
                           payment.PaymentStatus == PaymentStatus.AuthorizationFailed ||
                           payment.PaymentStatus == PaymentStatus.Authorized ||
                           payment.PaymentStatus == PaymentStatus.CaptureFailed);
                }

            case "CAPTURE":
                if (provider != null)
                {
                    if (!(((supportedTransactions & SupportedTransactions.Capture) == SupportedTransactions.Capture) || ((supportedTransactions & SupportedTransactions.AuthorizeCapture) == SupportedTransactions.AuthorizeCapture)))
                    {
                        return(false);
                    }
                }

                // DISABLE FOR PHONE CALL PAYMENT METHOD
                if (payment.PaymentMethod != null && payment.PaymentMethod.PaymentInstrumentType == PaymentInstrumentType.PhoneCall)
                {
                    return(false);
                }
                return(payment.PaymentStatus == PaymentStatus.Authorized);

            case "CANCEL":
                // DISABLE FOR PHONE CALL PAYMENT METHOD
                if (payment.PaymentMethod != null && payment.PaymentMethod.PaymentInstrumentType == PaymentInstrumentType.PhoneCall)
                {
                    return(false);
                }
                return(payment.PaymentStatus == PaymentStatus.Completed);

            case "REFUND":
                if (provider != null)
                {
                    if (!((supportedTransactions & SupportedTransactions.Refund) == SupportedTransactions.Refund))
                    {
                        return(false);
                    }
                }

                //SHOW REFUND IF THE PAYMENT WAS MADE WITHIN 60 DAYS
                //AND THE PAYMENT IS CAPTURED
                //AND THERE IS IS A POSTIVE TRANSACTION CAPTURE AMOUNT
                return((payment.PaymentDate > DateTime.UtcNow.AddDays(-60)) &&
                       (payment.PaymentStatus == PaymentStatus.Captured) &&
                       (payment.Transactions.GetTotalCaptured() > 0));

            case "DELETE":
                //BY DEFAULT DO NOT SHOW THE DELETE BUTTON
                return(false);

            default:
                throw new ArgumentException("Invalid button name: '" + buttonName, buttonName);
            }
        }
        protected void SaveCardButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CustomValidation())
            {
                AccountDataDictionary cardDetails = new AccountDataDictionary();
                cardDetails["AccountName"] = CardName.Text.Trim();
                cardDetails["AccountNumber"] = CardNumber.Text.Trim();
                cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedItem.Value;
                cardDetails["ExpirationYear"] = ExpirationYear.SelectedItem.Value;
                cardDetails["SecurityCode"] = SecurityCode.Text.Trim();
                PaymentMethod method = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue));
                PaymentInstrumentData instr = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
                PaymentGateway gateway = method.PaymentGateway;
                if (gateway != null)
                {
                    var provider = gateway.GetInstance();
                    string customerProfileId = string.Empty;
                    var profileResult = _user.PaymentProfiles.Where(p => p.GatewayIdentifier == gateway.ClassId)
                        .GroupBy(p => p.CustomerProfileId)
                        .Take(1)
                        .Select(g => new { CustomerProfileId = g.Key })
                        .SingleOrDefault();

                    if (profileResult != null && !string.IsNullOrEmpty(profileResult.CustomerProfileId))
                        customerProfileId = profileResult.CustomerProfileId;

                    if (string.IsNullOrEmpty(customerProfileId))
                    {
                        try 
                        {
                            var rsp = provider.DoCreateCustomerProfile(new CommerceBuilder.Payments.Providers.CreateCustomerProfileRequest(_user));
                            if (rsp.Successful)
                                customerProfileId = rsp.CustomerProfileId;
                            else if (rsp.ResponseCode == "E00039")
                            {
                                var match = Regex.Match(rsp.ResponseMessage, @"\d+", RegexOptions.IgnoreCase);
                                if(match.Success)
                                    customerProfileId = match.Value;
                                else
                                    ErrorMessage.Text = rsp.ResponseMessage;
                            }
                            else
                                ErrorMessage.Text = rsp.ResponseMessage;
                        }
                        catch(Exception exp)
                        {
                            ErrorMessage.Text = exp.Message;
                        }

                        if (string.IsNullOrEmpty(customerProfileId)) return;
                    }

                    try
                    {
                        var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_user, instr, customerProfileId) { ValidateProfile = true });
                        if (rsp.Successful)
                        {
                            GatewayPaymentProfile gwprofile = new GatewayPaymentProfile();
                            gwprofile.NameOnCard = CardName.Text.Trim(); ;
                            gwprofile.Expiry = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedItem.Value), AlwaysConvert.ToInt(ExpirationMonth.SelectedItem.Value), 1));
                            gwprofile.CustomerProfileId = customerProfileId;
                            gwprofile.PaymentProfileId = rsp.PaymentProfileId;
                            gwprofile.ReferenceNumber = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                            gwprofile.User = _user;
                            gwprofile.InstrumentType = instr.InstrumentType;
                            gwprofile.PaymentMethodName = method.Name;
                            gwprofile.GatewayIdentifier = gateway.ClassId;
                            gwprofile.Save();
                            if (_user.PaymentProfiles.Count == 0)
                            {
                                _user.Settings.DefaultPaymentProfileId = gwprofile.Id;
                                _user.Settings.Save();
                            }
                            CardName.Text = string.Empty;
                            CardNumber.Text = string.Empty;
                            ExpirationMonth.SelectedIndex = 0;
                            ExpirationYear.SelectedIndex = 0;
                            BindCards();
                        }
                        else
                        {
                            ErrorMessage.Text = rsp.ResponseMessage;
                            Logger.Error(rsp.ResponseMessage);
                        }
                    }
                    catch (Exception exp)
                    {
                        ErrorMessage.Text = exp.Message;
                    }
                }
            }
        }
        protected void SaveCardButton_Click(Object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                GatewayPaymentProfile profile = _Subscription.PaymentProfile;
                if (profile != null)
                {
                    AccountDataDictionary cardDetails = new AccountDataDictionary();
                    cardDetails["AccountName"]     = CardName.Text.Trim();
                    cardDetails["AccountNumber"]   = CardNumber.Text.Trim();
                    cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedItem.Value;
                    cardDetails["ExpirationYear"]  = ExpirationYear.SelectedItem.Value;
                    cardDetails["SecurityCode"]    = SecurityCode.Text.Trim();
                    PaymentMethod         method = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue));
                    PaymentInstrumentData instr  = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
                    int            gatewayId     = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(_Subscription.PaymentProfile.GatewayIdentifier);
                    PaymentGateway gateway       = PaymentGatewayDataSource.Load(gatewayId);
                    if (gateway != null)
                    {
                        var provider = gateway.GetInstance();
                        try
                        {
                            var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_Subscription.User, instr, profile.CustomerProfileId)
                            {
                                ValidateProfile = true
                            });
                            if (rsp.Successful)
                            {
                                GatewayPaymentProfile gwprofile = new GatewayPaymentProfile();
                                gwprofile.NameOnCard        = CardName.Text.Trim();;
                                gwprofile.Expiry            = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedItem.Value), AlwaysConvert.ToInt(ExpirationMonth.SelectedItem.Value), 1));
                                gwprofile.CustomerProfileId = profile.CustomerProfileId;
                                gwprofile.PaymentProfileId  = rsp.PaymentProfileId;
                                gwprofile.ReferenceNumber   = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                                gwprofile.User              = _Subscription.User;
                                gwprofile.InstrumentType    = instr.InstrumentType;
                                gwprofile.GatewayIdentifier = profile.GatewayIdentifier;
                                gwprofile.Save();
                                BindPayments(gwprofile.Id);
                                CardName.Text   = string.Empty;
                                CardNumber.Text = string.Empty;
                                ExpirationMonth.SelectedIndex = 0;
                                ExpirationYear.SelectedIndex  = 0;
                                AddCardPopup.Hide();
                            }
                            else
                            {
                                ErrorMessage.Text = rsp.ResponseMessage;
                                AddCardPopup.Show();
                            }
                        }
                        catch (Exception exp)
                        {
                            Logger.Error(exp.Message);
                            ErrorMessage.Text = exp.Message;
                            AddCardPopup.Show();
                        }
                    }

                    BindPayments(profile.Id);
                }
            }
            else
            {
                AddCardPopup.Show();
            }
        }
Esempio n. 15
0
        protected void CreditCardButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CustomValidation())
            {
                // CREATE THE PAYMENT OBJECT
                Payment payment = GetPayment();

                // PROCESS CHECKING OUT EVENT
                bool checkOut = true;
                if (CheckingOut != null)
                {
                    CheckingOutEventArgs c = new CheckingOutEventArgs(payment);
                    CheckingOut(this, c);
                    checkOut = !c.Cancel;
                }

                if (checkOut)
                {
                    // CONTINUE TO PROCESS THE CHECKOUT
                    Basket           basket           = AbleContext.Current.User.Basket;
                    ICheckoutService checkoutService  = AbleContext.Resolve <ICheckoutService>();
                    CheckoutRequest  checkoutRequest  = new CheckoutRequest(basket, payment);
                    CheckoutResponse checkoutResponse = checkoutService.ExecuteCheckout(checkoutRequest);
                    if (checkoutResponse.Success)
                    {
                        if (trSaveCard.Visible && SaveCard.Checked)
                        {
                            AccountDataDictionary cardDetails = new AccountDataDictionary();
                            cardDetails["AccountName"]     = CardName.Text.Trim();
                            cardDetails["AccountNumber"]   = CardNumber.Text.Trim();
                            cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedItem.Value;
                            cardDetails["ExpirationYear"]  = ExpirationYear.SelectedItem.Value;
                            cardDetails["SecurityCode"]    = SecurityCode.Text.Trim();
                            PaymentMethod         method  = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue));
                            PaymentGateway        gateway = method.PaymentGateway;
                            PaymentInstrumentData instr   = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
                            if (gateway != null)
                            {
                                var    provider          = gateway.GetInstance();
                                string customerProfileId = string.Empty;
                                var    profileResult     = _user.PaymentProfiles.Where(p => p.GatewayIdentifier == gateway.ClassId)
                                                           .GroupBy(p => p.CustomerProfileId)
                                                           .Take(1)
                                                           .Select(g => new { CustomerProfileId = g.Key })
                                                           .SingleOrDefault();

                                if (profileResult != null && !string.IsNullOrEmpty(profileResult.CustomerProfileId))
                                {
                                    customerProfileId = profileResult.CustomerProfileId;
                                }

                                if (string.IsNullOrEmpty(customerProfileId))
                                {
                                    try
                                    {
                                        var rsp = provider.DoCreateCustomerProfile(new CommerceBuilder.Payments.Providers.CreateCustomerProfileRequest(_user));
                                        if (rsp.Successful)
                                        {
                                            customerProfileId = rsp.CustomerProfileId;
                                        }
                                        else if (rsp.ResponseCode == "E00039")
                                        {
                                            var match = Regex.Match(rsp.ResponseMessage, @"\d+", RegexOptions.CultureInvariant);
                                            if (match.Success)
                                            {
                                                customerProfileId = match.Value;
                                            }
                                            else
                                            {
                                                Logger.Error(rsp.ResponseMessage);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Error(rsp.ResponseMessage);
                                        }
                                    }
                                    catch (Exception exp)
                                    {
                                        Logger.Error(exp.Message);
                                    }
                                }

                                try
                                {
                                    var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_user, instr, customerProfileId)
                                    {
                                        ValidateProfile = true
                                    });
                                    if (rsp.Successful)
                                    {
                                        GatewayPaymentProfile gwprofile = new GatewayPaymentProfile();
                                        gwprofile.NameOnCard        = CardName.Text.Trim();;
                                        gwprofile.Expiry            = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedItem.Value), AlwaysConvert.ToInt(ExpirationMonth.SelectedItem.Value), 1));
                                        gwprofile.CustomerProfileId = customerProfileId;
                                        gwprofile.PaymentProfileId  = rsp.PaymentProfileId;
                                        gwprofile.ReferenceNumber   = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                                        gwprofile.User              = _user;
                                        gwprofile.InstrumentType    = instr.InstrumentType;
                                        gwprofile.PaymentMethodName = method.Name;
                                        gwprofile.GatewayIdentifier = gateway.ClassId;
                                        gwprofile.Save();
                                        CardName.Text   = string.Empty;
                                        CardNumber.Text = string.Empty;
                                        ExpirationMonth.SelectedIndex = 0;
                                        ExpirationYear.SelectedIndex  = 0;
                                    }
                                }
                                catch (Exception exp)
                                {
                                    Logger.Error(exp.Message);
                                }
                            }
                        }

                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                        Response.Redirect(AbleCommerce.Code.NavigationHelper.GetReceiptUrl(checkoutResponse.Order.OrderNumber));
                    }
                    else
                    {
                        IList <string> warningMessages = checkoutResponse.WarningMessages;
                        if (warningMessages.Count == 0)
                        {
                            warningMessages.Add("The order could not be submitted at this time.  Please try again later or contact us for assistance.");
                        }
                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                    }
                }
            }
        }
        protected GatewayPaymentProfile CreateProfile(AccountDataDictionary cardDetails)
        {
            PaymentMethod         method  = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue));
            PaymentGateway        gateway = method.PaymentGateway;
            PaymentInstrumentData instr   = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
            GatewayPaymentProfile profile = null;

            if (gateway != null)
            {
                var    provider          = gateway.GetInstance();
                string customerProfileId = string.Empty;
                var    profileResult     = _user.PaymentProfiles.Where(p => p.GatewayIdentifier == gateway.ClassId)
                                           .GroupBy(p => p.CustomerProfileId)
                                           .Take(1)
                                           .Select(g => new { CustomerProfileId = g.Key })
                                           .SingleOrDefault();

                if (profileResult != null && !string.IsNullOrEmpty(profileResult.CustomerProfileId))
                {
                    customerProfileId = profileResult.CustomerProfileId;
                }

                if (string.IsNullOrEmpty(customerProfileId))
                {
                    try
                    {
                        var rsp = provider.DoCreateCustomerProfile(new CommerceBuilder.Payments.Providers.CreateCustomerProfileRequest(_user));
                        if (rsp.Successful)
                        {
                            customerProfileId = rsp.CustomerProfileId;
                        }
                        else if (rsp.ResponseCode == "E00039")
                        {
                            var match = Regex.Match(rsp.ResponseMessage, @"\d+", RegexOptions.CultureInvariant);
                            if (match.Success)
                            {
                                customerProfileId = match.Value;
                            }
                            else
                            {
                                Logger.Error(rsp.ResponseMessage);
                            }
                        }
                        else
                        {
                            Logger.Error(rsp.ResponseMessage);
                        }
                    }
                    catch (Exception exp)
                    {
                        Logger.Error(exp.Message);
                    }
                }

                try
                {
                    var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_user, instr, customerProfileId)
                    {
                        ValidateProfile = true
                    });
                    if (rsp.Successful)
                    {
                        GatewayPaymentProfile gwprofile = new GatewayPaymentProfile();
                        gwprofile.NameOnCard        = CardName.Text.Trim();;
                        gwprofile.Expiry            = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedItem.Value), AlwaysConvert.ToInt(ExpirationMonth.SelectedItem.Value), 1));
                        gwprofile.CustomerProfileId = customerProfileId;
                        gwprofile.PaymentProfileId  = rsp.PaymentProfileId;
                        gwprofile.ReferenceNumber   = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                        gwprofile.User              = _user;
                        gwprofile.InstrumentType    = instr.InstrumentType;
                        gwprofile.PaymentMethodName = method.Name;
                        gwprofile.GatewayIdentifier = gateway.ClassId;
                        gwprofile.Save();
                        CardName.Text   = string.Empty;
                        CardNumber.Text = string.Empty;
                        ExpirationMonth.SelectedIndex = 0;
                        ExpirationYear.SelectedIndex  = 0;
                        profile = gwprofile;
                    }
                }
                catch (Exception exp)
                {
                    Logger.Error(exp.Message);
                }
            }

            return(profile);
        }
Esempio n. 17
0
        public void ProcessRequest(HttpContext context)
        {
            //GET REFERENCE TO REQUEST
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;
            TraceContext trace    = context.Trace;

            //RECORD FORM VALUES TO TRACE OUTPUT
            foreach (string key in request.Form)
            {
                context.Trace.Write(key + ":" + request.Form[key]);
            }
            //SETUP DEFAULT REDIRECT URL
            string redirectUrl = "~/Default.aspx";
            //INITIALIZE THE PAYPAL PROVIDER
            PaymentGateway paypalGateway = PayPalProvider.GetPayPalPaymentGateway(true);

            if (paypalGateway == null)
            {
                response.Redirect(redirectUrl);
            }
            //LOOK FOR ORDER ID
            int    orderId;
            string customValue = request.Form["custom"];

            if (!String.IsNullOrEmpty(customValue))
            {
                int index = customValue.IndexOf(":");
                if (index > 0)
                {
                    orderId = AlwaysConvert.ToInt(customValue.Substring(0, index));
                }
                else
                {
                    orderId = AlwaysConvert.ToInt(customValue);
                }
            }
            else
            {
                // TRY TO LOCATE ORDER ID AS QUERY STRING PARAMETER
                orderId = AlwaysConvert.ToInt(request.QueryString["OrderId"]);
            }

            //IF ORDER ID WAS NOT IN CUSTOM, SEE IF WE CAN FIND THE ORDER VIA TRANSACTION ID
            if (orderId == 0)
            {
                trace.Write("OrderId not found in custom field; lookup via transaction ID");
                string parentTransactionId = IpnProcessor.GetFormValue(request.Form, "parent_txn_id");
                if (!string.IsNullOrEmpty(parentTransactionId) && (paypalGateway != null))
                {
                    trace.Write("Query for parent transaction " + parentTransactionId);
                    orderId = FindPayPalOrderId(paypalGateway.PaymentGatewayId, parentTransactionId);
                    if (orderId != 0)
                    {
                        trace.Write("Order ID Found: " + orderId.ToString());
                    }
                }
            }
            //TRY TO LOAD ORDER
            Order order = OrderDataSource.Load(orderId);

            //IF ORDER LOAD FAILS, STOP PROCESSING AND REDIRECT
            if (order == null)
            {
                response.Redirect(redirectUrl);
            }
            //ORDER LOAD SUCCESSFUL, UPDATE DEFAULT REDIRECT URL
            redirectUrl = "~/Members/MyOrder.aspx?OrderId=" + orderId.ToString();
            //IF GATEWAY NOT FOUND, STOP PROCESSING AND REDIRECT
            PayPalProvider provider = (PayPalProvider)paypalGateway.GetInstance();
            //GET TRANSACTION AMOUNT
            LSDecimal curSignedPayment = AlwaysConvert.ToDecimal(request.Form["mc_gross"]);
            LSDecimal curPayment       = Math.Abs((Decimal)curSignedPayment);

            context.Trace.Write("Transaction Amount is " + curPayment.ToString());
            if (curPayment != 0)
            {
                //VERIFY PAYMENT NOTIFICATION WITH PAYPAL
                bool valid = provider.ValidateNotification(request.Form.ToString());
                if (!valid)
                {
                    response.Redirect(redirectUrl);
                }
                //VERIFY THE RECEIVER EMAIL
                string lowerReceiverEmail   = AlwaysConvert.ToString(request.Form["receiver_email"]).ToLowerInvariant();
                string lowerProviderAccount = provider.PayPalAccount.ToLowerInvariant();
                if (lowerReceiverEmail != lowerProviderAccount)
                {
                    context.Trace.Write("Receiver Email (" + lowerReceiverEmail + ") does not match Primary Account (" + lowerProviderAccount + ")");
                    response.Redirect(redirectUrl);
                }
                //CHECK WHETHER TRANSACTION IS ALREADY PRESENT IN DATABASE
                string paypalTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                string authTransactionId   = IpnProcessor.GetFormValue(request.Form, "auth_id");
                string paymentStatus       = IpnProcessor.GetFormValue(request.Form, "payment_status").ToUpperInvariant();
                string authStatus          = IpnProcessor.GetFormValue(request.Form, "auth_status").ToUpperInvariant();
                context.Trace.Write("Transaction ID Is " + paypalTransactionId);
                context.Trace.Write("Payment Status Is " + paymentStatus);
                context.Trace.Write("Auth Status Is " + authStatus);

                //CHECK FOR THIS PAYPAL TRANSACTION (MATCHING PROVIDER, PAYPAL TRANSACTION ID, AND PAYMENT STATUS)
                Payment     payment            = null;
                Transaction pendingTransaction = null;
                if (!string.IsNullOrEmpty(paypalTransactionId))
                {
                    TransactionCollection matchingTransactions = TransactionDataSource.LoadForProviderTransaction(paypalGateway.PaymentGatewayId, paypalTransactionId);
                    foreach (Transaction tx in matchingTransactions)
                    {
                        //WHEN PAYMENT IS BY ECHECK, IPN ISSUES A PENDING TRANSACTION
                        //SECOND IPN COMES FOR COMPLETED STATUS USING SAME TRANSACTION ID
                        if ((tx.ResponseCode == "PENDING") && (paymentStatus != "PENDING"))
                        {
                            //WE HAVE TO GET THE TRANSACTION VIA THE PAYMENT OBJECT
                            //OTHERWISE WE WILL HAVE PROBLEMS WITH DATA CONSISTENCY LATER
                            payment = tx.Payment;
                            foreach (Transaction ptx in payment.Transactions)
                            {
                                if (ptx.TransactionId == tx.TransactionId)
                                {
                                    pendingTransaction = ptx;
                                }
                            }
                        }
                        else if ((tx.TransactionType != TransactionType.Void) && (paymentStatus == "VOIDED"))
                        {
                            //IF WE VOID AN AUTHORIZATION, THE VOID HAS THE SAME TXID
                            //THE AUTHORIZATION WILL HAVE A BLANK RESPONSE CODE
                            //THE VOID SHOULD HAVE A 'VOIDED' RESPONSE CODE
                            //(THIS TRANSACTION IS NOT A MATCH AND SHOULD BE IGNORED)
                        }
                        else
                        {
                            //NO FURTHER PROCESSING, REDIR TO ORDER SCREEN
                            context.Trace.Write("Transaction ID " + paypalTransactionId + " Already Exists in Database");
                            response.Redirect(redirectUrl);
                        }
                    }
                }

                Transaction       transaction       = null;
                PaymentMethod     paypalMethod      = PayPalProvider.GetPayPalPaymentMethod(true);
                PaymentCollection orderPayments     = order.Payments;
                Transaction       authTransaction   = null;
                PaymentStatus[]   validAuthStatuses = { PaymentStatus.Unprocessed, PaymentStatus.AuthorizationPending };
                context.Trace.Write("Processing Payment Status: " + paymentStatus);
                switch (paymentStatus)
                {
                case "PENDING":
                    //THIS IS A PENDING TRANSACTION, GET PENDING REASON AND FIND OUT IF IT IS AN ECHECK WAITING TO CLEAR
                    string pendingReason          = IpnProcessor.GetFormValue(request.Form, "pending_reason").ToLowerInvariant();
                    bool   isPendingeCheck        = (pendingReason == "echeck");
                    bool   isPendingAuthorization = (pendingReason == "authorization");
                    context.Trace.Write("Pending Reason: " + pendingReason);
                    context.Trace.Write("Is Pending eCheck: " + isPendingeCheck.ToString());
                    context.Trace.Write("Is Pending Authorization: " + isPendingAuthorization.ToString());
                    //FIND THE PAYPAL PAYMENT THAT IS UNPROCESSED OR PENDING AUTHORIZATION
                    payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validAuthStatuses);
                    if (payment != null)
                    {
                        //SEE IF WE CAN FIND A PENDING PAYPAL TRANSACTION WITHOUT A TXID
                        foreach (Transaction tx in payment.Transactions)
                        {
                            if ((tx.ResponseCode == "PENDING") && string.IsNullOrEmpty(tx.ProviderTransactionId))
                            {
                                transaction = tx;
                            }
                        }
                    }
                    //IF WE DID NOT FIND AN EXISTING TRANSACTION, CREATE A NEW ONE
                    if (transaction == null)
                    {
                        transaction = new Transaction();
                    }
                    //UPDATE THE TRANSACTION VALUES
                    transaction.TransactionType       = (isPendingeCheck ? TransactionType.Capture : TransactionType.Authorize);
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.Amount            = AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross"));
                    transaction.TransactionStatus = TransactionStatus.Successful;
                    if (isPendingAuthorization)
                    {
                        //THIS IS AN EXPECTED RESPONSE, NO NEED TO SAVE THE REASON CODES
                        transaction.ResponseMessage = string.Empty;
                        transaction.ResponseCode    = string.Empty;
                    }
                    else
                    {
                        transaction.ResponseMessage = pendingReason;
                        transaction.ResponseCode    = "PENDING";
                    }
                    transaction.AuthorizationCode = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.RemoteIP          = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer          = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                    if (payment == null)
                    {
                        payment                   = new Payment();
                        payment.OrderId           = orderId;
                        payment.PaymentMethodId   = paypalMethod.PaymentMethodId;
                        payment.PaymentMethodName = paypalMethod.Name;
                        order.Payments.Add(payment);
                    }
                    //UPDATE PAYMENT DETAILS
                    payment.ReferenceNumber = IpnProcessor.GetFormValue(request.Form, "payer_email");
                    payment.Amount          = transaction.Amount;
                    payment.PaymentDate     = transaction.TransactionDate;
                    if (isPendingAuthorization)
                    {
                        payment.PaymentStatus       = PaymentStatus.Authorized;
                        payment.PaymentStatusReason = string.Empty;
                    }
                    else
                    {
                        payment.PaymentStatus       = (isPendingeCheck ? PaymentStatus.CapturePending : PaymentStatus.AuthorizationPending);
                        payment.PaymentStatusReason = transaction.ResponseMessage;
                    }
                    //ADD IN TRANSACTION
                    payment.Transactions.Add(transaction);
                    break;

                case "COMPLETED":
                    //IF THIS IS A CAPTURE FROM AN AUTHORIZATION, FIND THE AUTHORIZATION TRANSACTION
                    //AND UPDATE THE STATUS ACCORDINGLY, DEPENDING ON WHETHER ADDITIONAL SETTLEMENT TRANSACTIONS REMAIN (INTREMSETTLE > 0)
                    authTransaction   = null;
                    authTransactionId = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    if (!string.IsNullOrEmpty(authTransactionId))
                    {
                        TransactionCollection matchingTransactions = TransactionDataSource.LoadForProviderTransaction(paypalGateway.PaymentGatewayId, authTransactionId);
                        //SHOULD ONLY BE ONE
                        if (matchingTransactions.Count > 0)
                        {
                            authTransaction = matchingTransactions[0];
                        }
                    }
                    //IF PAYPAL IS RUNNING IN CAPTURE MODE, WE MAY HAVE A COMPLETED PAYMENT
                    //WITH A PENDING OR UNPROCESSED PAYMENT ALREADY ASSOCIATED TO ORDER
                    if (pendingTransaction == null)
                    {
                        //FIND THE PAYPAL PAYMENT THAT IS UNPROCESSED OR PENDING
                        payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validAuthStatuses);
                        if (payment != null)
                        {
                            //SEE IF WE CAN FIND A PENDING PAYPAL TRANSACTION WITHOUT A TXID
                            foreach (Transaction tx in payment.Transactions)
                            {
                                if ((tx.ResponseCode == "PENDING") && string.IsNullOrEmpty(tx.ProviderTransactionId))
                                {
                                    pendingTransaction = tx;
                                }
                            }
                        }
                    }
                    //SEE IF THIS TRANSACTION WAS PENDING (SUCH AS A CHECK WAITING TO CLEAR)
                    if (pendingTransaction != null)
                    {
                        //GET THE PENDING TRANSACTION AND PAYMENT
                        payment     = order.Payments[order.Payments.IndexOf(pendingTransaction.PaymentId)];
                        transaction = payment.Transactions[payment.Transactions.IndexOf(pendingTransaction.TransactionId)];
                    }
                    else
                    {
                        //THIS IS NOT A PENDING TRANSACTION
                        //LOCATE THE APPROPRIATE PAYMENT
                        if (authTransaction != null)
                        {
                            payment = order.Payments[order.Payments.IndexOf(authTransaction.PaymentId)];
                        }
                        else
                        {
                            //FIND THE PAYPAL PAYMENT THAT CAN BE CAPTURED
                            PaymentStatus[] validCaptureStatuses = { PaymentStatus.Unprocessed, PaymentStatus.AuthorizationPending, PaymentStatus.Authorized, PaymentStatus.CaptureFailed, PaymentStatus.CapturePending };
                            payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validCaptureStatuses);
                            //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                            if (payment == null)
                            {
                                payment                   = new Payment();
                                payment.OrderId           = orderId;
                                payment.PaymentMethodId   = paypalMethod.PaymentMethodId;
                                payment.PaymentMethodName = paypalMethod.Name;
                                order.Payments.Add(payment);
                            }
                        }
                        //CREATE A NEW TRANSACTION RECORD
                        transaction           = new Transaction();
                        transaction.PaymentId = payment.PaymentId;
                    }
                    //UPDATE THE TRANSACTION DETAILS
                    transaction.TransactionType       = TransactionType.Capture;
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.RemoteIP              = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer              = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    transaction.TransactionStatus     = TransactionStatus.Successful;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.Amount          = AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross"));
                    transaction.ResponseCode    = paymentStatus;
                    transaction.ResponseMessage = string.Empty;

                    //HANDLE PARTIAL / FINAL CAPTURES
                    int remainingSettle = AlwaysConvert.ToInt(IpnProcessor.GetFormValue(request.Form, "remaining_settle"));
                    if (remainingSettle == 0)
                    {
                        //THIS IS A FINAL CAPTURE
                        transaction.TransactionType = TransactionType.Capture;
                        //SET PAYMENT AMOUNT TO SUM OF ALL CAPTURES
                        LSDecimal totalCaptures = 0;
                        foreach (Transaction tx in payment.Transactions)
                        {
                            if ((transaction.TransactionId != tx.TransactionId) &&
                                (tx.TransactionType == TransactionType.PartialCapture || tx.TransactionType == TransactionType.Capture))
                            {
                                totalCaptures += tx.Amount;
                            }
                        }
                        totalCaptures += transaction.Amount;
                        payment.Amount = totalCaptures;
                    }
                    else
                    {
                        //THIS IS A PARTIAL CAPTURE
                        transaction.TransactionType = TransactionType.PartialCapture;
                        //LEAVE PAYMENT AMOUNT ALONE (AMOUNT OF AUTHORIZATION)
                    }

                    //UPDATE PAYMENT DETAILS
                    payment.PaymentDate         = transaction.TransactionDate;
                    payment.PaymentStatus       = (remainingSettle == 0) ? PaymentStatus.Captured : PaymentStatus.Authorized;
                    payment.PaymentStatusReason = string.Empty;

                    //ADD IN TRANSACTION IF NEEDED
                    if (transaction.TransactionId == 0)
                    {
                        payment.Transactions.Add(transaction);
                    }
                    break;

                case "REFUNDED":
                case "REVERSED":
                    //GET THE REFUND AMOUNT
                    LSDecimal refundAmount = Math.Abs(AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross")));
                    //TRY TO LOCATE THE CORRECT PAYMENT BASED ON CAPTURE TRANSACITON ID
                    payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "parent_txn_id"));
                    if (payment == null)
                    {
                        //SEE IF WE CAN FIND THE PAYMENT VIA AUTH TRANSACTION ID
                        payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "auth_id"));
                    }
                    //CREATE A REFUND TRANSACTION
                    transaction = new Transaction();
                    //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                    if (payment == null)
                    {
                        payment                     = new Payment();
                        payment.OrderId             = orderId;
                        payment.PaymentMethodId     = paypalMethod.PaymentMethodId;
                        payment.PaymentMethodName   = paypalMethod.Name;
                        payment.Amount              = -1 * refundAmount;
                        transaction.TransactionType = TransactionType.Refund;
                        order.Payments.Add(payment);
                    }
                    else
                    {
                        if (payment.Amount == refundAmount)
                        {
                            //FULL REFUND
                            transaction.TransactionType = TransactionType.Refund;
                            payment.PaymentStatus       = PaymentStatus.Refunded;
                        }
                        else
                        {
                            //PARTIAL REFUND
                            transaction.TransactionType = TransactionType.PartialRefund;
                            payment.Amount       -= refundAmount;
                            payment.PaymentStatus = PaymentStatus.Captured;
                        }
                    }
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.TransactionStatus     = TransactionStatus.Successful;
                    transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.RemoteIP = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    transaction.Amount   = refundAmount;
                    string responseMessage = IpnProcessor.GetFormValue(request.Form, "reason_code");
                    if (responseMessage != "refund")
                    {
                        transaction.ResponseCode    = paymentStatus;
                        transaction.ResponseMessage = responseMessage;
                    }
                    //UPDATE PAYMENT DETAILS
                    payment.PaymentDate         = transaction.TransactionDate;
                    payment.PaymentStatusReason = string.Empty;
                    //ADD IN TRANSACTION
                    payment.Transactions.Add(transaction);
                    break;

                case "VOIDED":
                    //SEE IF WE CAN FIND THE PAYMENT VIA AUTH TRANSACTION ID
                    payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "auth_id"));
                    //WE ONLY NEED TO CONTINUE IF A PAYMENT TO VOID WAS FOUND
                    if (payment != null)
                    {
                        //PAYPAL DOES NOT SEND THE AMOUNT OF THE VOID
                        //SO IF THIS PAYMENT WAS PARTIALLY CAPTURED, WE NEED TO KNOW HOW MUCH TO VOID
                        LSDecimal remainingAuthorization = payment.Transactions.GetRemainingAuthorized();
                        if (remainingAuthorization > 0)
                        {
                            //CREATE A VOID TRANSACTION
                            transaction = new Transaction();
                            transaction.TransactionType       = TransactionType.Void;
                            transaction.Amount                = remainingAuthorization;
                            transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                            transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                            transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                            transaction.TransactionStatus     = TransactionStatus.Successful;
                            transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                            transaction.RemoteIP              = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                            transaction.Referrer              = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                            //UPDATE PAYMENT DETAILS
                            payment.PaymentDate         = transaction.TransactionDate;
                            payment.PaymentStatusReason = string.Empty;
                            if (payment.Amount == remainingAuthorization)
                            {
                                //FULL VOID, CHANGE PAYMENT STATUS TO VOID
                                payment.PaymentStatus = PaymentStatus.Void;
                            }
                            else
                            {
                                //PARTIAL VOID, REDUCE PAYMENT AMOUNT BY VOID
                                payment.Amount -= remainingAuthorization;
                                //PAYMENT HAS NO REMAINING AUTHORIZATION AND SO IT IS CAPTURED
                                payment.PaymentStatus = PaymentStatus.Captured;
                            }
                            //ADD IN TRANSACTION
                            payment.Transactions.Add(transaction);
                        }
                    }
                    break;

                case "FAILED":
                    //THIS IS A FAILED E-CHECK
                    //PENDINGTRANSACTION SHOULD HAVE BEEN OBTAINED ABOVE
                    if (payment != null && pendingTransaction != null)
                    {
                        pendingTransaction.TransactionStatus = TransactionStatus.Failed;
                        //MAKE SURE TO CLEAR OUT PENDING RESPONSECODE
                        pendingTransaction.ResponseCode = string.Empty;
                        //GET THE CURRENT TRANSACTION DATE
                        pendingTransaction.TransactionDate = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                        //UPDATE PAYMENT DETAILS
                        payment.PaymentDate         = pendingTransaction.TransactionDate;
                        payment.PaymentStatus       = (IsVoidableFailure(payment) ? PaymentStatus.Void : PaymentStatus.CaptureFailed);
                        payment.PaymentStatusReason = string.Empty;
                        //SAVE PAYMENT (AND CHILD TRANSACTIONS)
                        payment.Save();
                    }
                    break;

                default:
                    Logger.Warn("PayPal IPN transaction " + paypalTransactionId + " with a \"" + paymentStatus + "\" status was unhandled.");
                    break;
                }

                //IF PAYMENT IS SET, SAVE UPDATES
                if (payment != null)
                {
                    payment.Save();
                }
            }
            response.Redirect(redirectUrl);
        }
Esempio n. 18
0
        /// <summary>
        /// Binds the order details in the payment column
        /// </summary>
        protected void BindPaymentColumn()
        {
            // bind status
            OrderTotal.Text           = _order.TotalCharges.LSCurrencyFormat("lc");
            OrderBalance.Text         = _order.GetBalance(false).LSCurrencyFormat("lc");
            CurrentPaymentStatus.Text = _order.PaymentStatus.ToString();
            if (_order.PaymentStatus == OrderPaymentStatus.Paid)
            {
                CurrentPaymentStatus.CssClass = "goodCondition";
            }
            else
            {
                CurrentPaymentStatus.CssClass = "errorCondition";
            }


            // check for the last payment record
            Payment payment = GetLastPayment();

            if (payment != null)
            {
                // bind static payment info
                LastPaymentAmount.Text    = payment.Amount.LSCurrencyFormat("lc");
                LastPaymentStatus.Text    = StringHelper.SpaceName(payment.PaymentStatus.ToString());
                LastPaymentReference.Text = payment.PaymentMethodName;
                if (!string.IsNullOrEmpty(payment.ReferenceNumber))
                {
                    LastPaymentReference.Text += " " + payment.ReferenceNumber;
                }

                // bind transaction details
                Transaction lastAuthorization = payment.Transactions.GetLastAuthorization();
                if (lastAuthorization == null)
                {
                    lastAuthorization = payment.Transactions.GetLastRecurringAuthorization();
                }
                if (lastAuthorization != null)
                {
                    string friendlyCVV = AbleCommerce.Code.StoreDataHelper.TranslateCVVCode(lastAuthorization.CVVResultCode);
                    if (!string.IsNullOrEmpty(lastAuthorization.CVVResultCode))
                    {
                        friendlyCVV += " (" + lastAuthorization.CVVResultCode + ")";
                    }
                    LastPaymentCVV.Text = friendlyCVV;
                    string friendlyAVS = AbleCommerce.Code.StoreDataHelper.TranslateAVSCode(lastAuthorization.AVSResultCode);
                    if (!string.IsNullOrEmpty(lastAuthorization.AVSResultCode))
                    {
                        friendlyAVS += " (" + lastAuthorization.AVSResultCode + ")";
                    }
                    LastPaymentAVS.Text = friendlyAVS;
                }
                else
                {
                    TransactionPanel.Visible = false;
                }

                PaymentGateway gateway = null;
                if (payment.PaymentMethod != null)
                {
                    gateway = payment.PaymentMethod.PaymentGateway;
                }

                if (gateway == null && payment.PaymentProfile != null)
                {
                    int gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(payment.PaymentProfile.GatewayIdentifier);
                    gateway = PaymentGatewayDataSource.Load(gatewayId);
                }

                IPaymentProvider      provider = (gateway != null ? gateway.GetInstance() : null);
                SupportedTransactions supportedTransactions = SupportedTransactions.None;
                if (provider != null)
                {
                    supportedTransactions = provider.SupportedTransactions;
                }

                // bind payment buttons
                ReceivedButton.Visible = (payment.PaymentStatus == PaymentStatus.Unprocessed);
                if ((supportedTransactions & SupportedTransactions.Void) == SupportedTransactions.Void)
                {
                    VoidLink.Visible     = ((payment.PaymentStatus == PaymentStatus.Unprocessed) || (payment.PaymentStatus == PaymentStatus.Authorized) || (payment.PaymentStatus == PaymentStatus.AuthorizationFailed) || (payment.PaymentStatus == PaymentStatus.CaptureFailed));
                    VoidLink.NavigateUrl = "Payments/VoidPayment.aspx?PaymentId=" + payment.Id.ToString();
                }
                else
                {
                    VoidLink.Visible = false;
                }

                if ((((supportedTransactions & SupportedTransactions.Capture) == SupportedTransactions.Capture) || ((supportedTransactions & SupportedTransactions.AuthorizeCapture) == SupportedTransactions.AuthorizeCapture)))
                {
                    CaptureLink.Visible     = (payment.PaymentStatus == PaymentStatus.Authorized);
                    CaptureLink.NavigateUrl = "Payments/CapturePayment.aspx?PaymentId=" + payment.Id.ToString();
                }
                else
                {
                    VoidLink.Visible = false;
                }

                ButtonPanel.Visible = ReceivedButton.Visible || VoidLink.Visible || CaptureLink.Visible;
            }
            else
            {
                LastPaymentPanel.Visible = false;
            }

            // IP details
            if (!string.IsNullOrEmpty(_order.RemoteIP))
            {
                CustomerIP.Text               = _order.RemoteIP;
                CustomerIPBlocked.Visible     = BannedIPDataSource.IsBanned(CustomerIP.Text);
                BlockCustomerIP.Visible       = (!CustomerIPBlocked.Visible && (_order.RemoteIP != Request.UserHostAddress));
                BlockCustomerIP.OnClientClick = string.Format(BlockCustomerIP.OnClientClick, _order.RemoteIP);
            }
            else
            {
                CustomerIPPanel.Visible = false;
            }

            //Refferrer url
            if (!string.IsNullOrEmpty(_order.Referrer))
            {
                if (_order.Referrer.Length > UrlMaxLenght)
                {
                    OrderReferrer.NavigateUrl = _order.Referrer;
                    OrderReferrer.Text        = _order.Referrer.Substring(0, UrlMaxLenght) + "...";
                }
                else
                {
                    OrderReferrer.NavigateUrl = _order.Referrer;
                    OrderReferrer.Text        = _order.Referrer.Replace("/", "/<wbr />").Replace("_", "_<wbr />");
                }
            }

            // affiliate details
            if (_order.AffiliateId != 0)
            {
                Affiliate.Text = _order.Affiliate.Name;
            }
            else
            {
                AffiliatePanel.Visible = false;
            }
            TaxExemptionMessagePanel.Visible = this._order.Items.TotalPrice(OrderItemType.Tax) == 0 && !string.IsNullOrEmpty(this._order.TaxExemptionReference);
        }