简体   繁体   English

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

[英]Paypal Payment Invalid when redirecting with javascript?

I have a problem with Paypal SDK REST, ASP.NET MVC 5 (C#) and javascript redirection. 我在使用Paypal SDK REST,ASP.NET MVC 5(C#)和javascript重定向时遇到问题。

I'm creating all the required components (ItemList, Address, Details, Amount,...) to make a Payment object for Paypal (not using credit card, so FundingInstruments are empty). 我正在创建所有必需的组件(ItemList,Address,Details,Amount等)来为Paypal创建Payment对象(不使用信用卡,因此FundingInstruments为空)。 After it is created, I use a View with a JavaScript Redirection to the URL Payment object has given to me. 创建它之后,我使用了一个具有JavaScript重定向的视图,该视图具有给我的URL Payment对象的JavaScript重定向。 But everytime I see a 'Transaction is not valid...' 但是每次我看到“交易无效...”

But, If I copy/Paste the URL (" https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token= ...") to my browser MANUALLY, it works ! 但是,如果我将URL(“ https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token= ...”)复制/粘贴到我的浏览器中,则可以正常使用! I'm going crazy... 我要疯了...

Please have you got a solution ? 请问您有解决方案吗? (Find Enclosed the c# file, the payment in json format and the small html redirection component) (找到随附的C#文件,json格式的付款和小的html重定向组件)

  1. C# Payment Class C#付款类别

using System; 使用系统; using System.Collections.Generic; 使用System.Collections.Generic; using System.Linq; 使用System.Linq; using System.Web; 使用System.Web; using PayPal; 使用贝宝; using PayPal.Api; 使用PayPal.Api; using System.Configuration; 使用System.Configuration; using System.Threading; 使用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 Redirection HTML重定向
 @{ 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 Payment JSON付款
 { "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" } ] } 

Thank you very much ! 非常感谢你 ! I'm really stuck... 我真的被卡住了...

For the record, here's how I fixed it: 作为记录,这是我修复它的方法:

Ok, that was my fault, the redirection was not what I expected to be... To correct it, don't forget to put your URL from RAZOR in RAW mode :). 好的,那是我的错,重定向不是我期望的...要更正它,请不要忘记将来自RAZOR的URL设置为RAW模式:)。

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

Anyway, thanks to the Paypal team for trying to help but too late :) 无论如何,感谢贝宝团队的帮助,但为时已晚:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM