private void Charge(Transaction t)
        {
            PayPalAPI ppAPI = this.GetPaypalAPI();

            try
            {
                string OrderNumber = string.Empty;

                OrderNumber = t.MerchantInvoiceNumber;
                // Solves Duplicate Order Number Problem
                OrderNumber = OrderNumber + System.Guid.NewGuid().ToString();

                DoDirectPaymentResponseType chargeResponse = ppAPI.DoDirectPayment(String.Format("{0:N}", t.Amount),
                                                                                   t.Customer.LastName,
                                                                                   t.Customer.FirstName,
                                                                                   t.Customer.ShipLastName,
                                                                                   t.Customer.ShipFirstName,
                                                                                   t.Customer.Street,
                                                                                   "",
                                                                                   t.Customer.City,
                                                                                   t.Customer.Region,
                                                                                   t.Customer.PostalCode,
                                                                                   this.ConvertCountryName(t.Customer.Country),
                                                                                   t.Card.CardTypeName,
                                                                                   t.Card.CardNumber,
                                                                                   t.Card.SecurityCode,
                                                                                   t.Card.ExpirationMonth,
                                                                                   t.Card.ExpirationYear,
                                                                                   PaymentActionCodeType.Sale,
                                                                                   t.Customer.IpAddress,
                                                                                   t.Customer.ShipStreet,
                                                                                   "",
                                                                                   t.Customer.ShipCity,
                                                                                   t.Customer.ShipRegion,
                                                                                   t.Customer.ShipPostalCode,
                                                                                   this.ConvertCountryName(t.Customer.ShipCountry),
                                                                                   OrderNumber);



                if ((chargeResponse.Ack == AckCodeType.Success) || (chargeResponse.Ack == AckCodeType.SuccessWithWarning))
                {
                    t.Result.ReferenceNumber = chargeResponse.TransactionID;
                    t.Result.Succeeded       = true;
                }
                else
                {
                    t.Result.Messages.Add(new Message("Paypal Charge Failed.", "", MessageType.Warning));
                    foreach (ErrorType ppError in chargeResponse.Errors)
                    {
                        t.Result.Messages.Add(new Message(ppError.LongMessage, ppError.ErrorCode, MessageType.Error));
                    }
                    t.Result.Succeeded = false;
                }
            }
            finally
            {
                ppAPI = null;
            }
        }
        private void setKeyResponseObjects(PayPalAPIInterfaceServiceService service, DoDirectPaymentResponseType response)
        {
            HttpContext CurrContext = HttpContext.Current;

            CurrContext.Items.Add("Response_apiName", "DoDirectPayment");
            CurrContext.Items.Add("Response_redirectURL", null);
            CurrContext.Items.Add("Response_requestPayload", service.getLastRequest());
            CurrContext.Items.Add("Response_responsePayload", service.getLastResponse());

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

            responseParams.Add("Correlation Id", response.CorrelationID);
            responseParams.Add("API Result", response.Ack.ToString());

            if (response.Ack.Equals(AckCodeType.FAILURE) ||
                (response.Errors != null && response.Errors.Count > 0))
            {
                CurrContext.Items.Add("Response_error", response.Errors);
            }
            else
            {
                CurrContext.Items.Add("Response_error", null);
                responseParams.Add("Transaction Id", response.TransactionID);
                responseParams.Add("Payment status", response.PaymentStatus.ToString());
                if (response.PendingReason != null)
                {
                    responseParams.Add("Pending reason", response.PendingReason.ToString());
                }
            }
            CurrContext.Items.Add("Response_keyResponseObject", responseParams);
            Server.Transfer("../APIResponse.aspx");
        }
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context)
        {
            if (context.Store == null)
            {
                throw new NullReferenceException("Store should not be null.");
            }

            if (context.BankCardInfo == null)
            {
                throw new NullReferenceException("BankCardInfo should not be null.");
            }

            var retVal = new ProcessPaymentResult();

            DoDirectPaymentResponseType response = null;
            string error;
            bool   isSuccess = false;
            var    doDirectPaymentRequest = GetDoDirectPaymentRequest(context);

            try
            {
                var service = GetService();
                response = service.DoDirectPayment(doDirectPaymentRequest);

                isSuccess = CheckResponse(response, out error);
                context.Payment.IsApproved = true;
            }
            catch (PayPal.Exception.ConnectionException ex)
            {
                error = ((PayPal.Exception.ConnectionException)ex.InnerException).Response;
            }

            PaymentStatus newStatus;

            if (isSuccess)
            {
                retVal.OuterId   = context.Payment.OuterId = response.TransactionID;
                retVal.IsSuccess = (response.Ack.Value == AckCodeType.SUCCESS || response.Ack.Value == AckCodeType.SUCCESSWITHWARNING);
                if (retVal.IsSuccess)
                {
                    context.Payment.CapturedDate = DateTime.UtcNow;
                    newStatus = PaymentStatus.Paid;
                }
                else
                {
                    context.Payment.VoidedDate = DateTime.UtcNow;
                    newStatus = PaymentStatus.Voided;
                }
            }
            else
            {
                retVal.Error = error;
                newStatus    = PaymentStatus.Voided;
            }

            retVal.NewPaymentStatus = context.Payment.PaymentStatus = newStatus;
            return(retVal);
        }
        protected void GetPaid(string itemType, string aditem, string amnt, CreditCardDetailsType cc)
        {
            HttpContext CurrContext = HttpContext.Current;

            //amnt = "1.00";
            try
            {
                DoDirectPaymentResponseType reply = DirectPayment.DoDirectPaymentAPIOperation(cc, amnt);
                Session["Reply"]       = reply;
                Session["PaymentInfo"] = cc;
                if (reply.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    switch (itemType)
                    {
                    case "car":
                        VehiclesBilling vb = Session["VehicleBilling"] as VehiclesBilling;
                        vb.PayPalId    = reply.TransactionID;
                        vb.PayPalState = reply.Ack.ToString();
                        vb.CreateTime  = Convert.ToDateTime(reply.Timestamp);
                        if (VehiclesBilling.PaidInFull(vb))
                        {
                            CustomerVehicleInfo.UpdateBillingId(Convert.ToInt32(Session["VehicleId"]), vb.Id);
                            NotifyCustomer(Convert.ToInt32(Session["VehicleId"]), itemType, vb.Payment, "0", reply.TransactionID);
                            NotifyAdmin(Request.QueryString["item"], vb.Payment, "0", reply.TransactionID);
                        }
                        break;

                    case "ad":
                        AdsBilling ad = new AdsBilling
                        {
                            CustomerId  = Convert.ToInt32(Session["CustomerId"]),
                            AdId        = Convert.ToInt32(Request.QueryString["id"]),
                            Payment     = Convert.ToDouble(amnt),
                            PayPalId    = reply.TransactionID,
                            PayPalState = reply.Ack.ToString(),
                            CreateTime  = Convert.ToDateTime(reply.Timestamp)
                        };
                        if (AdsBilling.InsertNewBilling(ad))
                        {
                            CustomerAd.PaidInFull(ad.AdId);
                            NotifyCustomer(ad.AdId, itemType, ad.Payment, "0", reply.TransactionID);
                            NotifyAdmin(Request.QueryString["item"], ad.Payment, "0", reply.TransactionID);
                        }
                        break;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", " alert('Transaction failed, please check your credit card information and try again.');", true);
                    //Server.Transfer("~/account/PaymentResponse.aspx");
                }
            }
            catch (WebException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
                ErrorHandler.writeExceptionToLogFile(ex);
            }
        }
示例#5
0
    public void DoDirectPayment()
    {
        DoDirectPaymentSample       sample = new DoDirectPaymentSample();
        DoDirectPaymentResponseType responseDoDirectPaymentResponseType = sample.DoDirectPaymentAPIOperation();

        Assert.IsNotNull(responseDoDirectPaymentResponseType);
        Assert.AreEqual(responseDoDirectPaymentResponseType.Ack.ToString().ToUpper(), "SUCCESS");
        Assert.IsNotNull(responseDoDirectPaymentResponseType.TransactionID);
    }
示例#6
0
        private void DoDirectPayment(HttpContext context)
        {
            DoDirectPaymentReq req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails                              = new DoDirectPaymentRequestDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard                   = new CreditCardDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails               = new PaymentDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal    = new BasicAmountType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress = new AddressType();
            req.DoDirectPaymentRequest.Version = "78.0";
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CreditCardNumber = context.Request.Params["cardNum"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CreditCardType   = (CreditCardTypeType)EnumUtils.getValue(context.Request.Params["creditcardType"], typeof(CreditCardTypeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CVV2             = context.Request.Params["cvv2Num"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.ExpMonth         = System.Convert.ToInt32(context.Request.Params["expDateMonth"]);
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.ExpYear          = System.Convert.ToInt32(context.Request.Params["expDateYear"]);
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentAction = (PaymentActionCodeType)EnumUtils.getValue(context.Request.Params["paymentType"], typeof(PaymentActionCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID         = (CurrencyCodeType)EnumUtils.getValue(context.Request.Params["currencyCode"], typeof(CurrencyCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.value              = context.Request.Params["amount"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Street1         = context.Request.Params["addr1"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Street2         = context.Request.Params["addr2"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.CityName        = context.Request.Params["city"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.StateOrProvince = context.Request.Params["state"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.PostalCode      = context.Request.Params["zipCode"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Country         = (CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Name            = context.Request.Params["firstName"] + context.Request.Params["lastName"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner                         = new PayerInfoType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName               = new PersonNameType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerCountry            = (CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.FirstName     = context.Request.Params["firstName"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.LastName      = context.Request.Params["lastName"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address                 = new AddressType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street1         = context.Request.Params["addr1"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street2         = context.Request.Params["addr2"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CityName        = context.Request.Params["city"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.StateOrProvince = context.Request.Params["state"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.PostalCode      = context.Request.Params["zipCode"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Country         = (CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Name            = context.Request.Params["firstName"] + context.Request.Params["lastName"];
            try
            {
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
                DoDirectPaymentResponseType      resp    = service.DoDirectPayment(req);
                context.Response.Write("<html><body><textarea rows=30 cols=80>");
                ObjectDumper.Write(resp, 5, context.Response.Output);
                context.Response.Write("</textarea></body></html>");
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
            }
        }
示例#7
0
        private OrderingResponse GetPayPalReceipt(DoDirectPaymentResponseType PayPalResponse)
        {
            OrderResponse oVerisignReceipt = new OrderResponse();

            try
            {
                oVerisignReceipt.AuthCode        = PayPalResponse.TransactionID;
                oVerisignReceipt.ReferenceNumber = PayPalResponse.CorrelationID;


                if (PayPalResponse.Ack == AckCodeType.Success | PayPalResponse.Ack == AckCodeType.SuccessWithWarning)
                {
                    oVerisignReceipt.ResponseCode = RETURNCODE.RET_CODE_SUCCESS;
                    oVerisignReceipt.Success      = true;
                    oVerisignReceipt.Message      = PayPalResponse.PaymentStatus.ToString();
                }
                else
                {
                    oVerisignReceipt.ResponseCode = RETURNCODE.RET_CODE_UNKNOWN_ERROR;
                    oVerisignReceipt.Success      = false;
                    oVerisignReceipt.Message      = PayPalResponse.Errors[0].LongMessage;
                }

                oVerisignReceipt.BankTotals  = 0;
                oVerisignReceipt.CardType    = "";
                oVerisignReceipt.Complete    = true;
                oVerisignReceipt.ISO         = 0;
                oVerisignReceipt.ReceiptID   = "";
                oVerisignReceipt.Ticket      = "";
                oVerisignReceipt.TimedOut    = false;
                oVerisignReceipt.TransAmount = 0;
                oVerisignReceipt.TransDate   = DateTime.Now;
                oVerisignReceipt.TransID     = "";
                oVerisignReceipt.TransTime   = DateTime.Now;
                oVerisignReceipt.TransType   = "";
            }
            catch (Exception ex)
            {
                //WriteToEventLog(EventLogEntryType.Error, "GetMonerisObjectFromVeriSignResponse", ex.ToString)
                oVerisignReceipt         = new OrderResponse();
                oVerisignReceipt.Message = "Invalid VeriSignResponse";
            }

            return(oVerisignReceipt);
        }
        private Response ParseResponse(PayPalAPIInterfaceServiceService service, DoDirectPaymentResponseType paypalResponse)
        {
            Response  response         = new Response();
            Hashtable hGatewayResponse = new Hashtable();

            HttpContext CurrContext = HttpContext.Current;

            response.GatewayRequestRaw  = service.getLastRequest();
            response.GatewayResponseRaw = service.getLastResponse();

            switch (paypalResponse.Ack.ToString().ToLower())
            {
            case "success":
                response.ResponseType  = TransactionResponseType.Approved;
                response.TransactionID = paypalResponse.TransactionID;
                response.AuthCode      = paypalResponse.CorrelationID;
                hGatewayResponse.Add("PaymentStatus", paypalResponse.PaymentStatus.ToString());

                if (paypalResponse.PendingReason != null)
                {
                    hGatewayResponse.Add("PendingReason", paypalResponse.PendingReason.ToString());
                }
                break;

            case "failure":
                response.ResponseType = TransactionResponseType.Denied;
                break;

            default:
                response.ResponseType = TransactionResponseType.Error;
                break;
            }

            hGatewayResponse.Add("ACK", paypalResponse.Ack.ToString());

            response.AdditionalInfo = hGatewayResponse;

            return(response);
        }
示例#9
0
        /// <summary>
        /// Authorizes the payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        /// <param name="authorizeOnly">A value indicating whether to authorize only; true - authorize; false - sale</param>
        protected void AuthorizeOrSale(PaymentInfo paymentInfo, Customer customer,
                                       Guid orderGuid, ProcessPaymentResult processPaymentResult, bool authorizeOnly)
        {
            InitSettings();

            DoDirectPaymentReq req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = this.APIVersion;
            DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = NopContext.Current.UserHostAddress;
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = paymentInfo.CreditCardNumber;
            details.CreditCard.CreditCardType    = GetPaypalCreditCardType(paymentInfo.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = paymentInfo.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = paymentInfo.CreditCardExpireYear;
            details.CreditCard.CVV2      = paymentInfo.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry  = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;

            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = paymentInfo.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = paymentInfo.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = paymentInfo.BillingAddress.City;
            if (paymentInfo.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = paymentInfo.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = paymentInfo.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = paymentInfo.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = paymentInfo.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = paymentInfo.BillingAddress.LastName;
            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve <ICurrencyService>().PrimaryStoreCurrency);
            details.PaymentDetails.Custom                = orderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";


            //ShoppingCart cart = IoC.Resolve<IShoppingCartService>().GetShoppingCartByCustomerSessionGUID(ShoppingCartTypeEnum.ShoppingCart, NopContext.Current.Session.CustomerSessionGUID);
            //PaymentDetailsItemType[] cartItems = new PaymentDetailsItemType[cart.Count];
            //for (int i = 0; i < cart.Count; i++)
            //{
            //    ShoppingCartItem item = cart[i];
            //    cartItems[i] = new PaymentDetailsItemType()
            //    {
            //        Name = item.ProductVariant.FullProductName,
            //        Number = item.ProductVariant.ProductVariantID.ToString(),
            //        Quantity = item.Quantity.ToString(),
            //        Amount = new BasicAmountType()
            //        {
            //            currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve<ICurrencyService>().PrimaryStoreCurrency),
            //            Value = (item.Quantity * item.ProductVariant.Price).ToString("N", new CultureInfo("en-us"))
            //        }
            //    };
            //};
            //details.PaymentDetails.PaymentDetailsItem = cartItems;

            //shipping
            if (paymentInfo.ShippingAddress != null)
            {
                if (paymentInfo.ShippingAddress.StateProvince != null && paymentInfo.ShippingAddress.Country != null)
                {
                    AddressType shippingAddress = new AddressType();
                    shippingAddress.Name                 = paymentInfo.ShippingAddress.FirstName + " " + paymentInfo.ShippingAddress.LastName;
                    shippingAddress.Street1              = paymentInfo.ShippingAddress.Address1;
                    shippingAddress.CityName             = paymentInfo.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = paymentInfo.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), paymentInfo.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified     = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

            string error   = string.Empty;
            bool   Success = PaypalHelper.CheckSuccess(response, out error);

            if (Success)
            {
                processPaymentResult.AVSResult = response.AVSCode;
                processPaymentResult.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    processPaymentResult.AuthorizationTransactionId     = response.TransactionID;
                    processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();

                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                }
                else
                {
                    processPaymentResult.CaptureTransactionId     = response.TransactionID;
                    processPaymentResult.CaptureTransactionResult = response.Ack.ToString();

                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                }
            }
            else
            {
                processPaymentResult.Error     = error;
                processPaymentResult.FullError = error;
            }
        }
示例#10
0
        public void ProcessDirectPayment(PayPalInformation paypalinformation)
        {
            DoDirectPaymentRequestType DoDirectPmtReqType = new DoDirectPaymentRequestType();

            DoDirectPmtReqType.DoDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();

            // Set payment action
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentAction = PaymentActionCodeType.Sale;

            // Set IP
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.IPAddress = HttpContext.Current.Request.UserHostAddress;

            // Set CreditCard info.
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard = new CreditCardDetailsType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CreditCardNumber = paypalinformation.Order.CreditCard.Number;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CreditCardType   = ( CreditCardTypeType )StringToEnum(typeof(CreditCardTypeType), paypalinformation.Order.CreditCard.CardType);

            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CVV2     = paypalinformation.Order.CreditCard.SecurityCode;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.ExpMonth = paypalinformation.Order.CreditCard.ExpMonth;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.ExpYear  = paypalinformation.Order.CreditCard.ExpYear;

            // Set the billing address
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner                          = new PayerInfoType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName                = new PersonNameType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.FirstName      = paypalinformation.Order.EndUser.FirstName;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.LastName       = paypalinformation.Order.EndUser.LastName;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address                  = new AddressType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street1          = paypalinformation.Order.CreditCard.Address.AddressLine;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street2          = paypalinformation.Order.CreditCard.Address.AddressLine2;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CityName         = paypalinformation.Order.CreditCard.Address.City;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.StateOrProvince  = paypalinformation.Order.CreditCard.Address.State;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.PostalCode       = paypalinformation.Order.CreditCard.Address.PostalCode;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CountrySpecified = true;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Country          = CountryCodeType.US;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Phone            = paypalinformation.Order.EndUser.ContactInformation.Phone;

            PaymentDetailsItemType[] itemArray = new PaymentDetailsItemType[paypalinformation.Order.OrderDetails.Products.Length];
            PaymentDetailsItemType   items     = null;

            // Loop through all items that were added to the shopping cart.
            for (int i = 0; i < paypalinformation.Order.OrderDetails.Products.Length; i++)
            {
                items                   = new PaymentDetailsItemType();
                items.Amount            = new BasicAmountType();
                items.Amount.Value      = paypalinformation.Order.OrderDetails.Products[i].Price.ToString();
                items.Amount.currencyID = CurrencyCodeType.USD;
                items.Quantity          = paypalinformation.Order.OrderDetails.Products[i].Quantity.ToString();

                //items.Tax						= new BasicAmountType();
                //items.Tax.Value				= CalculationManager.CalcSalesTax( Convert.ToDecimal( items.Amount.Value ) ).ToString();
                //items.Tax.currencyID			= CurrencyCodeType.USD;

                items.Name   = paypalinformation.Order.OrderDetails.Products[i].Name;
                items.Number = paypalinformation.Order.OrderDetails.Products[i].ProductID.ToString();

                itemArray.SetValue(items, i);
            }

            // set payment Details
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails                  = new PaymentDetailsType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.Custom           = System.DateTime.Now.ToLongTimeString();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.OrderDescription = "";

            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.PaymentDetailsItem = new PaymentDetailsItemType[itemArray.Length];
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.PaymentDetailsItem = itemArray;

            for (int ii = 0; ii < itemArray.Length; ii++)
            {
                DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.PaymentDetailsItem.SetValue(itemArray[ii], ii);
            }

            // Order summary.
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal               = new BasicAmountType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID    = CurrencyCodeType.USD;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.Value         = paypalinformation.Order.OrderTotal.ToString();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShippingTotal            = new BasicAmountType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShippingTotal.currencyID = CurrencyCodeType.USD;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShippingTotal.Value      = paypalinformation.Order.ShippingTotal.ToString();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.TaxTotal             = new BasicAmountType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.TaxTotal.currencyID  = CurrencyCodeType.USD;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.TaxTotal.Value       = paypalinformation.Order.Tax.ToString();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ItemTotal            = new BasicAmountType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ItemTotal.currencyID = CurrencyCodeType.USD;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ItemTotal.Value      = paypalinformation.Order.SubTotal.ToString();

            //set ship to address
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress                  = new AddressType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Name             = paypalinformation.Order.EndUser.FirstName + " " + paypalinformation.Order.EndUser.LastName;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Street1          = paypalinformation.Order.ShippingAddress.AddressLine;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.CityName         = paypalinformation.Order.ShippingAddress.City;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.StateOrProvince  = paypalinformation.Order.ShippingAddress.State;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.PostalCode       = paypalinformation.Order.ShippingAddress.PostalCode;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.CountrySpecified = true;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Country          = CountryCodeType.US;

            // credentials
            DoDirectPaymentReq DoDPReq = new DoDirectPaymentReq();

            DoDPReq.DoDirectPaymentRequest         = DoDirectPmtReqType;
            DoDPReq.DoDirectPaymentRequest.Version = "2.20";

            try
            {
                //make call return response
                DoDirectPaymentResponseType DPRes = new DoDirectPaymentResponseType();
                DPRes = PPInterface.DoDirectPayment(DoDPReq);
                string errors = CheckForErrors(DPRes);

                if (errors == string.Empty)
                {
                    IsSubmissionSuccess = true;
                    paypalinformation.Order.TransactionID = DPRes.TransactionID;
                }
                else
                {
                    IsSubmissionSuccess = false;
                    SubmissionError     = errors;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#11
0
        public OrderResponse PlacePayPalOrder(ref OBE_Order oOrder, string cardNumber, int year)
        {
            OrderResponse oValue = new OrderResponse();

            try
            {
                OBE_VerificationPayPal oVerificationPayPal = new OBE_VerificationPayPal();
                GetVerificationObject(ref oVerificationPayPal);
                DoDirectPaymentResponseType       oDPayment      = new DoDirectPaymentResponseType();
                GetTransactionDetailsResponseType oDTransDetails = new GetTransactionDetailsResponseType();
                PayPalAPI.PayPalAPI oPayPalAPI = new PayPalAPI.PayPalAPI(oVerificationPayPal.User, oVerificationPayPal.Password, oVerificationPayPal.Signature, oVerificationPayPal.Enviroment);


                try
                {
                    if (HttpContext.Current.Session["Language"] != null && HttpContext.Current.Session["Language"].ToString() == "FR")
                    {
                        if (HttpContext.Current.Session["WarrantyCheckout"] == null)
                        {
                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString().Replace(",", "."), ".", oOrder.CreditCard.NameOnCard, oOrder.BillingCustomer.Address.Address1, oOrder.BillingCustomer.Address.Address2, oOrder.BillingCustomer.Address.City, oOrder.BillingCustomer.Address.ProvState, oOrder.BillingCustomer.Address.POCode, oOrder.BillingCustomer.Address.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }

                        //made up address as we don't require it for warrantyCheckout process.
                        else
                        {
                            //oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString().Replace(",", "."), ".", oOrder.CreditCard.NameOnCard, "123 main st.", "123 main st.",
                            //HttpContext.Current.Session["city"].ToString(), "ON", "L8W1P1", "Canada", oOrder.CreditCard.CardType.ToString(),
                            //cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);

                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString().Replace(",", "."), ".", oOrder.CreditCard.NameOnCard, oOrder.BillingCustomer.Address.Address1, oOrder.BillingCustomer.Address.Address2,
                                                                   oOrder.BillingCustomer.Address.City, oOrder.BillingCustomer.Address.ProvState, oOrder.BillingCustomer.Address.POCode, oOrder.BillingCustomer.Address.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }
                    }
                    else
                    {
                        if (HttpContext.Current.Session["WarrantyCheckout"] == null)
                        {
                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString(), ".", oOrder.CreditCard.NameOnCard, oOrder.BillingCustomer.Address.Address1, oOrder.BillingCustomer.Address.Address2, oOrder.BillingCustomer.Address.City, oOrder.BillingCustomer.Address.ProvState, oOrder.BillingCustomer.Address.POCode, oOrder.BillingCustomer.Address.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }

                        //made up address as we don't require it for warrantyCheckout process.
                        else
                        {
                            //oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString(), ".", oOrder.CreditCard.NameOnCard, "123 main st.", "123 main st.",
                            //HttpContext.Current.Session["city"].ToString(), "ON", "L8W1P1", "Canada", oOrder.CreditCard.CardType.ToString(),
                            //cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);


                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString(), ".", oOrder.CreditCard.NameOnCard, oOrder.BillingCustomer.Address.Address1, oOrder.BillingCustomer.Address.Address2,
                                                                   oOrder.BillingCustomer.Address.City, oOrder.BillingCustomer.Address.ProvState, oOrder.BillingCustomer.Address.POCode, oOrder.BillingCustomer.Address.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);



                            HttpContext.Current.Session["WarrantyCheckout"] = null;
                        }
                    }
                    try
                    {
                        if ((oDPayment.TransactionID != null) && !string.IsNullOrEmpty(oDPayment.TransactionID))
                        {
                            oDTransDetails = oPayPalAPI.GetTransactionDetails(oDPayment.TransactionID);
                        }

                        //AddPayPalTransaction(oOrder, oDPayment, com.paypal.soap.api.PaymentActionCodeType.Sale, oVerificationPayPal, false, oDTransDetails);
                    }
                    catch (Exception ex)
                    {
                    }

                    oValue = GetPayPalReceipt(oDPayment);

                    if (oValue.ResponseCode == 0 | oValue.ResponseCode == RETURNCODE.RET_CODE_SUCCESS)
                    {
                        oValue.ResponseCode = RETURNCODE.RET_CODE_SUCCESS;
                    }
                    else
                    {
                        if (HttpContext.Current.Session["Language"] != null && HttpContext.Current.Session["Language"].ToString() == "FR")
                        {
                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString().Replace(",", "."), ".", oOrder.CreditCard.NameOnCard, oVerificationPayPal.Address1, oVerificationPayPal.Address2, oVerificationPayPal.City, oVerificationPayPal.Prov, oVerificationPayPal.POCode, oVerificationPayPal.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }
                        else
                        {
                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString(), ".", oOrder.CreditCard.NameOnCard, oVerificationPayPal.Address1, oVerificationPayPal.Address2, oVerificationPayPal.City, oVerificationPayPal.Prov, oVerificationPayPal.POCode, oVerificationPayPal.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }
                        try
                        {
                            if ((oDPayment.TransactionID != null) && !string.IsNullOrEmpty(oDPayment.TransactionID))
                            {
                                oDTransDetails = oPayPalAPI.GetTransactionDetails(oDPayment.TransactionID);
                            }

                            //AddPayPalTransaction(oOrder, oDPayment, com.paypal.soap.api.PaymentActionCodeType.Sale, oVerificationPayPal, true, oDTransDetails);
                        }
                        catch (Exception ex)
                        {
                        }


                        oValue = GetPayPalReceipt(oDPayment);

                        if (oValue.ResponseCode == 0 | oValue.ResponseCode == RETURNCODE.RET_CODE_SUCCESS)
                        {
                            oValue.ResponseCode = RETURNCODE.RET_CODE_SUCCESS;
                        }
                        else
                        {
                            oValue.ResponseCode = RETURNCODE.RET_CODE_UNKNOWN_ERROR;
                        }
                    }
                }
                catch (Exception ex)
                {
                    if ((oDPayment.TransactionID != null) && !string.IsNullOrEmpty(oDPayment.TransactionID))
                    {
                        oDTransDetails = oPayPalAPI.GetTransactionDetails(oDPayment.TransactionID);
                    }

                    //AddPayPalTransaction(oOrder, oDPayment, com.paypal.soap.api.PaymentActionCodeType.Sale, oVerificationPayPal, false, oDTransDetails);

                    oValue.ResponseCode = RETURNCODE.RET_CODE_UNKNOWN_ERROR;
                    oValue.Message      = "Unknown Verisign Error";
                }
            }
            catch (Exception ex)
            {
                oValue.ResponseCode = RETURNCODE.RET_CODE_DB_UNKNOWN_ERROR;
                oValue.Message      = "Unknown Verisign DB Error";
            }

            if (HttpContext.Current.Session["Language"] != null && HttpContext.Current.Session["Language"].ToString() == "FR")
            {
                if (oValue.Message.ToString() == "This transaction cannot be processed. Please enter a valid credit card number and type.")
                {
                    oValue.Message = "Cette transaction ne peut pas être traitée. Veuillez saisir un numéro et un type de carte de crédit valides.";
                }
            }


            return(oValue);
        }
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();



            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.SALE;
            }
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType   = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonth         = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYear          = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2             = processPaymentRequest.CreditCardCvv2;



            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency("USD");

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "GreenProPaymentButton";



            //send request
            var service = GetService();
            DoDirectPaymentResponseType response = service.DoDirectPayment(req);

            string error;
            bool   success = PaypalHelper.CheckSuccess(response, out error);

            if (success)
            {
                result.AvsResult = response.AVSCode;
                result.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    result.AuthorizationTransactionId     = response.TransactionID;
                    result.AuthorizationTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId     = response.TransactionID;
                    result.CaptureTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
            }
            else
            {
                result.AddError(error);
            }
            return(result);
        }
        public Response PerformRequest(Request request)
        {
            // Create request object
            DoDirectPaymentRequestType paypalRequest = new DoDirectPaymentRequestType();

            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            paypalRequest.DoDirectPaymentRequestDetails = requestDetails;

            // (Optional) How you want to obtain payment. It is one of the following values:
            // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            // * Sale – This is a final sale for which you are requesting payment (default).
            // Note: Order is not allowed for Direct Payment.
            requestDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), gatewaySettings.PaymentAction.ToUpper());

            // (Required) Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            requestDetails.CreditCard = creditCard;
            PayerInfoType payer = new PayerInfoType();
            // (Optional) First and last name of buyer.
            PersonNameType name = new PersonNameType();

            name.FirstName  = request.FirstName;
            name.LastName   = request.LastName;
            payer.PayerName = name;

            // (Required) Details about the owner of the credit card.
            creditCard.CardOwner = payer;

            // (Required) Credit card number.
            creditCard.CreditCardNumber = request.CardNumber;
            // (Optional) Type of credit card. For UK, only Maestro, MasterCard, Discover, and Visa are allowable. For Canada, only MasterCard and Visa are allowable and Interac debit cards are not supported. It is one of the following values:
            // * Visa
            // * MasterCard
            // * Discover
            // * Amex
            // * Maestro: See note.
            // Note: If the credit card type is Maestro, you must set currencyId to GBP. In addition, you must specify either StartMonth and StartYear or IssueNumber.
            creditCard.CreditCardType = (CreditCardTypeType)
                                        Enum.Parse(typeof(CreditCardTypeType), UpdateCreditCardType(request.CardType));
            // Card Verification Value, version 2. Your Merchant Account settings determine whether this field is required. To comply with credit card processing regulations, you must not store this value after a transaction has been completed.
            // Character length and limitations: For Visa, MasterCard, and Discover, the value is exactly 3 digits. For American Express, the value is exactly 4 digits.
            creditCard.CVV2 = request.CardCvv;
            // (Required) Credit card expiration month.
            creditCard.ExpMonth = request.ExpireDate.Month;
            // (Required) Credit card expiration year.
            creditCard.ExpYear = request.ExpireDate.Year;

            requestDetails.PaymentDetails = new PaymentDetailsType();
            // (Optional) Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
            // Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
            //requestDetails.PaymentDetails.NotifyURL = "";

            // (Optional) Buyer's shipping address information.
            AddressType billingAddr = new AddressType();

            billingAddr.Name = request.FirstName + " " + request.LastName;
            // (Required) First street address.
            billingAddr.Street1 = request.Address1;
            // (Optional) Second street address.
            billingAddr.Street2 = request.Address2;
            // (Required) Name of city.
            billingAddr.CityName = request.City;
            // (Required) State or province.
            billingAddr.StateOrProvince = request.State;
            // (Required) Country code.
            billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), request.Country);
            // (Required) U.S. ZIP code or other country-specific postal code.
            billingAddr.PostalCode = request.ZipCode;

            // (Optional) Phone number.
            billingAddr.Phone = request.Phone;

            payer.Address = billingAddr;

            AddressType shippingAddr = new AddressType();

            shippingAddr.Name            = request.ShipToFirstName + " " + request.ShipToLastName;
            shippingAddr.Street1         = request.ShipToAddress;
            shippingAddr.CityName        = request.ShipToCity;
            shippingAddr.StateOrProvince = request.ShipToState;
            shippingAddr.PostalCode      = request.ShipToZipCode;
            shippingAddr.Country         = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), request.ShipToCountry);

            requestDetails.PaymentDetails.ShipToAddress = shippingAddr;

            // (Required) The total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. This field must be set to a value greater than 0.
            // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies.
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), gatewaySettings.CurrencyCode);

            BasicAmountType paymentAmount = new BasicAmountType(currency, request.Amount.ToString("N2"));

            requestDetails.PaymentDetails.OrderTotal    = paymentAmount;
            requestDetails.PaymentDetails.ItemTotal     = new BasicAmountType(currency, Convert.ToDouble(request.SubTotal ?? "0").ToString("N2"));
            requestDetails.PaymentDetails.ShippingTotal = new BasicAmountType(currency, Convert.ToDouble(request.ShippingTotal ?? "0").ToString("N2"));
            requestDetails.PaymentDetails.TaxTotal      = new BasicAmountType(currency, Convert.ToDouble(request.Tax ?? "0").ToString("N2"));

            // add skus
            List <PaymentDetailsItemType> items = new List <PaymentDetailsItemType>();

            foreach (PaymentSku sku in request.SkuItems)
            {
                PaymentDetailsItemType item = new PaymentDetailsItemType();

                item.Amount      = new BasicAmountType(currency, (sku.InitialPrice * sku.Quantity).ToString("N2"));
                item.Quantity    = sku.Quantity;
                item.Name        = sku.Title;
                item.Number      = sku.SkuCode;
                item.Description = sku.LongDescription;

                items.Add(item);
            }

            requestDetails.PaymentDetails.PaymentDetailsItem = items;

            // Invoke the API
            DoDirectPaymentReq wrapper = new DoDirectPaymentReq();

            wrapper.DoDirectPaymentRequest = paypalRequest;
            // Create the PayPalAPIInterfaceServiceService service object to make the API call

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

            // enforce 30000 minimum for timeout specification (30 secs)
            int timeout = 30000;

            timeout = Math.Max(timeout, Convert.ToInt32(gatewaySettings.Timeout ?? "0"));

            config.Add("account0.apiUsername", gatewaySettings.User);
            config.Add("account0.apiPassword", gatewaySettings.Password);
            config.Add("account0.apiSignature", gatewaySettings.Signature);
            config.Add("account0.applicationId", gatewaySettings.AppID);
            config.Add("connectionTimeout", timeout.ToString());
            config.Add("mode", gatewaySettings.Mode);

            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config);

            // # API call
            // Invoke the DoDirectPayment method in service wrapper object
            DoDirectPaymentResponseType paypalResponse = service.DoDirectPayment(wrapper);

            // Check for API return status
            return(ParseResponse(service, paypalResponse));
        }
示例#14
0
        public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
        {
            //init result structure
            TransactionResult ret = new TransactionResult();

            //set up Request
            //instantiate DoDirectPaymentRequestType and RequestDetails objects
            DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();

            request.Version = PROCESSOR_VERSION;
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            //set payment action
            requestDetails.PaymentAction = PaymentActionCodeType.Sale;

            //set IP
            //requestDetails.IPAddress = Request.UserHostAddress;
            requestDetails.IPAddress = details[CheckoutKeys.IPAddress];

            //set CreditCard info
            CreditCardDetailsType creditCardDetails = new CreditCardDetailsType();

            requestDetails.CreditCard          = creditCardDetails;
            creditCardDetails.CreditCardNumber = details[CheckoutKeys.CardNumber];
            creditCardDetails.CreditCardType   = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), details[CheckoutKeys.CardType], true);
            creditCardDetails.CVV2             = details[CheckoutKeys.VerificationCode];
            creditCardDetails.ExpMonth         = Int32.Parse(details[CheckoutKeys.ExpireMonth]);
            creditCardDetails.ExpYear          = Int32.Parse(details[CheckoutKeys.ExpireYear]);
            // Switch/Solo
            if (creditCardDetails.CreditCardType == CreditCardTypeType.Solo ||
                creditCardDetails.CreditCardType == CreditCardTypeType.Switch)
            {
                creditCardDetails.StartMonth  = Int32.Parse(details[CheckoutKeys.StartMonth]);
                creditCardDetails.StartYear   = Int32.Parse(details[CheckoutKeys.StartYear]);
                creditCardDetails.IssueNumber = details[CheckoutKeys.IssueNumber];
            }

            //set billing address
            PayerInfoType cardOwner = new PayerInfoType();

            creditCardDetails.CardOwner   = cardOwner;
            cardOwner.PayerName           = new PersonNameType();
            cardOwner.PayerName.FirstName = details[CheckoutKeys.FirstName];
            cardOwner.PayerName.LastName  = details[CheckoutKeys.LastName];

            cardOwner.Address         = new AddressType();
            cardOwner.Address.Street1 = details[CheckoutKeys.Address];
            //??? cardOwner.Address.Street2 = "";
            cardOwner.Address.CityName         = details[CheckoutKeys.City];
            cardOwner.Address.StateOrProvince  = details[CheckoutKeys.State];
            cardOwner.Address.PostalCode       = details[CheckoutKeys.Zip];
            cardOwner.Address.CountrySpecified = true;
            cardOwner.Address.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), details[CheckoutKeys.Country], true);

            //set payment Details
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            requestDetails.PaymentDetails = paymentDetails;
            paymentDetails.OrderTotal     = new BasicAmountType();
            //TODO: Add currency support
            paymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), details[CheckoutKeys.Currency]);
            //paymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
            //No currency symbol. Decimal separator must be a period (.), and the thousands separator must be a comma (,)
            paymentDetails.OrderTotal.Value = details[CheckoutKeys.Amount];

            DoDirectPaymentReq paymentRequest = new DoDirectPaymentReq();

            paymentRequest.DoDirectPaymentRequest = request;

            //FINISH set up req
            //setup request Header, API credentials
            PayPalAPIAASoapBinding paypalInterface = new PayPalAPIAASoapBinding();
            UserIdPasswordType     user            = new UserIdPasswordType();

            //set api credentials - username, password, signature
            user.Username  = Username;
            user.Password  = Password;
            user.Signature = Signature;
            // setup service url
            paypalInterface.Url = ServiceUrl;
            paypalInterface.RequesterCredentials             = new CustomSecurityHeaderType();
            paypalInterface.RequesterCredentials.Credentials = user;

            //make call return response
            DoDirectPaymentResponseType paymentResponse = new DoDirectPaymentResponseType();

            paymentResponse = paypalInterface.DoDirectPayment(paymentRequest);
            //write response xml to the ret object
            ret.RawResponse = SerializeObject(paymentResponse);

            switch (paymentResponse.Ack)
            {
            case AckCodeType.Success:
            case AckCodeType.SuccessWithWarning:
                ret.Succeed           = true;
                ret.TransactionId     = paymentResponse.TransactionID;
                ret.TransactionStatus = TransactionStatus.Approved;
                break;

            default:                     // show errors if Ack is NOT Success
                ret.Succeed           = false;
                ret.TransactionStatus = TransactionStatus.Declined;
                if (paymentResponse.Errors != null &&
                    paymentResponse.Errors.Length > 0)
                {
                    ret.StatusCode = PayPalProKeys.ErrorPrefix + paymentResponse.Errors[0].ErrorCode;
                }
                break;
            }
            return(ret);
        }
示例#15
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoDirectPaymentRequestType        request        = new DoDirectPaymentRequestType();
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            // (Optional) How you want to obtain payment. It is one of the following values:
            // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            // * Sale – This is a final sale for which you are requesting payment (default).
            // Note: Order is not allowed for Direct Payment.
            requestDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), paymentType.SelectedValue);

            // (Required) Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            requestDetails.CreditCard = creditCard;
            PayerInfoType payer = new PayerInfoType();
            // (Optional) First and last name of buyer.
            PersonNameType name = new PersonNameType();

            name.FirstName  = firstName.Value;
            name.LastName   = lastName.Value;
            payer.PayerName = name;
            // (Required) Details about the owner of the credit card.
            creditCard.CardOwner = payer;

            // (Required) Credit card number.
            creditCard.CreditCardNumber = creditCardNumber.Value;
            // (Optional) Type of credit card. For UK, only Maestro, MasterCard, Discover, and Visa are allowable. For Canada, only MasterCard and Visa are allowable and Interac debit cards are not supported. It is one of the following values:
            // * Visa
            // * MasterCard
            // * Discover
            // * Amex
            // * Maestro: See note.
            // Note: If the credit card type is Maestro, you must set currencyId to GBP. In addition, you must specify either StartMonth and StartYear or IssueNumber.
            creditCard.CreditCardType = (CreditCardTypeType)
                                        Enum.Parse(typeof(CreditCardTypeType), creditCardType.SelectedValue);
            // Card Verification Value, version 2. Your Merchant Account settings determine whether this field is required. To comply with credit card processing regulations, you must not store this value after a transaction has been completed.
            // Character length and limitations: For Visa, MasterCard, and Discover, the value is exactly 3 digits. For American Express, the value is exactly 4 digits.
            creditCard.CVV2 = cvv2Number.Value;
            string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' });
            if (cardExpiryDetails.Length == 2)
            {
                // (Required) Credit card expiration month.
                creditCard.ExpMonth = Convert.ToInt32(cardExpiryDetails[0]);
                // (Required) Credit card expiration year.
                creditCard.ExpYear = Convert.ToInt32(cardExpiryDetails[1]);
            }

            requestDetails.PaymentDetails = new PaymentDetailsType();
            // (Optional) Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
            // Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
            requestDetails.PaymentDetails.NotifyURL = ipnNotificationUrl.Value.Trim();

            // (Optional) Buyer's shipping address information.
            AddressType billingAddr = new AddressType();

            if (firstName.Value != string.Empty && lastName.Value != string.Empty &&
                street1.Value != string.Empty && country.Value != string.Empty)
            {
                billingAddr.Name = payerName.Value;
                // (Required) First street address.
                billingAddr.Street1 = street1.Value;
                // (Optional) Second street address.
                billingAddr.Street2 = street2.Value;
                // (Required) Name of city.
                billingAddr.CityName = city.Value;
                // (Required) State or province.
                billingAddr.StateOrProvince = state.Value;
                // (Required) Country code.
                billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.Value);
                // (Required) U.S. ZIP code or other country-specific postal code.
                billingAddr.PostalCode = postalCode.Value;

                // (Optional) Phone number.
                billingAddr.Phone = phone.Value;

                payer.Address = billingAddr;
            }

            // (Required) The total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. This field must be set to a value greater than 0.
            // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies.
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            BasicAmountType paymentAmount = new BasicAmountType(currency, amount.Value);

            requestDetails.PaymentDetails.OrderTotal = paymentAmount;

            // Invoke the API
            DoDirectPaymentReq wrapper = new DoDirectPaymentReq();

            wrapper.DoDirectPaymentRequest = request;

            // Configuration map containing signature credentials and other required configuration.
            // For a full list of configuration parameters refer in wiki page
            // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]
            Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig();

            // Create the PayPalAPIInterfaceServiceService service object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);

            // # API call
            // Invoke the DoDirectPayment method in service wrapper object
            DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, response);
        }
示例#16
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoDirectPaymentRequestType        request        = new DoDirectPaymentRequestType();
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            requestDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), paymentType.SelectedValue);

            // Populate card requestDetails
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            requestDetails.CreditCard = creditCard;
            PayerInfoType  payer = new PayerInfoType();
            PersonNameType name  = new PersonNameType();

            name.FirstName       = firstName.Value;
            name.LastName        = lastName.Value;
            payer.PayerName      = name;
            creditCard.CardOwner = payer;

            creditCard.CreditCardNumber = creditCardNumber.Value;
            creditCard.CreditCardType   = (CreditCardTypeType)
                                          Enum.Parse(typeof(CreditCardTypeType), creditCardType.SelectedValue);
            creditCard.CVV2 = cvv2Number.Value;
            string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' });
            if (cardExpiryDetails.Length == 2)
            {
                creditCard.ExpMonth = Int32.Parse(cardExpiryDetails[0]);
                creditCard.ExpYear  = Int32.Parse(cardExpiryDetails[1]);
            }

            requestDetails.PaymentDetails = new PaymentDetailsType();
            AddressType billingAddr = new AddressType();

            if (firstName.Value != "" && lastName.Value != "" &&
                street1.Value != "" && country.Value != "")
            {
                billingAddr.Name            = payerName.Value;
                billingAddr.Street1         = street1.Value;
                billingAddr.Street2         = street2.Value;
                billingAddr.CityName        = city.Value;
                billingAddr.StateOrProvince = state.Value;
                billingAddr.Country         = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.Value);
                billingAddr.PostalCode      = postalCode.Value;

                //Fix for release
                billingAddr.Phone = phone.Value;

                payer.Address = billingAddr;
            }

            // Populate payment requestDetails
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            BasicAmountType paymentAmount = new BasicAmountType(currency, amount.Value);

            requestDetails.PaymentDetails.OrderTotal = paymentAmount;


            // Invoke the API
            DoDirectPaymentReq wrapper = new DoDirectPaymentReq();

            wrapper.DoDirectPaymentRequest = request;
            PayPalAPIInterfaceServiceService service  = new PayPalAPIInterfaceServiceService();
            DoDirectPaymentResponseType      response = service.DoDirectPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, response);
        }
        // # DoDirectPaymentAPIOperation
        // The MassPay API operation makes a payment to one or more PayPal account holders.
        public static DoDirectPaymentResponseType DoDirectPaymentAPIOperation(CreditCardDetailsType creditCard, string amount)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            // Create the DoDirectPaymentResponseType object
            DoDirectPaymentResponseType responseDoDirectPaymentResponseType = new DoDirectPaymentResponseType();

            try
            {
                // Create the DoDirectPaymentReq object
                DoDirectPaymentReq doDirectPayment = new DoDirectPaymentReq();
                DoDirectPaymentRequestDetailsType doDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();

                // Information about the credit card to be charged.

                doDirectPaymentRequestDetails.CreditCard = creditCard;

                // Information about the payment
                PaymentDetailsType paymentDetails = new PaymentDetailsType();

                //paymentDetails.NotifyURL = "http://IPNhost";
                BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.CAD, amount);
                paymentDetails.OrderTotal = orderTotal;
                doDirectPaymentRequestDetails.PaymentDetails = paymentDetails;

                // IP address of the buyer's browser.
                // `Note:
                // PayPal records this IP addresses as a means to detect possible fraud.`
                doDirectPaymentRequestDetails.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; //127.0.0.1";

                DoDirectPaymentRequestType doDirectPaymentRequest = new DoDirectPaymentRequestType(doDirectPaymentRequestDetails);
                doDirectPayment.DoDirectPaymentRequest = doDirectPaymentRequest;

                // Create the service wrapper object to make the API call
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

                // # API call
                // Invoke the DoDirectPayment method in service wrapper object
                responseDoDirectPaymentResponseType = service.DoDirectPayment(doDirectPayment);

                if (responseDoDirectPaymentResponseType != null)
                {
                    // Response envelope acknowledgement
                    string acknowledgement = "DoDirectPayment API Operation - ";
                    acknowledgement += responseDoDirectPaymentResponseType.Ack.ToString();
                    logger.Info(acknowledgement + "\n");
                    HttpContext.Current.Session["acknowledgement"] = acknowledgement;

                    // # Success values
                    if (responseDoDirectPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Unique identifier of the transaction
                        logger.Info("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                        HttpContext.Current.Session["acknowledgement"] = string.Concat("Transaction ID : ", responseDoDirectPaymentResponseType.TransactionID, "<br />");
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseDoDirectPaymentResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            logger.Debug("API Error Message : " + error.LongMessage);
                            HttpContext.Current.Session["acknowledgement"] = string.Concat("API Error Message : ", error.LongMessage, "<br />");
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                logger.Debug("Error Message : " + ex.Message);
                // Console.WriteLine("Error Message : " + ex.Message);
            }
            return(responseDoDirectPaymentResponseType);
        }
示例#18
0
        /// <summary>
        /// Authorizes the payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="OrderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        /// <param name="authorizeOnly">A value indicating whether to authorize only; true - authorize; false - sale</param>
        protected void AuthorizeOrSale(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid, ProcessPaymentResult processPaymentResult, bool authorizeOnly)
        {
            InitSettings();

            DoDirectPaymentReq req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = this.APIVersion;
            DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = HttpContext.Current.Request.UserHostAddress;
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = paymentInfo.CreditCardNumber;
            details.CreditCard.CreditCardType    = GetPaypalCreditCardType(paymentInfo.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = paymentInfo.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = paymentInfo.CreditCardExpireYear;
            details.CreditCard.CVV2 = paymentInfo.CreditCardCVV2;

            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);

            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = paymentInfo.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = paymentInfo.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = paymentInfo.BillingAddress.City;
            if (paymentInfo.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = paymentInfo.BillingAddress.StateProvince.Abbreviation;
            }
            details.CreditCard.CardOwner.Address.Country     = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode  = paymentInfo.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = paymentInfo.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = paymentInfo.BillingAddress.LastName;
            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(CurrencyManager.PrimaryStoreCurrency);
            details.PaymentDetails.Custom                = OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";

            DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

            string error   = string.Empty;
            bool   Success = PaypalHelper.CheckSuccess(response, out error);

            if (Success)
            {
                processPaymentResult.AuthorizationTransactionID     = response.TransactionID;
                processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();

                //TODO save AVSCode and CVVCode in datatabase
                processPaymentResult.AVSResult = response.AVSCode;
                processPaymentResult.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                }
                else
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                }
                //processPaymentResult.AuthorizationDate = response.Timestamp;
                //processPaymentResult.AuthorizationDate = DateTime.Now;
            }
            else
            {
                processPaymentResult.Error     = error;
                processPaymentResult.FullError = error;
            }
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            var settings = CommonServices.Settings.LoadSetting <PayPalDirectPaymentSettings>(processPaymentRequest.StoreId);

            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = PayPalHelper.GetApiVersion();

            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = CommonServices.WebHelper.GetCurrentIpAddress();

            if (details.IPAddress.IsEmpty())
            {
                details.IPAddress = "127.0.0.1";
            }

            if (settings.TransactMode == TransactMode.Authorize)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }

            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType    = PayPalHelper.GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2      = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry  = PayPalHelper.GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = PayPalHelper.GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = SmartStoreVersion.CurrentFullVersion;
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name                 = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1              = customer.ShippingAddress.Address1;
                    shippingAddress.CityName             = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified     = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                DoDirectPaymentResponseType response = service.DoDirectPayment(req);

                string error   = "";
                bool   success = PayPalHelper.CheckSuccess(Helper, response, out error);
                if (success)
                {
                    result.AvsResult = response.AVSCode;
                    result.AuthorizationTransactionCode = response.CVV2Code;
                    if (settings.TransactMode == TransactMode.Authorize)
                    {
                        result.AuthorizationTransactionId     = response.TransactionID;
                        result.AuthorizationTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Authorized;
                    }
                    else
                    {
                        result.CaptureTransactionId     = response.TransactionID;
                        result.CaptureTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Paid;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }
            return(result);
        }
示例#20
0
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            if (customer == null)
            {
                throw new Exception("Customer cannot be loaded");
            }

            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress();
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType    = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2      = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry  = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";
            //pass product names and totals to PayPal
            //if (_paypalDirectPaymentSettings.PassProductNamesAndTotals)
            //{
            //    //individual items
            //var cart = customer.ShoppingCartItems
            //    .Where(x=>x.ShoppingCartType == ShoppingCartType.ShoppingCart)
            //    .Where(x=>x.StoreId == processPaymentRequest.StoreId)
            //    .ToList();
            //    var cartItems = new PaymentDetailsItemType[cart.Count];
            //    for (int i = 0; i < cart.Count; i++)
            //    {
            //        var sc = cart[i];
            //        decimal taxRate = decimal.Zero;
            //        var customer = processPaymentRequest.Customer;
            //        decimal scUnitPrice = _priceCalculationService.GetUnitPrice(sc, true);
            //        decimal scSubTotal = _priceCalculationService.GetSubTotal(sc, true);
            //        decimal scUnitPriceInclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, true, customer, out taxRate);
            //        decimal scUnitPriceExclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, false, customer, out taxRate);
            //        //decimal scSubTotalInclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, true, customer, out taxRate);
            //        //decimal scSubTotalExclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, false, customer, out taxRate);
            //        cartItems[i] = new PaymentDetailsItemType()
            //        {
            //            Name = sc.ProductVariant.FullProductName,
            //            Number = sc.ProductVariant.Id.ToString(),
            //            Quantity = sc.Quantity.ToString(),
            //            Amount = new BasicAmountType()
            //            {
            //                currencyID = payPalCurrency,
            //                Value = scUnitPriceExclTax.ToString("N", new CultureInfo("en-us")),
            //            },
            //            Tax = new BasicAmountType()
            //            {
            //                currencyID = payPalCurrency,
            //                Value = (scUnitPriceInclTax - scUnitPriceExclTax).ToString("N", new CultureInfo("en-us")),
            //            },
            //        };
            //    };
            //    details.PaymentDetails.PaymentDetailsItem = cartItems;
            //    //other totals (undone)
            //    details.PaymentDetails.ItemTotal = null;
            //    details.PaymentDetails.ShippingTotal = null;
            //    details.PaymentDetails.TaxTotal = null;
            //    details.PaymentDetails.HandlingTotal = null;
            //}
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name                 = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1              = customer.ShippingAddress.Address1;
                    shippingAddress.CityName             = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified     = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            using (var service2 = new PayPalAPIAASoapBinding())
            {
                if (!_paypalDirectPaymentSettings.UseSandbox)
                {
                    service2.Url = "https://api-3t.paypal.com/2.0/";
                }
                else
                {
                    service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";
                }

                service2.RequesterCredentials                       = new CustomSecurityHeaderType();
                service2.RequesterCredentials.Credentials           = new UserIdPasswordType();
                service2.RequesterCredentials.Credentials.Username  = _paypalDirectPaymentSettings.ApiAccountName;
                service2.RequesterCredentials.Credentials.Password  = _paypalDirectPaymentSettings.ApiAccountPassword;
                service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
                service2.RequesterCredentials.Credentials.Subject   = "";

                DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

                string error   = "";
                bool   success = PaypalHelper.CheckSuccess(response, out error);
                if (success)
                {
                    result.AvsResult = response.AVSCode;
                    result.AuthorizationTransactionCode = response.CVV2Code;
                    if (authorizeOnly)
                    {
                        result.AuthorizationTransactionId     = response.TransactionID;
                        result.AuthorizationTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Authorized;
                    }
                    else
                    {
                        result.CaptureTransactionId     = response.TransactionID;
                        result.CaptureTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Paid;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }
            return(result);
        }
        private void Authorize(Transaction t)
        {
            PayPalAPI ppAPI = this.GetPaypalAPI();

            try
            {
                string OrderNumber = string.Empty;

                OrderNumber = t.MerchantInvoiceNumber;
                // Solves Duplicate Order Number Problem
                OrderNumber = OrderNumber + System.Guid.NewGuid().ToString();

                //        Dim cardType As Core.Payment.CreditCardType = Core.Payment.CreditCardType.FindByCode(data.Payment.CreditCardType)


                DoDirectPaymentResponseType authResponse = ppAPI.DoDirectPayment(String.Format("{0:N}", t.Amount),
                                                                                 t.Customer.LastName,
                                                                                 t.Customer.FirstName,
                                                                                 t.Customer.ShipLastName,
                                                                                 t.Customer.ShipFirstName,
                                                                                 t.Customer.Street,
                                                                                 "",
                                                                                 t.Customer.City,
                                                                                 t.Customer.Region,
                                                                                 t.Customer.PostalCode,
                                                                                 this.ConvertCountryName(t.Customer.Country),
                                                                                 t.Card.CardTypeName,
                                                                                 t.Card.CardNumber,
                                                                                 t.Card.SecurityCode,
                                                                                 t.Card.ExpirationMonth,
                                                                                 t.Card.ExpirationYear,
                                                                                 PaymentActionCodeType.Authorization,
                                                                                 t.Customer.IpAddress,
                                                                                 t.Customer.ShipStreet,
                                                                                 "",
                                                                                 t.Customer.ShipCity,
                                                                                 t.Customer.ShipRegion,
                                                                                 t.Customer.ShipPostalCode,
                                                                                 this.ConvertCountryName(t.Customer.ShipCountry),
                                                                                 OrderNumber);

                if (Settings.DebugMode)
                {
                    StringBuilder posted = new StringBuilder();
                    posted.Append("Amount=" + String.Format("{0:N}", t.Amount));
                    posted.Append(", LastName=" + t.Customer.LastName);
                    posted.Append(", FirstName=" + t.Customer.FirstName);
                    posted.Append(", ShipLastName=" + t.Customer.ShipLastName);
                    posted.Append(", ShipFirstName=" + t.Customer.ShipFirstName);
                    posted.Append(", Street=" + t.Customer.Street);
                    posted.Append(", City=" + t.Customer.Street);
                    posted.Append(", Region=" + t.Customer.Region);
                    posted.Append(", PostalCode=" + t.Customer.PostalCode);
                    posted.Append(", CountryName=" + this.ConvertCountryName(t.Customer.Country));
                    posted.Append(", CardTypeName=" + t.Card.CardTypeName);
                    posted.Append(", CardNumber=**********" + t.Card.CardNumberLast4Digits);
                    posted.Append(", CardExpMonth=" + t.Card.ExpirationMonth);
                    posted.Append(", CardExpYear=" + t.Card.ExpirationYear);
                    posted.Append(", OrderNumber=" + OrderNumber);

                    t.Result.Messages.Add(new Message(posted.ToString(), "DEBUG", MessageType.Information));
                }

                if ((authResponse.Ack == AckCodeType.Success) || (authResponse.Ack == AckCodeType.SuccessWithWarning))
                {
                    t.Result.ReferenceNumber = authResponse.TransactionID;
                    t.Result.Succeeded       = true;
                }
                else
                {
                    t.Result.Messages.Add(new Message("Paypal Payment Authorization Failed.", "", MessageType.Warning));
                    foreach (ErrorType ppError in authResponse.Errors)
                    {
                        t.Result.Messages.Add(new Message(ppError.LongMessage, ppError.ErrorCode, MessageType.Error));
                    }
                    t.Result.Succeeded = false;
                }
            }
            finally
            {
                ppAPI = null;
            }
        }
        ///// <summary>
        ///// Process payment
        ///// </summary>
        ///// <param name="paymentInfo">Payment info required for an order processing</param>
        ///// <param name="customer">Customer</param>
        ///// <param name="orderGuid">Unique order identifier</param>
        ///// <param name="processPaymentResult">Process payment result</param>
        //public void ProcessPayment(PaymentInfo paymentInfo, Customer customer,
        //        Guid orderGuid, ref ProcessPaymentResult processPaymentResult, bool TransactMode)
        //{
        //    if (TransactMode)
        //    {
        //        AuthorizeOrSale(paymentInfo, customer, orderGuid, processPaymentResult, true);
        //        if (!String.IsNullOrEmpty(processPaymentResult.Error))
        //            return;
        //    }
        //    else
        //    {
        //        AuthorizeOrSale(paymentInfo, customer, orderGuid, processPaymentResult, false);
        //        if (!String.IsNullOrEmpty(processPaymentResult.Error))
        //            return;
        //    }
        //}
        /// <summary>
        /// Authorizes the payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        /// <param name="authorizeOnly">A value indicating whether to authorize only; true - authorize; false - sale</param>
        //protected void AuthorizeOrSale(PaymentInfo paymentInfo, Customer customer,
        //    Guid orderGuid, ProcessPaymentResult processPaymentResult, bool authorizeOnly)
        //{
        //    //InitSettings();
        //    DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();
        //    DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();
        //    request.Version = this.APIVersion;
        //    request.DoDirectPaymentRequestDetails = details;
        //    details.IPAddress = HttpContext.Current.Request.UserHostAddress;
        //    details.MerchantSessionId = "1X911810264059026";
        //    if (authorizeOnly)
        //        details.PaymentAction = PaymentActionCodeType.Authorization;
        //    else
        //        details.PaymentAction = PaymentActionCodeType.Sale;
        //    details.CreditCard = new CreditCardDetailsType();
        //    details.CreditCard.CreditCardTypeSpecified = true;
        //    details.CreditCard.CreditCardNumber = paymentInfo.CreditCardNumber;
        //    details.CreditCard.CreditCardType = GetPaypalCreditCardType(paymentInfo.CreditCardType);
        //    details.CreditCard.CVV2 = paymentInfo.CreditCardCvv2;
        //    details.CreditCard.ExpMonth = paymentInfo.CreditCardExpireMonth;
        //    details.CreditCard.ExpYear = paymentInfo.CreditCardExpireYear;
        //    details.CreditCard.ExpMonthSpecified = true;
        //    details.CreditCard.ExpYearSpecified = true;
        //    details.CreditCard.CardOwner = new PayerInfoType();
        //    details.CreditCard.CardOwner.Payer = "";
        //    details.CreditCard.CardOwner.PayerID = "";
        //    details.CreditCard.CardOwner.PayerStatus = PayPalUserStatusCodeType.unverified;
        //    details.CreditCard.CardOwner.PayerCountry = "India";
        //    details.CreditCard.CardOwner.Address = new AddressType();
        //    details.CreditCard.CardOwner.Address.CountrySpecified = true;
        //    details.CreditCard.CardOwner.Address.Street1 = paymentInfo.BillingAddress.Address1;
        //    details.CreditCard.CardOwner.Address.Street2 = paymentInfo.BillingAddress.Address2;
        //    details.CreditCard.CardOwner.Address.CityName = paymentInfo.BillingAddress.City;
        //    if (paymentInfo.BillingAddress.StateProvince != null)
        //        details.CreditCard.CardOwner.Address.StateOrProvince = paymentInfo.BillingAddress.StateProvince.Abbreviation;
        //    else
        //        details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
        //    details.CreditCard.CardOwner.Address.PostalCode = paymentInfo.BillingAddress.ZipPostalCode;
        //    details.CreditCard.CardOwner.Address.CountryName = paymentInfo.BillingAddress.Country.Name;
        //    details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);
        //    details.CreditCard.CardOwner.Address.CountrySpecified = true;
        //    details.CreditCard.CardOwner.Payer = paymentInfo.BillingAddress.Email;
        //    details.CreditCard.CardOwner.PayerName = new PersonNameType();
        //    details.CreditCard.CardOwner.PayerName.FirstName = paymentInfo.BillingAddress.FirstName;
        //    details.CreditCard.CardOwner.PayerName.LastName = paymentInfo.BillingAddress.LastName;
        //    details.PaymentDetails = new PaymentDetailsType();
        //    details.PaymentDetails.OrderTotal = new BasicAmountType();
        //    details.PaymentDetails.OrderTotal.Value = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us"));
        //    details.PaymentDetails.OrderTotal.currencyID = PayPalHelper.GetPaypalCurrency("INR");
        //    details.PaymentDetails.Custom = orderGuid.ToString();
        //    if (paymentInfo.ShippingAddress != null)
        //    {
        //        if (paymentInfo.ShippingAddress.StateProvince != null && paymentInfo.ShippingAddress.Country != null)
        //        {
        //            AddressType shippingAddress = new AddressType();
        //            shippingAddress.Name = paymentInfo.ShippingAddress.FirstName + " " + paymentInfo.ShippingAddress.LastName;
        //            shippingAddress.Street1 = paymentInfo.ShippingAddress.Address1;
        //            shippingAddress.CityName = paymentInfo.ShippingAddress.City;
        //            shippingAddress.StateOrProvince = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
        //            shippingAddress.PostalCode = paymentInfo.ShippingAddress.ZipPostalCode;
        //            shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), paymentInfo.ShippingAddress.Country.TwoLetterIsoCode, true);
        //            shippingAddress.CountrySpecified = true;
        //            details.PaymentDetails.ShipToAddress = shippingAddress;
        //        }
        //    }
        //    DoDirectPaymentResponseType response = new DoDirectPaymentResponseType();
        //    response = (DoDirectPaymentResponseType)caller.Call("DoDirectPayment", request);
        //    string error = string.Empty;
        //    bool Success = PayPalHelper.CheckSuccess(customer.LanguageId, response, out error);
        //    if (Success)
        //    {
        //        processPaymentResult.AVSResult = response.AVSCode;
        //        processPaymentResult.AuthorizationTransactionCode = response.CVV2Code;
        //        if (authorizeOnly)
        //        {
        //            processPaymentResult.AuthorizationTransactionId = response.TransactionID;
        //            processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();
        //            processPaymentResult.PaymentStatus = "Authorized";
        //        }
        //        else
        //        {
        //            processPaymentResult.CaptureTransactionId = response.TransactionID;
        //            processPaymentResult.CaptureTransactionResult = response.Ack.ToString();
        //            processPaymentResult.PaymentStatus = "Paid";
        //        }
        //    }
        //    else
        //    {
        //        processPaymentResult.Error = error;
        //        processPaymentResult.FullError = error;
        //    }
        //}
        public string DoDirectPaymentCode(string paymentAmount, string buyerLastName, 
                string buyerFirstName, string buyerAddress1, string buyerAddress2, 
                string buyerCity, string buyerState, string buyerZipCode, 
                string creditCardType, string creditCardNumber, string CVV2, int expMonth, int expYear)
        {
            CallerServices caller = new CallerServices();

            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, and API version.
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AtP7rLd7TBR7eGbquoauyoA.T0bXAEgVPCgWRJ7.pbYP9lvnEWI2G4k6";
            profile.Environment = "sandbox";

            caller.APIProfile = profile;
            // Create the request object.
            DoDirectPaymentRequestType pp_Request = new DoDirectPaymentRequestType();
            //DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();
            pp_Request.Version = APIVersion;

            // Add request-specific fields to the request.
            // Create the request details object.
            pp_Request.DoDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();
            //details.IPAddress = HttpContext.Current.Request.UserHostAddress;
            //details.MerchantSessionId = "1X911810264059026";
            pp_Request.DoDirectPaymentRequestDetails.IPAddress = HttpContext.Current.Request.UserHostAddress;
            pp_Request.DoDirectPaymentRequestDetails.MerchantSessionId = "1X911810264059026";
            //details.PaymentAction = PaymentActionCodeType.Sale;
            pp_Request.DoDirectPaymentRequestDetails.PaymentAction = PaymentActionCodeType.Sale;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard = new CreditCardDetailsType();
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardNumber = creditCardNumber;
            switch (creditCardType)
            {
                case "Visa":
                    pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.Visa;
                    break;
                case "MasterCard":
                    pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.MasterCard;
                    break;
                case "Discover":
                    pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.Discover;
                    break;
                case "Amex":
                    pp_Request.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.Amex;
                    break;
            }
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CVV2 = CVV2;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.ExpMonth = expMonth;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.ExpMonthSpecified = true;

            pp_Request.DoDirectPaymentRequestDetails.CreditCard.ExpYear = expYear;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.ExpYearSpecified = true;

            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner = new PayerInfoType();
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Payer = "";
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerID = "";
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerStatus = PayPalUserStatusCodeType.unverified;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerCountry = CountryCodeType.US;

            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address = new AddressType();
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street1 = buyerAddress1;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street2 = buyerAddress2;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CityName = buyerCity;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.StateOrProvince = buyerState;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.PostalCode = buyerZipCode;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CountryName = "INR";
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Country = CountryCodeType.IN;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CountrySpecified = true;

            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName = new PersonNameType();
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.FirstName = buyerFirstName;
            pp_Request.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.LastName = buyerLastName;
            pp_Request.DoDirectPaymentRequestDetails.PaymentDetails = new PaymentDetailsType();
            pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal = new BasicAmountType();

            // NOTE: The only currency supported by the Direct Payment API at this time is US dollars (USD).

            pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
            pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.Value = paymentAmount;

            // Execute the API operation and obtain the response.
            DoDirectPaymentResponseType pp_response = new DoDirectPaymentResponseType();
            pp_response = (DoDirectPaymentResponseType)caller.Call("DoDirectPayment", pp_Request);

            InsPayDetails(pp_response.TransactionID);

            return pp_response.Ack.ToString();

            //InitSettings();

            //DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();
            //DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();

            //request.Version = this.APIVersion;
            //request.DoDirectPaymentRequestDetails = details;
            //details.IPAddress = HttpContext.Current.Request.UserHostAddress;
            //details.MerchantSessionId = "1X911810264059026";

            ////if (authorizeOnly)
            //details.PaymentAction = PaymentActionCodeType.Sale;
            ////else
            ////    details.PaymentAction = PaymentActionCodeType.Sale;

            //details.CreditCard = new CreditCardDetailsType();
            //details.CreditCard.CreditCardTypeSpecified = true;
            //details.CreditCard.CreditCardNumber = creditCardNumber;
            //details.CreditCard.CreditCardType = CreditCardTypeType.Visa;
            //details.CreditCard.CVV2 = CVV2;
            //details.CreditCard.ExpMonth = expMonth;
            //details.CreditCard.ExpYear = expYear;
            //details.CreditCard.ExpMonthSpecified = true;
            //details.CreditCard.ExpYearSpecified = true;
            //details.CreditCard.CardOwner = new PayerInfoType();
            //details.CreditCard.CardOwner.Payer = "";
            //details.CreditCard.CardOwner.PayerID = "";
            //details.CreditCard.CardOwner.PayerStatus = PayPalUserStatusCodeType.unverified;
            //details.CreditCard.CardOwner.PayerCountry = CountryCodeType.US;

            //details.CreditCard.CardOwner.Address = new AddressType();
            //details.CreditCard.CardOwner.Address.CountrySpecified = true;
            //details.CreditCard.CardOwner.Address.Street1 = "Test Street1";
            //details.CreditCard.CardOwner.Address.Street2 = "Test Street2";
            //details.CreditCard.CardOwner.Address.CityName = "Test City";
            ////if (paymentInfo.BillingAddress.StateProvince != null)
            ////    details.CreditCard.CardOwner.Address.StateOrProvince = paymentInfo.BillingAddress.StateProvince.Abbreviation;
            ////else
            //    details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            //    details.CreditCard.CardOwner.Address.PostalCode = "560032";
            //    details.CreditCard.CardOwner.Address.CountryName = "US";
            //    details.CreditCard.CardOwner.Address.Country = CountryCodeType.US;
            //details.CreditCard.CardOwner.Address.CountrySpecified = true;
            //details.CreditCard.CardOwner.Payer = "*****@*****.**";
            //details.CreditCard.CardOwner.PayerName = new PersonNameType();
            //details.CreditCard.CardOwner.PayerName.FirstName = buyerFirstName;
            //details.CreditCard.CardOwner.PayerName.LastName = buyerLastName;
            //details.PaymentDetails = new PaymentDetailsType();
            //details.PaymentDetails.OrderTotal = new BasicAmountType();
            //details.PaymentDetails.OrderTotal.Value = paymentAmount;
            //details.PaymentDetails.OrderTotal.currencyID = PayPalHelper.GetPaypalCurrency("US");
            //details.PaymentDetails.Custom = Guid.NewGuid().ToString();

            ////if (paymentInfo.ShippingAddress != null)
            ////{
            ////    if (paymentInfo.ShippingAddress.StateProvince != null && paymentInfo.ShippingAddress.Country != null)
            ////    {
            //        AddressType shippingAddress = new AddressType();
            //        shippingAddress.Name = "Ramesh rc";
            //        shippingAddress.Street1 = "Test street";
            //        shippingAddress.CityName = "Test City";
            //        shippingAddress.StateOrProvince = "Karnadaka";
            //        shippingAddress.PostalCode = "560032";
            //        shippingAddress.Country = CountryCodeType.US;
            //        shippingAddress.CountrySpecified = true;
            //        details.PaymentDetails.ShipToAddress = shippingAddress;
            ////    }
            ////}

            //DoDirectPaymentResponseType response = new DoDirectPaymentResponseType();
            //response = (DoDirectPaymentResponseType)caller.Call("DoDirectPayment", request);
            //return response.Ack.ToString();
        }
示例#23
0
    public PayPalReturn Pay(string orderNumber, string paymentAmount, string buyerLastName, string buyerFirstName, string buyerAddress, string buyerCity, string buyerStateOrProvince, string buyerCountryCode, string buyerCountryName, string buyerZipCode, string creditCardType, string creditCardNumber, string CVV2, string expMonth, string expYear)
    {
        //PayPal Return Structure
        PayPalReturn rv = new PayPalReturn();

        rv.IsSucess = false;

        DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

        requestDetails.CreditCard                     = new CreditCardDetailsType();
        requestDetails.CreditCard.CardOwner           = new PayerInfoType();
        requestDetails.CreditCard.CardOwner.Address   = new AddressType();
        requestDetails.PaymentDetails                 = new PaymentDetailsType();
        requestDetails.PaymentDetails.OrderTotal      = new BasicAmountType();
        requestDetails.CreditCard.CardOwner.PayerName = new PersonNameType();

        //Request
        requestDetails.PaymentAction = PaymentActionCodeType.Sale;
        requestDetails.IPAddress     = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        //Payment
        requestDetails.PaymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
        requestDetails.PaymentDetails.OrderTotal.Value      = paymentAmount;

        //Credit card
        requestDetails.CreditCard.CreditCardNumber        = creditCardNumber;
        requestDetails.CreditCard.CreditCardType          = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), creditCardType, true);
        requestDetails.CreditCard.ExpMonth                = Convert.ToInt32(expMonth);
        requestDetails.CreditCard.ExpYear                 = Convert.ToInt32(expYear);
        requestDetails.CreditCard.CVV2                    = CVV2;
        requestDetails.CreditCard.CreditCardTypeSpecified = true;
        requestDetails.CreditCard.ExpMonthSpecified       = true;
        requestDetails.CreditCard.ExpYearSpecified        = true;

        //Card Owner
        requestDetails.CreditCard.CardOwner.PayerName.FirstName      = buyerFirstName;
        requestDetails.CreditCard.CardOwner.PayerName.LastName       = buyerLastName;
        requestDetails.CreditCard.CardOwner.Address.Street1          = buyerAddress;
        requestDetails.CreditCard.CardOwner.Address.CityName         = buyerCity;
        requestDetails.CreditCard.CardOwner.Address.StateOrProvince  = buyerStateOrProvince;
        requestDetails.CreditCard.CardOwner.Address.CountryName      = buyerCountryName;
        requestDetails.CreditCard.CardOwner.Address.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), buyerCountryCode, true);
        requestDetails.CreditCard.CardOwner.Address.PostalCode       = buyerZipCode;
        requestDetails.CreditCard.CardOwner.Address.CountrySpecified = true;
        requestDetails.CreditCard.CardOwner.PayerCountry             = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), buyerCountryCode, true);
        requestDetails.CreditCard.CardOwner.PayerCountrySpecified    = true;

        DoDirectPaymentReq request = new DoDirectPaymentReq();

        request.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
        request.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = requestDetails;
        request.DoDirectPaymentRequest.Version = "51.0";

        //Headers
        CustomSecurityHeaderType headers = new CustomSecurityHeaderType();

        headers.Credentials           = new UserIdPasswordType();
        headers.Credentials.Username  = ConfigurationManager.AppSettings["PayPalAPIUsername"];
        headers.Credentials.Password  = ConfigurationManager.AppSettings["PayPalAPIPassword"];
        headers.Credentials.Signature = ConfigurationManager.AppSettings["PayPalAPISignature"];

        //Client
        PayPalAPIAASoapBinding client = new PayPalAPIAASoapBinding();

        client.RequesterCredentials = headers;
        client.Timeout = 15000;
        DoDirectPaymentResponseType response = client.DoDirectPayment(request);

        if (response.Ack == AckCodeType.Success || response.Ack == AckCodeType.SuccessWithWarning)
        {
            rv.IsSucess      = true;
            rv.TransactionID = response.TransactionID;
        }
        else
        {
            rv.ErrorMessage = response.Errors[0].LongMessage;
        }
        return(rv);
    }
