从外部api获取数据

时间:2017-02-17 08:06:36

标签: javascript jquery json ajax api

我已成功创建ajax代码以将数据发送到外部api(支付网关)。

问题是如何在付款后显示数据并显示"等待付款"显示前的按钮"谢谢你"容器?

以下是我的ajax发布数据代码:



$.ajax({
            url: 'creating_bill.php',
            data: { 
                paid_amount : JSON.stringify(jumlah_semua),
                email : emel,
                mobile : telefon,
                name : nama
            },
            type: "POST",
            dataType: "json",
            success: function (data) {
               confirm('Terima Kasih ! Sila buat pembayaran dengan segera.');
               console.log(data)               
               window.open(data.url, '_blank');
               
                 setTimeout(function()
                 {
                    window.location = 'index.html';
                 },10000);
            },
            async: false,
            error: function(data) {
                handleRequestError(data);
            }
        })   
}




以下是付款完成的api doc链接:BillPlz doc

但我不知道它是如何工作的。如何发布数据并将数据恢复到相同的ajax请求中?

基本上我的系统流程是这样的。

  1. 客户访问网站
  2. 客户添加他们想要购买的商品
  3. 客户确认该项目并决定通过支付网关付款
  4. 客户重定向到支付网关发票以支付
  5. 系统展示'等待'在等待客户完成付款时,在我的网站上留言。
  6. 客户完​​成付款后,他们将返回我的网站并查看"感谢您的付款"消息。
  7. 上面发布的代码是我用来将客户数据发布到支付网关api的代码。我现在的问题是,我怎么能表现出等待"等待客户完成付款并显示的消息"谢谢你"付款完成后的消息。

1 个答案:

答案 0 :(得分:2)

因此,您必须单独提出检查用户是否已完成支付账单的请求。基本上你创建了一个函数:

  • 发送请求以检查帐单是否已付款
  • 如果账单已付款,则会在1秒(或其他某个时间间隔)内再次自行调用
  • 如果账单已付清,则显示"谢谢你"消息并重定向到索引(或者您想要做的任何事情)

同样删除async: false可能是一个好主意,因为它会在请求运行时阻止浏览器。

您的代码应该符合以下方式:

function checkBillStatus() {
  $.ajax({
    ...
    // Compose the ajax request to check the bill status
    ...
    success: function (data) {
      // Here you need to check if the bill is paid
      if (data.isBillPaid) {
        console.log('Remove waiting for the payment message');
        console.log('Show thank you for the payment message');
        // Payment is done, redirecting to index
        setTimeout(function() {
          window.location = 'index.html';
        },10000);
      } else {
        // Repeat the request after a while
        setTimeout(checkBillStatus, 1000);
      }
    }
  });
}

$.ajax({
  ...
  success: function (data) {
    confirm('Terima Kasih ! Sila buat pembayaran dengan segera.');
    console.log('Add waiting for the payment message');
    console.log('User confirmed the payment, redirecting to gateway');
    window.open(data.url, '_blank');

    setTimeout(checkBillStatus, 1000);
  },
  async: true,
  ...
});

所以在confirm后你应该显示"等待"消息,然后代码打开网关页面并设置超时以在1秒内检查账单状态。 checkBillStatus功能本身执行账单状态检查,如果没有支付,则设置超时以在1秒内再次检查账单状态。等等,直到账单支付。如果是,它会显示“谢谢你”。消息并重定向到索引。

您必须依靠网关关闭已打开的窗口。