@adyen/adyen-web
Version:
[](https://www.npmjs.com/package/@adyen/adyen-web)
3 lines (2 loc) • 8.12 kB
JavaScript
import{createElement as e}from"../../external/preact/dist/preact.js";import{UIElement as t}from"../internal/UIElement/UIElement.js";import o from"./components/ApplePayButton.js";import n from"./services/ApplePayService.js";import s from"../../utils/base64.js";import r from"./defaultProps.js";import{httpPost as i}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 u}from"./utils/format-applepay-contact-to-adyen-format.js";import{mapBrands as y}from"./utils/map-adyen-brands-to-applepay-brands.js";import m from"./services/ApplePaySdkLoader.js";import{detectInIframe as P}from"../../utils/detectInIframe.js";import{AnalyticsInfoEvent as b,InfoEventType as f,UiTarget as A}from"../../core/Analytics/events/AnalyticsInfoEvent.js";function g(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function v(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{},n=Object.keys(o);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(o).filter(function(e){return Object.getOwnPropertyDescriptor(o,e).enumerable}))),n.forEach(function(t){g(e,t,o[t])})}return e}function w(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t.push.apply(t,o)}return t}(Object(t)).forEach(function(o){Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(t,o))}),e}class S extends t{formatProps(e){var t,o,n,s,r;const i=(null===(n=e.brands)||void 0===n?void 0:n.length)?y(e.brands):e.supportedNetworks;return w(v({},e),{configuration:e.configuration,supportedNetworks:i,buttonLocale:null!==(t=e.buttonLocale)&&void 0!==t?t:null===(s=e.i18n)||void 0===s?void 0:s.locale,totalPriceLabel:e.totalPriceLabel||(null===(r=e.configuration)||void 0===r?void 0:r.merchantName),renderApplePayCodeAs:null!==(o=e.renderApplePayCodeAs)&&void 0!==o?o:P()?"window":"modal"})}formatData(){const{applePayToken:e,billingAddress:t,deliveryAddress:o}=this.state,{isExpress:n}=this.props;return v({paymentMethod:v({type:S.type,applePayToken:e},n&&{subtype:"express"})},t&&{billingAddress:t},o&&{deliveryAddress:o})}beforeRender(e){const t=new b(v({type:f.rendered,component:this.type,configData:w(v({},e),{showPayButton:this.props.showPayButton})},(null==e?void 0:e.isExpress)&&{isExpress:e.isExpress},(null==e?void 0:e.expressPage)&&{expressPage:e.expressPage}));this.analytics.sendAnalytics(t)}get isValid(){return!0}async applePayCapabilities(e){const t=e||this.props.configuration.merchantId;try{var o;return await this.sdkLoader.isSdkLoaded(),await(null===(o=ApplePaySession)||void 0===o?void 0:o.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{var e;return await this.sdkLoader.isSdkLoaded(),(null===(e=ApplePaySession)||void 0===e?void 0:e.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(v({renderApplePayCodeAs:e},t&&{onApplePayCodeClose:t}))}}startSession(){const{onValidateMerchant:e,onPaymentMethodSelected:t,onShippingMethodSelected:o,onShippingContactSelected:s,onCouponCodeChanged:r}=this.props,i=a(v({companyName:this.props.configuration.merchantName,countryCode:this.core.options.countryCode},this.props)),l=new n(i,{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:o,onShippingContactSelected:s,onCouponCodeChanged:r,onValidateMerchant:e||this.validateMerchant,onPaymentAuthorized:(e,t,o)=>{const n=u(o.payment.billingContact),s=u(o.payment.shippingContact,!0);this.setState(v({applePayToken:btoa(JSON.stringify(o.payment.token.paymentData)),authorizedEvent:o},n&&{billingAddress:n},s&&{deliveryAddress:s})),this.handleAuthorization().then(this.makePaymentsCall).then(d).then(c).then(this.collectOrderTrackingDetailsIfNeeded).then(({paymentResponse:t,orderDetails:o})=>(e(v({status:ApplePaySession.STATUS_SUCCESS},o&&{orderDetails:o})),t)).then(e=>{this.handleResponse(e)}).catch(e=>{var o;const n=null==e||null===(o=e.error)||void 0===o?void 0:o.applePayError;t({status:ApplePaySession.STATUS_FAILURE,errors:n?Array.isArray(n)?n:[n]:void 0});const s=w(v({},e),{error:{applePayError:n}});this.handleFailedResult(s)})}});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:o,billingAddress:n,deliveryAddress:s}=this.state;this.props.onAuthorized(v({authorizedEvent:o},n&&{billingAddress:n},s&&{deliveryAddress:s}),{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=>v({paymentResponse:e},t&&{orderDetails:t})).catch(()=>({paymentResponse:e}))}async validateMerchant(e,t){const{hostname:o}=window.location,{clientKey:n,configuration:r,loadingContext:a,initiative:p,domainName:l}=this.props,{merchantName:d,merchantId:c}=r,h={loadingContext:a,path:`v1/applePay/sessions?clientKey=${n}`},u={displayName:d,domainName:l||o,initiative:p,merchantIdentifier:c};try{const o=await i(h,u),n=s.decode(o.data);if(n.success){e(JSON.parse(n.data))}else t("Could not decode Apple Pay session")}catch(e){t("Could not get Apple Pay session")}}componentToRender(){return this.props.showPayButton?e(o,{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 b({component:this.type,type:f.selected,target:A.instantPaymentButton});this.submitAnalytics(e)}this.startSession()});const{isExpress:o,onShippingContactSelected:n,onShippingMethodSelected:s}=this.props;if(!1===o&&(n||s))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 m({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",r);export{S as default};
//# sourceMappingURL=ApplePay.js.map