示例#24
0
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            if (customer == null)
            {
                throw new Exception("Customer cannot be loaded");
            }

            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.SALE;
            }
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber       = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType         = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonth               = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYear                = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2                   = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner              = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            //billing address
            details.CreditCard.CardOwner.Address          = new AddressType();
            details.CreditCard.CardOwner.Address.Street1  = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2  = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name                 = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1              = customer.ShippingAddress.Address1;
                    shippingAddress.Street2              = customer.ShippingAddress.Address2;
                    shippingAddress.CityName             = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            var service = GetService();
            DoDirectPaymentResponseType response = service.DoDirectPayment(req);

            string error;
            bool   success = PaypalHelper.CheckSuccess(response, out error);

            if (success)
            {
                result.AvsResult = response.AVSCode;
                result.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    result.AuthorizationTransactionId     = response.TransactionID;
                    result.AuthorizationTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId     = response.TransactionID;
                    result.CaptureTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
            }
            else
            {
                result.AddError(error);
            }
            return(result);
        }
示例#25
0
    // # DoDirectPaymentAPIOperation
    // The MassPay API operation makes a payment to one or more PayPal account holders.
    public DoDirectPaymentResponseType DoDirectPaymentAPIOperation()
    {
        // Create the DoDirectPaymentResponseType object
        DoDirectPaymentResponseType responseDoDirectPaymentResponseType = new DoDirectPaymentResponseType();

        try
        {
            // Create the DoDirectPaymentReq object
            DoDirectPaymentReq doDirectPayment = new DoDirectPaymentReq();
            DoDirectPaymentRequestDetailsType doDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();

            // Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            // Type of credit card. For UK, only Maestro, MasterCard, Discover, and
            // Visa are allowable. For Canada, only MasterCard and Visa are
            // allowable and Interac debit cards are not supported. It is one of the
            // following values:
            //
            // * Visa
            // * MasterCard
            // * Discover
            // * Amex
            // * Solo
            // * Switch
            // * Maestro: See note.
            // `Note:
            // If the credit card type is Maestro, you must set currencyId to GBP.
            // In addition, you must specify either StartMonth and StartYear or
            // IssueNumber.`
            creditCard.CreditCardType = CreditCardTypeType.VISA;

            // Credit Card number
            creditCard.CreditCardNumber = "4770461107194023";

            // ExpiryMonth of credit card
            creditCard.ExpMonth = Convert.ToInt32("12");

            // Expiry Year of credit card
            creditCard.ExpYear = Convert.ToInt32("2021");

            //Details about the owner of the credit card.
            PayerInfoType cardOwner = new PayerInfoType();

            // Email address of buyer.
            cardOwner.Payer      = "*****@*****.**";
            creditCard.CardOwner = cardOwner;

            doDirectPaymentRequestDetails.CreditCard = creditCard;

            // Information about the payment
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            // IPN URL
            // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed
            // * The transaction related IPN variables will be received on the call back URL specified in the request
            // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"
            // * PayPal would continuously resend IPN if a wrong IPN is sent
            paymentDetails.NotifyURL = "http://IPNhost";

            // Total cost of the transaction to the buyer. If shipping cost and tax
            // charges are known, include them in this value. If not, this value
            // should be the current sub-total of the order.
            //
            // If the transaction includes one or more one-time purchases, this field must be equal to
            // the sum of the purchases. Set this field to 0 if the transaction does
            // not include a one-time purchase such as when you set up a billing
            // agreement for a recurring payment that is not immediately charged.
            // When the field is set to 0, purchase-specific fields are ignored.
            //
            // * `Currency Code` - You must set the currencyID attribute to one of the
            // 3-character currency codes for any of the supported PayPal
            // currencies.
            // * `Amount`
            BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, "4.00");
            paymentDetails.OrderTotal = orderTotal;
            doDirectPaymentRequestDetails.PaymentDetails = paymentDetails;

            // IP address of the buyer's browser.
            // `Note:
            // PayPal records this IP addresses as a means to detect possible fraud.`
            doDirectPaymentRequestDetails.IPAddress = "127.0.0.1";

            DoDirectPaymentRequestType doDirectPaymentRequest = new DoDirectPaymentRequestType(doDirectPaymentRequestDetails);
            doDirectPayment.DoDirectPaymentRequest = doDirectPaymentRequest;

            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

            // # API call
            // Invoke the DoDirectPayment method in service wrapper object
            responseDoDirectPaymentResponseType = service.DoDirectPayment(doDirectPayment);

            if (responseDoDirectPaymentResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "DoDirectPayment API Operation - ";
                acknowledgement += responseDoDirectPaymentResponseType.Ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseDoDirectPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Unique identifier of the transaction
                    logger.Info("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                    Console.WriteLine("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseDoDirectPaymentResponseType.Errors;
                    foreach (ErrorType error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.LongMessage);
                        Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                    }
                }
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return(responseDoDirectPaymentResponseType);
    }
