当前位置: 首页 > 知识库问答 >
问题:

如何集成asp。net mvc 5与最新的贝宝结帐。NETSDKv2?

张翰海
2023-03-14

我试图在我的Asp中使用Paypal Checkout SDK V2。Net MVC 5项目与。网络框架4.7.2但是这似乎是我这边缺失或错误的东西。

我正在尝试集成Paypal Checkout sdk,并希望创建一个订单,以便某些Paypal用户可以继续付款,我只想显示一个“立即付款”按钮。

SDK链接在这里:

https://github.com/paypal/Checkout-NET-SDK

并遵循这些链接

https://developer.paypal.com/docs/checkout/reference/server-integration/get-transaction/#on-客户https://developer.paypal.com/demo/checkout/#/pattern/server

这是我尝试它的代码

C# Code


public class CheckoutController : Controller
{
   
    public ActionResult Index()
    {
        ViewBag.ClientId = PayPalClient.ClientId;
        ViewBag.CurrencyCode = "GBP"; // Get from a data store
        ViewBag.CurrencySign = "£";   // Get from a data store

        return View();
    }
    //[Route("api/paypal/checkout/order/create")]
    public async static Task<HttpResponse> createOrder()
    {
        HttpResponse response;
        // Construct a request object and set desired parameters
        // Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
        var order = new OrderRequest()
        {
            CheckoutPaymentIntent = "CAPTURE",
            PurchaseUnits = new List<PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = "USD",
                            Value = "100.00"
                        }
                    }
                },
            ApplicationContext = new ApplicationContext()
            {
                ReturnUrl = "https://www.example.com",
                CancelUrl = "https://www.example.com"
            }
        };


        // Call API with your client and get a response for your call
        var request = new OrdersCreateRequest();
        request.Prefer("return=representation");
        request.RequestBody(order);
        response = await PayPalClient.Client().Execute(request);
        var statusCode = response.StatusCode;
        Order result = response.Result<Order>();
        Console.WriteLine("Status: {0}", result.Status);
        Console.WriteLine("Order Id: {0}", result.Id);
        Console.WriteLine("Intent: {0}", result.CheckoutPaymentIntent);
        Console.WriteLine("Links:");
        foreach (LinkDescription link in result.Links)
        {
            Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
        }
        return response;
    }

    public async static Task<HttpResponse> captureOrder()
    {
        // Construct a request object and set desired parameters
        // Replace ORDER-ID with the approved order id from create order
        var request = new OrdersCaptureRequest("APPROVED-ORDER-ID");
        request.RequestBody(new OrderActionRequest());
        HttpResponse response = await PayPalClient.Client().Execute(request);
        var statusCode = response.StatusCode;
        Order result = response.Result<Order>();
        Console.WriteLine("Status: {0}", result.Status);
        Console.WriteLine("Capture Id: {0}", result.Id);
        return response;
    }

    /// <summary>
    /// This action is called when the user clicks on the PayPal button.
    /// </summary>
    /// <returns></returns>
    //[Route("api/paypal/checkout/order/create")]
    public async Task<SmartButtonHttpResponse> Create()
    {
        var request = new PayPalCheckoutSdk.Orders.OrdersCreateRequest();

        request.Prefer("return=representation");
        request.RequestBody(OrderBuilder.Build());

        // Call PayPal to set up a transaction
        var response = await PayPalClient.Client().Execute(request);

        // Create a response, with an order id.
        var result = response.Result<PayPalCheckoutSdk.Orders.Order>();
        var payPalHttpResponse = new SmartButtonHttpResponse(response)
        {
            orderID = result.Id
        };
        return payPalHttpResponse;
    }


    /// <summary>
    /// This action is called once the PayPal transaction is approved
    /// </summary>
    /// <param name="orderId"></param>
    /// <returns></returns>
    //[Route("api/paypal/checkout/order/approved/{orderId}")]
    public ActionResult Approved(string orderId)
    {
        return Json("Sucess", JsonRequestBehavior.AllowGet);
    }

    /// <summary>
    /// This action is called once the PayPal transaction is complete
    /// </summary>
    /// <param name="orderId"></param>
    /// <returns></returns>
    //[Route("api/paypal/checkout/order/complete/{orderId}")]
    public ActionResult Complete(string orderId)
    {
        // 1. Update the database.
        // 2. Complete the order process. Create and send invoices etc.
        // 3. Complete the shipping process.
        return Json("Completed", JsonRequestBehavior.AllowGet);
    }

    /// <summary>
    /// This action is called once the PayPal transaction is complete
    /// </summary>
    /// <param name="orderId"></param>
    /// <returns></returns>
    //[Route("api/paypal/checkout/order/cancel/{orderId}")]
    public ActionResult Cancel(string orderId)
    {
        // 1. Remove the orderId from the database.
        return Json("Cancel", JsonRequestBehavior.AllowGet);
    }

    /// <summary>
    /// This action is called once the PayPal transaction is complete
    /// </summary>
    /// <param name="orderId"></param>
    /// <returns></returns>
    //[Route("api/paypal/checkout/order/error/{orderId}/{error}")]
    public ActionResult Error(string orderId,
                               string error)
    {
        // Log the error.
        // Notify the user.
        string temp = System.Web.HttpUtility.UrlDecode(error);
        return Json(temp, JsonRequestBehavior.AllowGet);
    }
}

public static class OrderBuilder
{
    /// <summary>
    /// Use classes from the PayPalCheckoutSdk to build an OrderRequest
    /// </summary>
    /// <returns></returns>
    public static OrderRequest Build()
    {
        // Construct a request object and set desired parameters
        // Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
        OrderRequest order = new OrderRequest()
        {
            CheckoutPaymentIntent = "CAPTURE",
            PurchaseUnits = new List<PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = "USD",
                            Value = "100.00"
                        }
                    }
                },
            ApplicationContext = new ApplicationContext()
            {
                ReturnUrl = "https://www.example.com",
                CancelUrl = "https://www.example.com"
            }
        };


        // Call API with your client and get a response for your call
        var request = new OrdersCreateRequest();
        request.Prefer("return=representation");
        request.RequestBody(order);
        return order;
    }
}

public class PayPalClient
{

    public static string ClientId = " your client id";
    public static string Secrets = "your client secret";
    public static string SandboxClientId { get; set; } =
                         "<alert>{SandboxClientId}</alert>";
    public static string SandboxClientSecret { get; set; } =
                         "<alert>{SandboxClientSecret}</alert>";

    public static string LiveClientId { get; set; } =
                  "<alert>{PayPal LIVE Client Id}</alert>";
    public static string LiveClientSecret { get; set; } =
                  "<alert>{PayPal LIVE Client Secret}</alert>";


    public static PayPalEnvironment Environment()
    {
        //return new SandboxEnvironment("<alert>SandboxClientId</alert>",
        //                              "<alert>SandboxClientSecret</alert>");
        return new SandboxEnvironment(ClientId, Secrets);
    }
    public static PayPalCheckoutSdk.Core.PayPalHttpClient Client()
    {
        return new PayPalHttpClient(Environment());
    }

    public static PayPalCheckoutSdk.Core.PayPalHttpClient Client(string refreshToken)
    {
        return new PayPalHttpClient(Environment(), refreshToken);
    }

    public static String ObjectToJSONString(Object serializableObject)
    {
        MemoryStream memoryStream = new MemoryStream();
        var writer = JsonReaderWriterFactory.CreateJsonWriter(memoryStream,
                                                              Encoding.UTF8,
                                                              true,
                                                              true,
                                                              "  ");

        var ser = new DataContractJsonSerializer(serializableObject.GetType(),
                                             new DataContractJsonSerializerSettings
                                             {
                                                 UseSimpleDictionaryFormat = true
                                             });

        ser.WriteObject(writer,
                        serializableObject);

        memoryStream.Position = 0;
        StreamReader sr = new StreamReader(memoryStream);

        return sr.ReadToEnd();
    }
}

