PaymentResponse: retry() 方法
PaymentResponse 接口的 retry() 方法允许在处理过程中发生错误后,要求用户重试付款。
这可以让您的应用能够优雅地处理诸如无效的送货地址或被拒绝的信用卡等情况。
语法
js
retry(errorFields)
参数
errorFields-
一个对象,包含以下属性
error可选-
对付款错误的通用描述,用户可以通过重试付款来尝试恢复,可能是在纠正付款信息中的错误之后。
error可以单独提供,仅提供通用的错误消息,或者与其他属性结合使用,作为概述,而其他属性的值则指导用户修正付款表单中的特定字段错误。 paymentMethod可选-
可能发生的任何特定于付款方法的错误。此对象的内容将根据所使用的付款方法而有所不同。
返回值
一个 Promise,当付款成功完成时解析。如果付款再次失败,该 Promise 将以适当的异常值拒绝。
通常,您会通过调用 show() 来使用此方法,然后进入一个循环或递归函数,该函数检查 PaymentResponse 是否有错误或其他需要重试付款请求的原因。如果需要重试,循环会调用 retry(),然后返回到循环的开始处,在响应返回时进行检查。只有当用户取消付款请求或请求成功时,循环才会退出。
请参阅下面的 示例 以获得更全面的示例,但基本概念的轮廓如下:
-
创建一个新的
PaymentRequest(newPaymentRequest()) -
显示付款请求 (
PaymentRequest.show() -
如果
show()解析,返回的PaymentResponse描述了请求的付款以及用户选择的选项。继续执行以下步骤:- 验证返回的响应;如果存在任何字段的值不可接受,请调用响应的
complete()方法,并将值设置为"fail"以表示失败。 - 如果响应的数据有效且可接受,请调用
complete("success")来完成付款并进行处理。
- 验证返回的响应;如果存在任何字段的值不可接受,请调用响应的
-
如果
show()被拒绝,则付款请求失败,通常是因为已有一个正在处理中,或者因为 用户代理不支持任何指定的付款方法,或者由于安全问题。有关show()的更多详细信息,请参阅 异常列表。调用complete("fail")来关闭付款请求。
js
async function handlePayment() {
const payRequest = new PaymentRequest(methodData, details, options);
try {
let payResponse = await payRequest.show();
while (validate(payResponse)) {
/* let the user edit the payment information,
wait until they submit */
await response.retry();
}
await payResponse.complete("success");
} catch (err) {
/* handle the exception */
}
}
示例
js
async function doPaymentRequest() {
const request = new PaymentRequest(methodData, details, options);
const response = await request.show();
await recursiveValidate(request, response);
await response.complete("success");
}
// Keep validating until the data looks good!
async function recursiveValidate(request, response) {
const promisesToFixThings = [];
const errors = await validate(request, response);
if (!errors) {
return;
}
if (errors.shippingAddress) {
// "shippingaddresschange" fired at request object
const promise = fixField(
request,
"shippingaddresschange",
shippingValidator,
);
promisesToFixThings.push(promise);
}
if (errors.payer) {
// "payerdetailchange" fired at response object
const promise = fixField(response, "payerdetailchange", payerValidator);
promisesToFixThings.push(promise);
}
await Promise.all([response.retry(errors), ...promisesToFixThings]);
await recursiveValidate(request, response);
}
function fixField(requestOrResponse, event, validator) {
return new Promise((resolve) => {
// Browser keeps calling this until promise resolves.
requestOrResponse.addEventListener(event, async function listener(ev) {
const promiseToValidate = validator(requestOrResponse);
ev.updateWith(promiseToValidate);
const errors = await promiseToValidate;
if (!errors) {
// yay! fixed!
event.removeEventListener(event, listener);
resolve();
}
});
});
}
doPaymentRequest();
规范
| 规范 |
|---|
| Payment Request API # dom-paymentresponse-retry |
浏览器兼容性
加载中…
另见
PaymentResponse接口。