示例#26
0
        // ProcessCard() is used for Credit Card processing via Website Payments Pro,
        // just like other credit card gateways.
        // ProcessPaypal() is used for Express Checkout and PayPal payments.
        public override string ProcessCard(int OrderNumber, int CustomerID, decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, string CardExtraCode, Address UseShippingAddress, string CAVV, string ECI, string XID, out string AVSResult, out string AuthorizationResult, out string AuthorizationCode, out string AuthorizationTransID, out string TransactionCommandOut, out string TransactionResponse)
        {
            String result = AppLogic.ro_OK;

            AuthorizationCode     = String.Empty;
            AuthorizationResult   = String.Empty;
            AuthorizationTransID  = String.Empty;
            AVSResult             = String.Empty;
            TransactionCommandOut = String.Empty;
            TransactionResponse   = String.Empty;
            try
            {
                // the request details object contains all payment details
                DoDirectPaymentRequestDetailsType RequestDetails = new DoDirectPaymentRequestDetailsType();

                // define the payment action to 'Sale'
                // (another option is 'Authorization', which would be followed later with a DoCapture API call)
                RequestDetails.PaymentAction = (PaymentActionCodeType)CommonLogic.IIF(AppLogic.TransactionModeIsAuthOnly(), (int)PaymentActionCodeType.Authorization, (int)PaymentActionCodeType.Sale);

                // define the total amount and currency for the transaction
                PaymentDetailsType PaymentDetails = new PaymentDetailsType();

                BasicAmountType totalAmount = new BasicAmountType();
                totalAmount.Value               = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
                totalAmount.currencyID          = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
                PaymentDetails.OrderTotal       = totalAmount;
                PaymentDetails.InvoiceID        = OrderNumber.ToString();
                PaymentDetails.ButtonSource     = PayPal.BN + "_DP_US";
                PaymentDetails.OrderDescription = AppLogic.AppConfig("StoreName");

                // define the credit card to be used

                CreditCardDetailsType creditCard = new CreditCardDetailsType();
                creditCard.CreditCardNumber  = UseBillingAddress.CardNumber;
                creditCard.ExpMonth          = Localization.ParseUSInt(UseBillingAddress.CardExpirationMonth);
                creditCard.ExpYear           = Localization.ParseUSInt(UseBillingAddress.CardExpirationYear);
                creditCard.ExpMonthSpecified = true;
                creditCard.ExpYearSpecified  = true;
                creditCard.CVV2 = CardExtraCode;

                if (UseBillingAddress.CardType == "AmericanExpress")
                {
                    creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), "Amex", true);
                }
                else
                {
                    creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), UseBillingAddress.CardType, true);
                }
                creditCard.CreditCardTypeSpecified = true;

                PayerInfoType  cardHolder      = new PayerInfoType();
                PersonNameType oPersonNameType = new PersonNameType();
                oPersonNameType.FirstName  = UseBillingAddress.FirstName;
                oPersonNameType.LastName   = UseBillingAddress.LastName;
                oPersonNameType.MiddleName = String.Empty;
                oPersonNameType.Salutation = String.Empty;
                oPersonNameType.Suffix     = String.Empty;
                cardHolder.PayerName       = oPersonNameType;

                AddressType PayerAddress = new AddressType();
                PayerAddress.Street1          = UseBillingAddress.Address1;
                PayerAddress.CityName         = UseBillingAddress.City;
                PayerAddress.StateOrProvince  = UseBillingAddress.State;
                PayerAddress.PostalCode       = UseBillingAddress.Zip;
                PayerAddress.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country), true);
                PayerAddress.CountrySpecified = true;

                if (UseShippingAddress != null)
                {
                    AddressType shippingAddress = new AddressType();
                    shippingAddress.Name             = (UseShippingAddress.FirstName + " " + UseShippingAddress.LastName).Trim();
                    shippingAddress.Street1          = UseShippingAddress.Address1;
                    shippingAddress.Street2          = UseShippingAddress.Address2 + CommonLogic.IIF(UseShippingAddress.Suite != "", " Ste " + UseShippingAddress.Suite, "");
                    shippingAddress.CityName         = UseShippingAddress.City;
                    shippingAddress.StateOrProvince  = UseShippingAddress.State;
                    shippingAddress.PostalCode       = UseShippingAddress.Zip;
                    shippingAddress.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseShippingAddress.Country), true);
                    shippingAddress.CountrySpecified = true;
                    PaymentDetails.ShipToAddress     = shippingAddress;
                }

                cardHolder.Address   = PayerAddress;
                creditCard.CardOwner = cardHolder;

                RequestDetails.CreditCard     = creditCard;
                RequestDetails.PaymentDetails = PaymentDetails;
                RequestDetails.IPAddress      = CommonLogic.CustomerIpAddress();            // cart.ThisCustomer.LastIPAddress;

                if (RequestDetails.IPAddress == "::1")
                {
                    RequestDetails.IPAddress = "127.0.0.1";
                }

                // instantiate the actual request object
                PaymentRequest         = new DoDirectPaymentRequestType();
                PaymentRequest.Version = API_VER;
                PaymentRequest.DoDirectPaymentRequestDetails = RequestDetails;
                DDPReq = new DoDirectPaymentReq();
                DDPReq.DoDirectPaymentRequest = PaymentRequest;

                DoDirectPaymentResponseType responseDetails = (DoDirectPaymentResponseType)IPayPal.DoDirectPayment(DDPReq);

                //if (LogToErrorTable)
                //{
                //    PayPalController.Log(XmlCommon.SerializeObject(DDPReq, DDPReq.GetType()), "DoDirectPayment Request");
                //    PayPalController.Log(XmlCommon.SerializeObject(responseDetails, responseDetails.GetType()), "DoDirectPayment Response");
                //}

                if (responseDetails != null && responseDetails.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    AuthorizationTransID = CommonLogic.IIF(TransactionMode.ToString().ToLower() == AppLogic.ro_TXModeAuthOnly.ToLower(), "AUTH=", "CAPTURE=") + responseDetails.TransactionID.ToString();
                    AuthorizationCode    = responseDetails.CorrelationID;
                    AVSResult            = responseDetails.AVSCode;
                    result = AppLogic.ro_OK;
                    AuthorizationResult = responseDetails.Ack.ToString() + "|AVSCode=" + responseDetails.AVSCode.ToString() + "|CVV2Code=" + responseDetails.CVV2Code.ToString();
                }
                else
                {
                    if (responseDetails.Errors != null)
                    {
                        String Separator = String.Empty;
                        for (int ix = 0; ix < responseDetails.Errors.Length; ix++)
                        {
                            AuthorizationResult += Separator;
                            AuthorizationResult += responseDetails.Errors[ix].LongMessage;                            // record failed TX
                            TransactionResponse += Separator;
                            try
                            {
                                TransactionResponse += String.Format("|{0},{1},{2}|", responseDetails.Errors[ix].ShortMessage, responseDetails.Errors[ix].ErrorCode, responseDetails.Errors[ix].LongMessage);                                 // record failed TX
                            }
                            catch { }
                            Separator = ", ";
                        }
                    }
                    result = AuthorizationResult;
                    // just store something here, as there is no other way to get data out of this gateway about the failure for logging in failed transaction table
                }
            }
            catch
            {
                result = "Transaction Failed";
            }
            return(result);
        }
