首页 > 解决方案 > 如何仅在交易完成后重定向?

问题描述

在我使用贝宝签出的示例代码中,有一个重定向请求到路由purchase/complete。我想确保仅在发布请求/paypal/purchase/complete完成后才请求此路由,以便我可以orderID在服务器端获取创建并将其作为 get 参数传递给purchase/complete路由,使其类似于purchase/complete?orderId=XXXX. XXXX 这里将是收到的data.orderID

客户端:

    // Render the PayPal button into #paypal-button-container
    paypal.Buttons({

      // Set up the transaction
      createOrder: function(data, actions) {
        var payableAmount = $("#finalAmountTotalOrders").attr("amountData");
        return actions.order.create({
          purchase_units: [{
            amount: {
              value: payableAmount
            }
          }]
        });
      },

      // Finalize the transaction
      onApprove: function(data, actions) {
        return actions.order.capture().then(function(details) {
          //will redirect user to custom page change values as desired
          window.location.replace("/purchase/complete");
          // Call your server to save the transaction
          return fetch('/paypal/purchase/complete', {
            method: 'post',
            headers: {
              'content-type': 'application/json',
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            body: JSON.stringify({
              orderID: data.orderID,
              details: details

            })

          });

        });
      }


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

编辑:

我想这样做的原因是,虽然我能够创建一个订单并将其存储在我的数据库中,一旦/paypal/purchase/complete发出发布请求,我不确定什么时候我会做一些事情,比如通过电子邮件向客户和商家发送我刚刚创建的订单(数据库行)的 ID。尝试在 post 请求中执行此操作会引发错误,因此如果我可以在/purchase/complete路线上获取 ID,我可以查询数据库并获取订单详细信息并通过电子邮件发送。任何其他方法都会对我有用。

标签: javascriptphplaravellaravel-5paypal

解决方案


我发现您可以.then在第一个块之后立即链接另一个actions.order.capture().then

onApprove: function(data, actions) {
    return actions.order.capture().then(function(details) {
        //will redirect user to custom page change values as desired
        // Call your server to save the transaction
        return fetch('/paypal/purchase/complete', {
        method: 'post',
        headers: {
            'content-type': 'application/json',
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        body: JSON.stringify({
            orderID: data.orderID,
            details:details

        })

        }).then((response) => {
          window.location.replace("/purchase/complete?paypalOrderId="+data.orderID);
        });

    });
  }

推荐阅读