public class SmartButtonHttpResponse
{
    readonly PayPalCheckoutSdk.Orders.Order _result;
    public SmartButtonHttpResponse(PayPalHttp.HttpResponse httpResponse)
    {
        Headers = httpResponse.Headers;
        StatusCode = httpResponse.StatusCode;
        _result = httpResponse.Result<PayPalCheckoutSdk.Orders.Order>();
    }

    public HttpHeaders Headers { get; }
    public HttpStatusCode StatusCode { get; }

    public PayPalCheckoutSdk.Orders.Order Result()
    {
        return _result;
    }

    public string orderID { get; set; }
}





View html is

<!-- Set up a container element for the PayPal smart button -->
<div id="paypal-button-container"></div>
@section scripts
{
<script src="https://www.paypal.com/sdk/js?client-id=@ViewBag.ClientId"></script>
<script type="text/javascript">
       

        var orderId;
    function httpGet(url) {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", url, false);
        xmlHttp.send(null);
        return xmlHttp.responseText;
    }
       
    paypal.Buttons({
        // Set up the transaction
        enableStandardCardFields: true,
        createOrder: function (data, actions) {
            orderId = data.orderID;
            console.log("Start");
            console.log(data);
            console.log(actions);
            console.log("End");
            return fetch(
                '/PaypalPayments/create/', {
                method: 'post'
            }).then(function (res) {
                return res.json();
            }).then(function (data) {
                return data.orderID;
            });
        },

        // Finalise the transaction
        onApprove: function (data, actions) {
            return fetch('/PaypalPayments/approved/' + data.orderID, {
                method: 'post'
            }).then(function (res) {
                return actions.order.capture();
            }).then(function (details) {

                // (Preferred) Notify the server that the transaction id complete
                // and have an option to display an order completed screen.
                window.location.replace('/PaypalPayments/complete/' +
                                         data.orderID + '/@ViewBag.CurrencyCode');

                // OR
                // Notify the server that the transaction id complete
                //httpGet('/api/paypal/checkout/order/complete/' + data.orderID);

                // Show a success message to the buyer
                alert('Transaction completed by ' + details.payer.name.given_name + '!');
            });
        },

        // Buyer cancelled the payment
        onCancel: function (data, actions) {
            httpGet('/PaypalPayments/cancel/' + data.orderID);
        },

        // An error occurred during the transaction
        onError: function (err) {
            debugger;
            fetch(
                '/PaypalPayments/error/', {
                    method: 'post',
                    headers: { 'Content-type': 'application/json' },
                    body: JSON.stringify({ orderId: orderId, error: encodeURIComponent(err)})
            }).then(function (res) {
                return res.json();
            }).then(function (data) {
                return data.orderID;
            });           
        }

    }).render('#paypal-button-container');

</script>
}

下面给出了我必须接收的错误:我的createpost请求通过返回200状态而成功。

在这个请求之后,控件立即转到Error函数并抛出这个错误。

错误:位置0的JSON中意外的令牌P"

完整的错误详细信息如下所述

SyntaxError: Unexpected token P in JSON at position 0

Error: Unexpected token P in JSON at position 0
    at Qt.error (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:60544)
    at Object.<anonymous> (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:68311)
    at JSON.parse (<anonymous>)
    at o (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:68170)
    at dr (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:68323)
    at u.on (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:72994)
    at br (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:73131)
    at https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:79250
    at Function.n.try (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:14118)
    at https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:79047