示例#27
0
        public Commerce.Common.Transaction DoDirectCheckout(Commerce.Common.Order order, bool AuthOnly)
        {
            PayPalSvc.DoDirectPaymentReq req = new DoDirectPaymentReq();
            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = PayPalServiceUtility.PayPalAPIVersionNumber;

            DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();

            details.CreditCard                     = new CreditCardDetailsType();
            details.CreditCard.CardOwner           = new PayerInfoType();
            details.CreditCard.CardOwner.Address   = new AddressType();
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.PaymentDetails                 = new PaymentDetailsType();

            CountryCodeType payerCountry = CountryCodeType.US;

            if (order.BillingAddress.Country != "US")
            {
                try {
                    payerCountry = (CountryCodeType)StringToEnum(typeof(CountryCodeType), order.BillingAddress.Country);
                }
                catch {
                }
            }

            details.CreditCard.CardOwner.Address.Country = payerCountry;
            details.CreditCard.CardOwner.PayerCountry    = payerCountry;

            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = order.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = order.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = order.BillingAddress.City;
            details.CreditCard.CardOwner.Address.StateOrProvince  = order.BillingAddress.StateOrRegion;
            details.CreditCard.CardOwner.Address.PostalCode       = order.BillingAddress.Zip;

            details.CreditCard.CardOwner.PayerName.FirstName = order.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = order.BillingAddress.LastName;


            //the basics
            int     roundTo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits;
            decimal dTotal  = Math.Round(order.CalculateSubTotal(), roundTo) + Math.Round(order.TaxAmount, roundTo) + Math.Round(order.ShippingAmount, roundTo);

            details.PaymentDetails.OrderTotal    = GetBasicAmount(dTotal);
            details.PaymentDetails.ShippingTotal = this.GetBasicAmount(Math.Round(order.ShippingAmount, roundTo));
            details.PaymentDetails.TaxTotal      = this.GetBasicAmount(Math.Round(order.TaxAmount, roundTo));
            details.PaymentDetails.Custom        = order.OrderNumber;
            details.PaymentDetails.ItemTotal     = GetBasicAmount(Math.Round(order.CalculateSubTotal(), roundTo));
            details.PaymentDetails.ButtonSource  = DP_BN_ID;



            //credit card
            details.CreditCard.CreditCardNumber = order.CreditCardNumber;
            CreditCardTypeType ccType = CreditCardTypeType.Visa;

            switch (order.CreditCardType)
            {
            case Commerce.Common.CreditCardType.MasterCard:
                ccType = CreditCardTypeType.MasterCard;
                break;

            case Commerce.Common.CreditCardType.Amex:
                ccType = CreditCardTypeType.Amex;
                break;
            }

            details.CreditCard.CreditCardType = ccType;
            details.CreditCard.ExpMonth       = Convert.ToInt16(order.CreditCardExpireMonth);
            details.CreditCard.ExpYear        = Convert.ToInt16(order.CreditCardExpireYear);
            details.CreditCard.CVV2           = order.CreditCardSecurityNumber;

            //set the IP - required
            details.IPAddress = order.UserIP;

            //set the req var to details
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;

            //sale type
            if (AuthOnly)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }

            //send the request
            DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

            string errors = this.CheckErrors(response);

            Commerce.Common.Transaction trans = new Commerce.Common.Transaction();
            trans.OrderID = order.OrderID;

            string sOut = "";

            if (errors == string.Empty)
            {
                trans.GatewayResponse   = response.Ack.ToString();
                trans.AuthorizationCode = response.TransactionID;
                trans.CVV2Code          = response.CVV2Code;
            }
            else
            {
                trans.GatewayResponse = errors;
                throw new Exception(errors);
            }
            return(trans);
        }