JavaScrip如何安全使用Payment Request API详解

更新时间:2022-10-27 09:54:51

Payment Request API提供了一个跨浏览器标准,允许您从客户那里收集付款、地址和联系信息。然后,您可以使用这些信息来处理他们的订单。

它还促进了浏览器和网站之间交换这些信息。这背后的基本思想是通过让用户轻松在浏览器中存储付款和联系信息来改善用户的在线购物体验。

Payment Request API浏览器支持

Payment Request API仍在积极开发中,仅受现代浏览器的最后几个版本的支持。

在开始提出付款请求之前,您应该进行功能检测,以确保浏览器支持API:

if (window.PaymentRequest) {
  // Yes, we can use the API
} else {
  // No, fallback to the checkout page
  window.location.href = '/checkout'
}

请注意,您只能在超过https服务的网站上使用# Payment Request API。

现在让我们看看这个有用的API是如何工作的。

如何创建PaymentRequest对象

付款请求始终通过使用PaymentRequest()构造函数创建PaymentRequest的新对象来启动。构造函数接受两个强制性参数和一个可选参数:

  • paymentMethods定义接受哪种付款方式。例如,您只能接受Visa和MasterCard信用卡。
  • paymentDetails包含应付付款总额、税款、运费、显示项目等。
  • options是一个可选参数,用于向用户请求其他详细信息,例如姓名、电子邮件、电话等。

接下来,我们将创建一个仅包含所需参数的新付款请求。

How to use thepaymentMethodsparameter

const paymentMethods = [  {supportedMethods: ['basic-card']
  }
]
const paymentDetails = {
  total: {
label: 'Total Amount',
amount: {
  currency: 'USD',
  value: 8.49
}
  }
}
const paymentRequest = new PaymentRequest(paymentMethods, paymentDetails)

Notice thesupportedMethodsparameter in thepaymentMethodsobject. When it is set tobasic-card, both debit and credit cards of all networks will be accepted.

但您可以限制受支持的网络和卡片类型。例如,只有以下Visa、MasterCard和Discover信用卡被接受:

const paymentMethods = [  {supportedMethods: ['basic-card'],
data: {
  supportedNetworks: ['visa', 'mastercard', 'discover'],
  supportedTypes: ['credit']
}
  }
]
// ...

How to use thepaymentDetailsobject

传递给PaymentRequest构造函数的第二个参数是付款详细信息对象。它包含订单总数和可选的显示项目数组。total参数必须包括一个label参数和一个带有currencyvalue``amount参数。

您还可以添加其他显示项目,以提供总数的高级细分:

const paymentDetails = {
  total: {
label: 'Total Amount',
amount: {
  currency: 'USD',
  value: 8.49
}
  },
  displayItems: [
{
  label: '15% Discount',
  amount: {
currency: 'USD',
value: -1.49
  }
},
{
  label: 'Tax',
  amount: {
currency: 'USD',
value: 0.79
  }
}
  ]
}

displayItems参数并不意味着显示一长长的项目列表。由于移动设备上浏览器的支付用户界面的空间有限,您应该使用此参数仅显示顶级字段,如小计、折扣、税费、运费等。

Keep in mind that thePaymentRequestAPI does not perform any calculations. So your web application is responsible for providing the pre-calculatedtotalamount.

如何使用options参数请求更多详细信息

您可以使用第三个可选参数向用户请求其他信息,例如姓名、电子邮件地址和电话号码:

// ...
const options = {
  requestPayerName: true,
  requestPayerPhone: true,
  requestPayerEmail: true
}
const paymentRequest = new PaymentRequest(paymentMethods, paymentDetails, options)

默认情况下,所有这些值都是false的,但将它们中的任何一个值为true``options对象中将导致付款UI中的额外步骤。如果用户已经在浏览器中存储了这些详细信息,它们将被预先填充。

如何显示付款用户界面

创建PaymentRequest对象后,您必须调用show()方法向用户显示付款请求UI。

show()方法返回一个承诺,如果用户成功填写了详细信息,则该promise将使用aPaymentResponse对象解决。如果出现错误或用户关闭用户界面,则承诺将被拒绝。

// ...
const paymentRequest = new PaymentRequest(paymentMethods, paymentDetails, options)
paymentRequest
  .show()
  .then(paymentResponse => {
// close the payment UI
paymentResponse.complete().then(() => {
  // TODO: call REST API to process the payment at the backend server
  // with the data from `paymentResponse`.
})
  })
  .catch(err => {
// user closed the UI or the API threw an error
console.log('Error:', err)
  })

使用上述代码,浏览器将向用户显示付款用户界面。一旦用户填写了详细信息并单击“Pay”按钮,您将在show()承诺中收到PaymentResponse对象。

当您调用PaymentResponse.complete()方法时,付款请求UI会立即关闭。此方法返回一个新的承诺,以便您可以使用收集的信息调用后端服务器并处理付款。

如果您想在付款用户界面显示旋转器时致电后端服务器处理付款,您可以延迟调用complete())。

Let's create a mock function for payment processing with the backend server. It takespaymentResponseas a parameter and returns a promise after 1.5 seconds that resolves to aJSON object:

const processPaymentWithServer = paymentResponse => {
  return new Promise((resolve, reject) => {
setTimeout(() => {
  resolve({ status: true })
}, 1500)
  })
}
//...
paymentRequest
  .show()
  .then(paymentResponse => {
processPaymentWithServer(paymentResponse).then(data => {
  if (data.status) {
paymentResponse.complete('success')
  } else {
paymentResponse.complete('fail')
  }
})
  })
  .catch(err => {
console.log('Error:', err)
  })

在上面的示例中,浏览器支付UI将显示一个处理屏幕,直到processPaymentWithServer()方法返回的承诺得到解决。我们还使用“成功”和“失败”字符串来告诉浏览器交易结果。如果您调用complete('fail')浏览器将向用户显示错误消息。

如何取消付款请求

如果您想取消付款请求,因为没有活动或任何其他原因,您可以使用PaymentRequest.abort()方法。它立即关闭付款请求UI,并拒绝show()承诺。

// ...
setTimeout(() => {
  paymentRequest
.abort()
.then(() => {
  // aborted payment request
  console.log('Payment request aborted due to no activity.')
})
.catch(err => {
  // error while aborting
  console.log('abort() Error: ', err)
})
}, 5000)

结论

这就是JavaScript# Payment Request API快速介绍的结束。它提供了一种基于浏览器的方法来收集客户付款和联系信息,这些信息可以发送到后端服务器以处理付款。

JavaScrip