Error: Unexpected token P in JSON at position 0
    at Qt.error (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:60544)
    at Array.<anonymous> (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:68311)
    at JSON.parse (<anonymous>)
    at o (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:68170)
    at dr (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:68323)
    at u.on (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:72994)
    at br (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:73131)
    at https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:79250
    at Function.n.try (https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:14118)
    at https://www.paypal.com/sdk/js?client-id=ATiT9hZAk22xK68Sg9cE3qg24jH1GP9eTm6XW2O47fPl3cligEblR35E1f24OnLg8XOmD7Y_tcnHDhPZ:2:79047

有人能正确地指导我吗?我尝试了不同的文章,但我仍然得到这些错误。

共有1个答案

农飞星
2023-03-14

当您从服务器获取/PaypalPayments/create/时,您得到了什么?

显然,您没有得到有效的JSON,但是您的代码试图将其解析为JSON。

将服务器代码更改为仅返回有效的JSON。代码实际上看起来还可以,所以客户端代码中硬编码的/PayPalPayments/create/路由可能有问题。

更改客户端代码以遵循可用的最佳示例也是明智的,该示例位于https://developer.paypal.com/demo/checkout/#/pattern/server并演示如何正确处理捕获错误

(刚刚注意到您示例中的代码使用了actions.order.capture()与此服务器端集成相结合,这非常糟糕——似乎服务器端captureOrder任务从未被调用过,这正是使用服务器端API的初衷,如果不从服务器上捕获,则不会获得任何好处)

 类似资料:
  • 我想在中集成Omnipay paypal。我经历过,但我不明白该怎么做。我没找到任何文件。我经历过这个,这个,这个。我已经使用Composer安装了它。现在我对以下问题感到困惑。 > 这里会给谁的凭据?正在购买的人或将把钱转给的人。我在哪种情况下会给别人的证书? 用户将如何进行交易?我看过它的purchase和purchasecomplete函数,但不能理解它。在正常的Paypal集成中,我们通常

  • 我创建贝宝Restapi以下步骤1.创建登录ID由developer.paypal.com2.点击我的应用程序3.点击按钮"创建应用程序"创建测试应用程序4.通过单击testapp,我得到了两个api凭据(i)测试凭据(ii)实时凭据(通过单击显示) 我的代码中存在上述api(客户端ID和密码)的问题,代码给出的错误号为401或某个时间为400 我已检查“帐户资格” PayPal付款和登录与Pay

  • 我正在开发Android应用程序,我必须集成PayPal,我已经按照MPL PayPal教程在应用程序中集成PalPal。我明白了。但我的问题是 我无法创建个人和业务测试帐户,因为当我创建帐户时,它会询问我帐户详细信息。 我住在非美国国家。 我跟着沙箱TestAccount做帐号。 如果我在这一点上忽略了信用卡信息,那么在下一步我必须添加它。

  • 我对Paypal express结账有点困惑,是否有可能为通过信用卡付款而没有账单协议的买家进行参考付款(我们禁用账单协议,因为如果启用,Paypal会要求创建新帐户)。 我知道在payment Pro中,我们可以在没有任何账单协议的情况下进行参考支付,因为它仅限于少数几个我们无法使用的国家。 注意:我们的商户账户已经激活,可以进行参考支付。 谢谢,阿兹

  • 我正在尝试使用我的沙盒模式通过PayPal运行付款。NET CORE 3项目。这个想法是让客户能够选择是使用他/她的PayPal账户还是信用卡付款。我正在使用PayPal-NET-SDKv2.0.0-rc2 我正在努力理解这是否是正确的运行顺序: 使用 这是正确的执行命令吗?

  • 问题内容: 有任何方法可以将用于Ruby的新Elasticsearch宝石集成到轨道中,轮胎很棒,但两个月以来就已淘汰,并由新宝石替代,但是还没有与轨道的集成功能。 所有教程都使用累了,但是现在,我们如何在Elasticsearch中使用rails? 问题答案: 还有另一个名为“ searchkick”的宝石,它将elasticsearch与Rails集成在一起: https://github.c