Web 接口
AddressErrors - 用于表示付款中地址的验证错误
最终完整的 AddressErrors 例子如下
源代码:
点击运行 »
<p>为我们值得的事业捐款 65 美元,我们将向您发送一份礼物,以表示感谢!</p> <button id="pay">立即捐款</button> <script> let supportedHandlers = [ { supportedMethods: "basic-card", data: { supportedNetworks: ["visa", "mastercard", "amex", "discover"], supportedTypes: ["credit", "debit"] } } ]; let defaultPaymentDetails = { total: {label: 'Donation', amount: {currency: 'USD', value: '65.00'}}, displayItems: [ { label: 'Original donation amount', amount: {currency: 'USD', value: '65.00'} } ], shippingOptions: [ { id: 'standard', label: 'Standard shipping', amount: {currency: 'USD', value: '0.00'}, selected: true } ] }; let request; function process() { let options = {requestShipping: true}; try { request = new PaymentRequest(supportedHandlers, defaultPaymentDetails, options); // 在此处添加事件监听器。 request.onshippingaddresschange = handleAddressChange; // 调用 show() 以触发浏览器的付款流程。 request.show().then(function(instrumentResponse) { // 对 UI 的响应进行处理。 console.log("得到响应!"); }) .catch(function(err) { // 对 request.show() 中的错误进行处理。 console.error(`来自 show() 的错误:${err}`); }); } catch (e) { // 捕获尝试创建 PaymentRequest 对象的所有错误。 } } function handleAddressChange(ev) { const validCountries = ["US", "CA", "GB", "JP", "CN", "MX"]; const genericAddressError = "无法运送到指定地址。请检查是否有任何错误。"; const invalidCountryError = "目前,我们只运送到美国,加拿大,英国,日本,中国和德国。"; let shippingAddress = ev.target.shippingAddress; let shippingAddressErrors = {}; let updateDetails = {}; if (!validCountries.includes(shippingAddress.country)) { ev.target.shippingOptions = []; shippingAddressErrors.country = invalidCountryError; updateDetails = { error: genericAddressError, shippingAddressErrors, ...defaultPaymentDetails }; } ev.updateWith(updateDetails); } window.addEventListener("load", function(ev) { document.getElementById("pay").addEventListener("click", process, false); }, false); </script>
运行结果:
点击运行 »