UNPKG

@adyen/adyen-web

Version:

[![npm](https://img.shields.io/npm/v/@adyen/adyen-web.svg)](https://www.npmjs.com/package/@adyen/adyen-web)

3 lines (2 loc) 7.11 kB
import{createElement as e}from"../../external/preact/dist/preact.js";import{UIElement as t}from"../internal/UIElement/UIElement.js";import s from"./components/ApplePayButton.js";import o from"./services/ApplePayService.js";import n from"../../utils/base64.js";import i from"./defaultProps.js";import{httpPost as r}from"../../core/Services/http.js";import{preparePaymentRequest as a}from"./utils/payment-request.js";import p from"../../core/Errors/AdyenCheckoutError.js";import{TxVariants as l}from"../tx-variants.js";import{sanitizeResponse as d,verifyPaymentDidNotFail as c}from"../internal/UIElement/utils.js";import{resolveSupportedVersion as h}from"./utils/resolve-supported-version.js";import{formatApplePayContactToAdyenAddressFormat as y}from"./utils/format-applepay-contact-to-adyen-format.js";import{mapBrands as m}from"./utils/map-adyen-brands-to-applepay-brands.js";import u from"./services/ApplePaySdkLoader.js";import{detectInIframe as P}from"../../utils/detectInIframe.js";import{AnalyticsInfoEvent as A,InfoEventType as b,UiTarget as f}from"../../core/Analytics/events/AnalyticsInfoEvent.js";function g(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}class S extends t{formatProps(e){const t=e.brands?.length?m(e.brands):e.supportedNetworks;return{...e,configuration:e.configuration,supportedNetworks:t,buttonLocale:e.buttonLocale??e.i18n?.locale,totalPriceLabel:e.totalPriceLabel||e.configuration?.merchantName,renderApplePayCodeAs:e.renderApplePayCodeAs??(P()?"window":"modal")}}formatData(){const{applePayToken:e,billingAddress:t,deliveryAddress:s}=this.state,{isExpress:o}=this.props;return{paymentMethod:{type:S.type,applePayToken:e,...o&&{subtype:"express"}},...t&&{billingAddress:t},...s&&{deliveryAddress:s}}}beforeRender(e){const t=new A({type:b.rendered,component:this.type,configData:{...e,showPayButton:this.props.showPayButton},...e?.isExpress&&{isExpress:e.isExpress},...e?.expressPage&&{expressPage:e.expressPage}});this.analytics.sendAnalytics(t)}get isValid(){return!0}async applePayCapabilities(e){const t=e||this.props.configuration.merchantId;try{return await this.sdkLoader.isSdkLoaded(),await(ApplePaySession?.applePayCapabilities(t))}catch(e){throw new p("ERROR","Apple Pay: Error when requesting applePayCapabilities()",{cause:e})}}async isAvailable(){if("https:"!==window.location.protocol)return Promise.reject(new p("IMPLEMENTATION_ERROR","Trying to start an Apple Pay session from an insecure document"));try{return await this.sdkLoader.isSdkLoaded(),ApplePaySession?.canMakePayments()?Promise.resolve():Promise.reject(new p("ERROR","Apple Pay is not available on this device"))}catch(e){return Promise.reject(new p("ERROR","Apple Pay SDK failed to load",{cause:e}))}}defineApplePayVersionNumber(){"https:"===window.location.protocol&&(this.applePayVersionNumber=this.props.version||h(14))}configureApplePayWebOptions(){if(window.ApplePayWebOptions){const{renderApplePayCodeAs:e,onApplePayCodeClose:t}=this.props;window.ApplePayWebOptions.set({renderApplePayCodeAs:e,...t&&{onApplePayCodeClose:t}})}}startSession(){const{onValidateMerchant:e,onPaymentMethodSelected:t,onShippingMethodSelected:s,onShippingContactSelected:n,onCouponCodeChanged:i}=this.props,r=a({companyName:this.props.configuration.merchantName,countryCode:this.core.options.countryCode,...this.props}),l=new o(r,{version:this.applePayVersionNumber,onError:e=>{this.handleError(new p("ERROR","ApplePay - Something went wrong on ApplePayService",{cause:e}))},onCancel:e=>{this.handleError(new p("CANCEL","ApplePay UI dismissed",{cause:e}))},onPaymentMethodSelected:t,onShippingMethodSelected:s,onShippingContactSelected:n,onCouponCodeChanged:i,onValidateMerchant:e||this.validateMerchant,onPaymentAuthorized:(e,t,s)=>{const o=y(s.payment.billingContact),n=y(s.payment.shippingContact,!0);this.setState({applePayToken:btoa(JSON.stringify(s.payment.token.paymentData)),authorizedEvent:s,...o&&{billingAddress:o},...n&&{deliveryAddress:n}}),this.handleAuthorization().then(this.makePaymentsCall).then(d).then(c).then(this.collectOrderTrackingDetailsIfNeeded).then(({paymentResponse:t,orderDetails:s})=>(e({status:ApplePaySession.STATUS_SUCCESS,...s&&{orderDetails:s}}),t)).then(e=>{this.handleResponse(e)}).catch(e=>{const s=e?.error?.applePayError;t({status:ApplePaySession.STATUS_FAILURE,errors:s?Array.isArray(s)?s:[s]:void 0});const o={...e,error:{applePayError:s}};this.handleFailedResult(o)})}});return new Promise((e,t)=>this.props.onClick(e,t)).then(()=>{l.begin()}).catch(()=>({}))}async handleAuthorization(){return new Promise((e,t)=>{this.props.onAuthorized||e();const{authorizedEvent:s,billingAddress:o,deliveryAddress:n}=this.state;this.props.onAuthorized({authorizedEvent:s,...o&&{billingAddress:o},...n&&{deliveryAddress:n}},{resolve:e,reject:t})}).catch(e=>{const t={error:{applePayError:e}};return Promise.reject(t)})}async collectOrderTrackingDetailsIfNeeded(e){return new Promise((e,t)=>{if(!this.props.onOrderTrackingRequest)return e();this.props.onOrderTrackingRequest(e,t)}).then(t=>({paymentResponse:e,...t&&{orderDetails:t}})).catch(()=>({paymentResponse:e}))}async validateMerchant(e,t){const{hostname:s}=window.location,{clientKey:o,configuration:i,loadingContext:a,initiative:p,domainName:l}=this.props,{merchantName:d,merchantId:c}=i,h={loadingContext:a,path:`v1/applePay/sessions?clientKey=${o}`},y={displayName:d,domainName:l||s,initiative:p,merchantIdentifier:c};try{const s=await r(h,y),o=n.decode(s.data);if(o.success){e(JSON.parse(o.data))}else t("Could not decode Apple Pay session")}catch(e){t("Could not get Apple Pay session")}}componentToRender(){return this.props.showPayButton?e(s,{buttonStyle:this.props.buttonColor,buttonType:this.props.buttonType,buttonLocale:this.props.buttonLocale,onClick:this.submit}):null}constructor(e,t){super(e,t),g(this,"sdkLoader",void 0),g(this,"applePayVersionNumber",void 0),g(this,"submit",()=>{if(this.props.isInstantPayment){const e=new A({component:this.type,type:b.selected,target:f.instantPaymentButton});this.submitAnalytics(e)}this.startSession()});const{isExpress:s,onShippingContactSelected:o,onShippingMethodSelected:n}=this.props;if(!1===s&&(o||n))throw new p("IMPLEMENTATION_ERROR",'ApplePay - You must set "isExpress" flag to "true" in order to use "onShippingContactSelected" and/or "onShippingMethodSelected" callbacks');this.startSession=this.startSession.bind(this),this.submit=this.submit.bind(this),this.validateMerchant=this.validateMerchant.bind(this),this.collectOrderTrackingDetailsIfNeeded=this.collectOrderTrackingDetailsIfNeeded.bind(this),this.handleAuthorization=this.handleAuthorization.bind(this),this.defineApplePayVersionNumber=this.defineApplePayVersionNumber.bind(this),this.configureApplePayWebOptions=this.configureApplePayWebOptions.bind(this),this.sdkLoader=new u({analytics:this.analytics}),this.sdkLoader.load().then(this.defineApplePayVersionNumber).then(this.configureApplePayWebOptions).catch(e=>{this.handleError(e)})}}g(S,"type",l.applepay),g(S,"defaultProps",i);export{S as default}; //# sourceMappingURL=ApplePay.js.map