使用javascript重定向时,Paypal付款无效?

时间:2015-07-10 13:09:31

标签: c# asp.net-mvc paypal

我在Paypal SDK REST,ASP.NET MVC 5(C#)和javascript重定向方面遇到了问题。

我正在创建所有必需的组件(ItemList,Address,Details,Amount,...)来为PayPal制作付款对象(不使用信用卡,因此FundingInstruments为空)。在创建之后,我使用带有JavaScript重定向的View到URL Payment对象给我的。但每次我看到“交易无效......”

但是,如果我手动将URL(“https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token= ...”)复制/粘贴到我的浏览器,它就可以了!我疯了......

请你有解决方案吗? (查找包含c#文件,json格式的付款和小的html重定向组件)

  1. C#Payment Class
  2.   

    使用System;       使用System.Collections.Generic;       使用System.Linq;       使用System.Web;       使用PayPal;       使用PayPal.Api;       使用System.Configuration;       使用System.Threading;

    namespace WizziqWebApp.Paypal
    {
        public class PaymentService
        {
            public enum EPaymentMethod { Paypal, CreditCard };
            public static readonly Dictionary<EPaymentMethod, string> PaymentMethods = new Dictionary<EPaymentMethod, string>() {
                { EPaymentMethod.Paypal, "paypal" },
                { EPaymentMethod.CreditCard, "credit_card" }
            };
    
            private OAuthTokenCredential _authToken;
            private APIContext _api;
    
            public Payment CreatePayment(Models.OrderModel order, EPaymentMethod paymentMethod, string cancelUrl, string returnUrl)
            {
                ItemList itemList = CreateItemList(order.shoppingCart);            
                //itemList.shipping_address = (ShippingAddress) CreateDeliveryAddress(order.fullRegisterModel);            
                Address InvoicingAddress = CreateInvoiceAddress(order.fullRegisterModel);            
                Details details = CreatePaymentDetails(order.shoppingCart);
                Amount amount = CreateAmount(order.shoppingCart, details);
    
                Payer payer = null;
                if (paymentMethod == EPaymentMethod.CreditCard)
                {
                    CreditCard creditCard = CreateCreditCard(InvoicingAddress);
                    FundingInstrument fundingInstrument = CreateCreditCardFundingInstrument(creditCard);
                    List<FundingInstrument> lst = new List<FundingInstrument>();
                    lst.Add(fundingInstrument);
                    payer = CreatePayerCreditCard(lst);
                }
                else if (paymentMethod == EPaymentMethod.Paypal)
                {
                    payer = CreatePayerPaypal();
                }
    
                var transactionList = new List<Transaction>();
                Transaction transaction = CreateTransaction(amount, itemList, order);
                transactionList.Add(transaction);
    
    
                var payment = new Payment
                {
                    transactions = transactionList,
                    intent = "sale",
                    payer = payer,
                    redirect_urls = new RedirectUrls
                    {
                        cancel_url = cancelUrl,
                        return_url = returnUrl
                    }
                };
    
                payment = payment.Create(this.Api);
    
                System.IO.File.WriteAllText(@"d:\devel\PaymentObject.json",
    
         

    payment.ConvertToJson());

                return payment;
            }
    
            public Payment ConfirmPayment(string token, string payerId)
            {
                var paymentExecution = new PaymentExecution
                {
                    payer_id = payerId
                };
    
                var payment = new Payment { id = token };
    
                return payment.Execute(this.Api, paymentExecution);
            }
    
            private ItemList CreateItemList(Models.ShoppingCart Cart)
            {
                ItemList PaypalItemList = new ItemList();
                List<Item> itms = new List<Item>();
    
                if (Cart != null)
                {
                    foreach (Models.ShoppingCartLine line in Cart.Lines)
                    {
                        Item item = new Item();
                        item.name = line.Product.ArticleId;
                        item.currency = line.Currency.ShortCode;
                        item.price = line.UnitPrice.ToString("0.00", Thread.CurrentThread.CurrentCulture);
                        item.quantity = Convert.ToString(line.Quantity);
                        item.sku = line.Product.ArticleId;
                        itms.Add(item);
                    }
                }
    
                PaypalItemList.items = itms;
                return PaypalItemList;
            }
    
            private Address CreateInvoiceAddress(Models.FullRegisterModel model)
            {
                Address Address = null;
    
                if (model != null && model.InvoicingAddress != null)
                {
                    Address = new Address();
                    Address.city = model.InvoicingAddress.City;
                    Address.country_code = model.InvoicingAddress.Country;
                    Address.line1 = model.InvoicingAddress.StreetAddress;
                    Address.postal_code = model.InvoicingAddress.ZipCode;
                    Address.state = model.InvoicingAddress.State;
                }
    
                return Address;
            }
    
            private ShippingAddress CreateDeliveryAddress(Models.FullRegisterModel model)
            {
                ShippingAddress Address = null;
    
                if (model != null && model.DeliveryAddress != null)
                {
                    Address = new ShippingAddress();
                    Address.city = model.DeliveryAddress.City;
                    Address.country_code = model.DeliveryAddress.Country;
                    Address.line1 = model.DeliveryAddress.StreetAddress;
                    Address.postal_code = model.DeliveryAddress.ZipCode;
                    Address.state = model.DeliveryAddress.State;
                    Address.recipient_name = model.LastName + ", " + model.FirstName;
                }
    
                return Address;
            }
    
            private CreditCard CreateCreditCard(Address invoiceAddress) 
            {
                CreditCard creditCard = null;
                {
                    creditCard = new CreditCard();
                    creditCard.billing_address = invoiceAddress;
                    creditCard.cvv2 = "874";  //card cvv2 number
                    creditCard.expire_month = 4; //card expire date
                    creditCard.expire_year = 2020; //card expire year
                    creditCard.first_name = "Aman";
                    creditCard.last_name = "Thakur";
                    creditCard.number = "4032034438655220"; //enter your credit card number here
                    creditCard.type = "visa"; //credit card type here paypal allows 4 types
                }
                return creditCard;
            }
    
            private Details CreatePaymentDetails(Models.ShoppingCart Cart)
            {
                Details details = null;
                if (Cart != null)
                {
                    details = new Details();
                    details.shipping = Convert.ToString(Cart.DeliveryFee.Total);
                    details.subtotal = Convert.ToString(Cart.GetTotal());
                    details.tax = "0";
                }
                return details;
            }
    
            private Amount CreateAmount(Models.ShoppingCart Cart, Details details)
            {
                var total = Cart.GetTotal() + Cart.DeliveryFee.Total + Convert.ToDecimal(details.tax);
    
                var amount = new Amount
                {
                    currency = Cart.Currency.ShortCode,
                    details = details,
                    total = total.ToString()
                };
    
                return amount;
            }
    
            private Transaction CreateTransaction(Amount amount, ItemList itemList, Models.OrderModel model)
            {
                Transaction transaction = new Transaction();
                if (amount != null && itemList != null)
                {
                    transaction.amount = amount;
                    transaction.description = "WIZZIQ products";
                    transaction.invoice_number = Convert.ToString(model.OrderNumber);
                    transaction.item_list = itemList;
                    //transaction.notify_url = "";
                    //transaction.order_url = "";
                }
                return transaction;
            }
    
            private FundingInstrument CreateCreditCardFundingInstrument(CreditCard creditCard)
            {
                return new FundingInstrument()
                {
                    credit_card = creditCard
                };
            }
    
            private Payer CreatePayerCreditCard(List<FundingInstrument> listFundingInstruments)
            {
                Payer payer = new Payer();
                if (listFundingInstruments != null)
                {
                    payer.funding_instruments = listFundingInstruments;
                    payer.payment_method = PaymentMethods[EPaymentMethod.CreditCard];
                }
                return payer;
            }
    
            private Payer CreatePayerPaypal()
            {
                Payer payer = new Payer();
                payer.payment_method = PaymentMethods[EPaymentMethod.Paypal];
                return payer;
            }
    
            private OAuthTokenCredential ApiAccessToken
            {
                get
                {
                    if (this._authToken != null)
                    {
                        return this._authToken;
                    }
    
                    var clientId = ConfigurationManager.AppSettings["clientId"];
                    var secretToken = ConfigurationManager.AppSettings["secretToken"];
                    var config = new Dictionary<string, string> { { "mode", "sandbox" } };
    
                    this._authToken = new OAuthTokenCredential(clientId, secretToken, config);
    
                    return this._authToken;
                }
            }
    
            private APIContext Api
            {
                get
                {
                    return this._api ?? (this._api = new APIContext(this.ApiAccessToken.GetAccessToken()));
                }
            }
        }
    }
    
    1. HTML重定向
    2. @{
          ViewBag.Title = "_Redirect";
          Layout = "~/Views/Shared/Layout/_LayoutEmpty.cshtml";
      }
      
      <div class="jumbotron">
          <div class="container">
              <h1>Please wait...</h1>
              <p>        
                  <div class="popover-content">                
                          <div class="loading-circle"></div>
                          <div class="loading-circle1"></div>
                          <div class="small-title clr-wizziq text-center"><span>While redirecting to Paypal...</span></div>
      
                  </div>
              </p>
          </div>
      </div>
      
      <script>
          setTimeout(function () {
              var url = '@ViewBag.RedirectUrl';
              alert('Redirect to: ' + url);
              window.location.href = url;
          }, 1000);
      </script>
      
      1. JSON付款
      2. {  
           "id":"PAY-14N977666S5313604KWP4CGQ",
           "intent":"sale",
           "payer":{  
              "payment_method":"paypal",
              "payer_info":{  
                 "shipping_address":{  
        
                 }
              }
           },
           "transactions":[  
              {  
                 "related_resources":[  
        
                 ],
                 "amount":{  
                    "currency":"EUR",
                    "total":"18033.45",
                    "details":{  
                       "subtotal":"18033.45"
                    }
                 },
                 "description":"WIZZIQ products",
                 "invoice_number":"4",
                 "item_list":{  
                    "items":[  
                       {  
                          "quantity":"1",
                          "name":"IQREPAIRKIT",
                          "price":"1500.00",
                          "currency":"EUR",
                          "sku":"IQREPAIRKIT"
                       },
                       {  
                          "quantity":"3",
                          "name":"IQBUR010",
                          "price":"9.20",
                          "currency":"EUR",
                          "sku":"IQBUR010"
                       },
                       {  
                          "quantity":"1",
                          "name":"IQBUR016",
                          "price":"9.20",
                          "currency":"EUR",
                          "sku":"IQBUR016"
                       },
                       {  
                          "quantity":"250",
                          "name":"IQREP20INJ",
                          "price":"49.90",
                          "currency":"EUR",
                          "sku":"IQREP20INJ"
                       },
                       {  
                          "quantity":"1",
                          "name":"IQPOLISH",
                          "price":"3.75",
                          "currency":"EUR",
                          "sku":"IQPOLISH"
                       },
                       {  
                          "quantity":"2",
                          "name":"IQTRANSFO",
                          "price":"8.95",
                          "currency":"EUR",
                          "sku":"IQTRANSFO"
                       },
                       {  
                          "quantity":"5",
                          "name":"IQSTARTERKIT",
                          "price":"800.00",
                          "currency":"EUR",
                          "sku":"IQSTARTERKIT"
                       }
                    ]
                 }
              }
           ],
           "state":"created",
           "create_time":"2015-07-10T12:56:58Z",
           "update_time":"2015-07-10T12:56:58Z",
           "links":[  
              {  
                 "href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-14N977666S5313604KWP4CGQ",
                 "rel":"self",
                 "method":"GET"
              },
              {  
                 "href":"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-4HC32806NW4529238",
                 "rel":"approval_url",
                 "method":"REDIRECT"
              },
              {  
                 "href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-14N977666S5313604KWP4CGQ/execute",
                 "rel":"execute",
                 "method":"POST"
              }
           ]
        }
        

        非常感谢!我真的被卡住了......

1 个答案:

答案 0 :(得分:0)

为了记录,这是我如何解决它:

好的,这是我的错,重定向不是我预期的...要纠正它,不要忘记将RAZOR的URL放在RAW模式中:)。

<script>
    setTimeout(function () {
        var url = '**@Html.Raw(Model.Url)**';
        alert('Redirect to: ' + url);
        window.location.href = url;
    }, 1000);
</script>

无论如何,感谢Paypal团队试图提供帮助但为时已晚:)