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) 6.77 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 i from"./services/ApplePayService.js";import o from"../../utils/base64.js";import r from"./defaultProps.js";import{httpPost as n}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{ANALYTICS_SELECTED_STR as h,ANALYTICS_INSTANT_PAYMENT_BUTTON as m}from"../../core/Analytics/constants.js";import{resolveSupportedVersion as y}from"./utils/resolve-supported-version.js";import{formatApplePayContactToAdyenAddressFormat as u}from"./utils/format-applepay-contact-to-adyen-format.js";import{mapBrands as P}from"./utils/map-adyen-brands-to-applepay-brands.js";import A from"./services/ApplePaySdkLoader.js";import{detectInIframe as b}from"../../utils/detectInIframe.js";function f(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}class g extends t{formatProps(e){const t=e.brands?.length?P(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??(b()?"window":"modal")}}formatData(){const{applePayToken:e,billingAddress:t,deliveryAddress:s}=this.state,{isExpress:i}=this.props;return{paymentMethod:{type:g.type,applePayToken:e,...i&&{subtype:"express"}},...t&&{billingAddress:t},...s&&{deliveryAddress:s}}}submitAnalytics(e){super.submitAnalytics({...e},this.props)}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||y(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:o}=this.props,r=a({companyName:this.props.configuration.merchantName,countryCode:this.core.options.countryCode,...this.props}),n=new i(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:o,onValidateMerchant:e||this.validateMerchant,onPaymentAuthorized:(e,t,s)=>{const i=u(s.payment.billingContact),o=u(s.payment.shippingContact,!0);this.setState({applePayToken:btoa(JSON.stringify(s.payment.token.paymentData)),authorizedEvent:s,...i&&{billingAddress:i},...o&&{deliveryAddress:o}}),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 i={...e,error:{applePayError:s}};this.handleFailedResult(i)}))}});return new Promise(((e,t)=>this.props.onClick(e,t))).then((()=>{n.begin()})).catch((()=>({})))}async handleAuthorization(){return new Promise(((e,t)=>{this.props.onAuthorized||e();const{authorizedEvent:s,billingAddress:i,deliveryAddress:o}=this.state;this.props.onAuthorized({authorizedEvent:s,...i&&{billingAddress:i},...o&&{deliveryAddress:o}},{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:i,configuration:r,loadingContext:a,initiative:p}=this.props,{merchantName:l,merchantId:d}=r,c={loadingContext:a,path:`v1/applePay/sessions?clientKey=${i}`},h={displayName:l,domainName:s,initiative:p,merchantIdentifier:d};try{const s=await n(c,h),i=o.decode(s.data);if(i.success){e(JSON.parse(i.data))}else t("Could not decode Apple Pay session")}catch(e){t("Could not get Apple Pay session")}}render(){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),f(this,"sdkLoader",void 0),f(this,"applePayVersionNumber",void 0),f(this,"submit",(()=>{this.props.isInstantPayment&&this.submitAnalytics({type:h,target:m}),this.startSession()}));const{isExpress:s,onShippingContactSelected:i,onShippingMethodSelected:o}=this.props;if(!1===s&&(i||o))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 A,this.sdkLoader.load().then(this.defineApplePayVersionNumber).then(this.configureApplePayWebOptions).catch((e=>{this.handleError(e)}))}}f(g,"type",l.applepay),f(g,"defaultProps",r);export{g as default}; //# sourceMappingURL=ApplePay.js.map