@payrails/web-sdk 1.1.6 → 1.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +14 -0
- package/index.js +1 -1
- package/package.json +2 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Payrails (https://www.payrails.com/)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Payrails Web SDK
|
|
2
|
+
|
|
3
|
+
Payrails Web provides you with the building blocks to create a checkout experience for your customers.
|
|
4
|
+
|
|
5
|
+
You can integrate Payrails Web in two ways:
|
|
6
|
+
|
|
7
|
+
- Dropin: all-in-one solution, the quickest but less customizable solution on how to accept payments on your website.
|
|
8
|
+
- Elements: One component for each payment method, credit card forms and more. Fully customizable solution.
|
|
9
|
+
|
|
10
|
+
## Importing the SDK
|
|
11
|
+
|
|
12
|
+
```JavaScript
|
|
13
|
+
npm install @payrails/web-sdk
|
|
14
|
+
```
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const DEFAULT_ELEMENT_CONFIG={table:"cards",labelStyles:{},errorTextStyles:{}};var ElementType;exports.ElementType=void 0,(ElementType=exports.ElementType||(exports.ElementType={})).CARD_NUMBER="CARD_NUMBER",ElementType.CARDHOLDER_NAME="CARDHOLDER_NAME",ElementType.CVV="CVV",ElementType.EXPIRATION_MONTH="EXPIRATION_MONTH",ElementType.EXPIRATION_YEAR="EXPIRATION_YEAR";class PayrailsElement{constructor(elementType,{id:id="",className:className=""}={}){this.subElements=[];const el=document.createElement(elementType);id&&(this.id=id,el.setAttribute("id",id)),className&&el.setAttribute("class",className),this.element=el}get parentElement(){return this.element.parentElement}mount(location){const parent=document.querySelector(location);if(!parent)throw new Error(`Element with selector "${location}" not found in in the DOM`);parent.appendChild(this.element),this.subElements.forEach((el=>{if(!this.id)throw new Error("Sub elements can not be rendered, please set id for the element");el.mount(`#${this.id}`)}))}unmount(){var _a;this.subElements.forEach((i=>i.unmount())),null===(_a=this.parentElement)||void 0===_a||_a.removeChild(this.element)}}const{CARD_NUMBER:CARD_NUMBER,CVV:CVV,CARDHOLDER_NAME:CARDHOLDER_NAME,EXPIRATION_MONTH:EXPIRATION_MONTH,EXPIRATION_YEAR:EXPIRATION_YEAR}=exports.ElementType,INPUT_STYLES={base:{border:"none",padding:"10px 16px",color:"#1d1d1d",backgroundColor:"#fff"},invalid:{backgroundColor:"#f9e1e1",borderColor:"#f25226",border:"1px solid"}},FORM_FIELDS=[{type:CARDHOLDER_NAME,placeholder:"Card holder",styles:Object.assign(Object.assign({},INPUT_STYLES),{base:Object.assign(Object.assign({},INPUT_STYLES.base),{border:"1px solid #eae8ee",padding:"10px 16px",borderTopLeftRadius:"4px",borderTopRightRadius:"4px"})})},{type:CARD_NUMBER,placeholder:"1234 1234 1234 1234",styles:Object.assign(Object.assign({},INPUT_STYLES),{base:Object.assign(Object.assign({},INPUT_STYLES.base),{border:"1px solid #eae8ee",padding:"10px 16px",borderTopLeftRadius:"4px",borderTopRightRadius:"4px",textIndent:"0"}),cardIcon:{position:"absolute",right:"8px",height:"24px",bottom:"calc(50% - 12px)"}})},{type:EXPIRATION_MONTH,placeholder:"MM",styles:Object.assign(Object.assign({},INPUT_STYLES),{base:Object.assign(Object.assign({},INPUT_STYLES.base),{borderBottom:"1px solid #eae8ee",borderLeft:"1px solid #eae8ee",borderRight:"1px solid #eae8ee",borderBottomLeftRadius:"4px"})})},{type:EXPIRATION_YEAR,placeholder:"YY",format:"YY",styles:Object.assign(Object.assign({},INPUT_STYLES),{base:Object.assign(Object.assign({},INPUT_STYLES.base),{borderBottom:"1px solid #eae8ee",borderRight:"1px solid #eae8ee"})})},{type:CVV,placeholder:"CVC",styles:Object.assign(Object.assign({},INPUT_STYLES),{base:Object.assign(Object.assign({},INPUT_STYLES.base),{borderBottom:"1px solid #eae8ee",borderRight:"1px solid #eae8ee",borderBottomRightRadius:"4px"})})}];class CardForm extends PayrailsElement{constructor(collectContainer,options){var _a,_b,_c,_d,_e,_f;super("div",{id:"payrails-card-form"}),this.collectContainer=collectContainer,this.options=options,this.storeCardCheckbox=null,this.formFields=[],FORM_FIELDS.forEach((({type:type,styles:styles,format:format,placeholder:placeholder,label:label})=>{var _a,_b,_c,_d,_e;if(!(null===(_a=this.options)||void 0===_a?void 0:_a.showCardHolderName)&&type===exports.ElementType.CARDHOLDER_NAME)return;const inputStyles=this.prepareStyles(styles,type),el=new CardField(this.collectContainer,{type:type,label:label,placeholder:(null===(_c=null===(_b=null==options?void 0:options.translations)||void 0===_b?void 0:_b.placeholders)||void 0===_c?void 0:_c[type])||placeholder,inputStyles:inputStyles,format:format,events:{onFocus:null===(_e=null===(_d=this.options)||void 0===_d?void 0:_d.events)||void 0===_e?void 0:_e.onFocus,onChange:this.onChange.bind(this)}});this.formFields.push(el)})),this.subElements.push(this.collectContainer),(null===(_a=this.options)||void 0===_a?void 0:_a.showStoreInstrumentCheckbox)&&(this.storeCardCheckbox=new StoreCardCheckbox({label:null===(_d=null===(_c=null===(_b=this.options)||void 0===_b?void 0:_b.translations)||void 0===_c?void 0:_c.labels)||void 0===_d?void 0:_d.saveCreditCard,styles:null===(_f=null===(_e=this.options)||void 0===_e?void 0:_e.styles)||void 0===_f?void 0:_f.storeCardCheckbox}),this.subElements.push(this.storeCardCheckbox))}show(){this.element.style.display="flex"}hide(){this.element.style.display="none"}prepareStyles(styles,type){var _a;let inputStyles=JSON.parse(JSON.stringify(styles));return(null===(_a=this.options)||void 0===_a?void 0:_a.showCardHolderName)&&type===exports.ElementType.CARD_NUMBER&&(this.element.setAttribute("class","with-card-holder"),inputStyles=Object.assign(Object.assign({},styles),{base:Object.assign(Object.assign({},INPUT_STYLES.base),{border:"1px solid #eae8ee",borderTop:"none",padding:"10px 16px"})})),["base","complete","empty","focus","invalid","cardIcon","copyIcon"].forEach((key=>{var _a,_b,_c,_d,_e,_f,_g;inputStyles[key]=Object.assign(Object.assign(Object.assign({},inputStyles[key]),null===(_d=null===(_c=null===(_b=null===(_a=this.options)||void 0===_a?void 0:_a.styles)||void 0===_b?void 0:_b.inputFields)||void 0===_c?void 0:_c.all)||void 0===_d?void 0:_d[key]),null===(_g=null===(_f=null===(_e=this.options)||void 0===_e?void 0:_e.styles)||void 0===_f?void 0:_f.inputFields)||void 0===_g?void 0:_g[type])})),inputStyles}get isValid(){return this.formFields.reduce(((prev,curr)=>prev&&curr.isValid),!0)}onChange(){var _a,_b,_c,_d;(null===(_b=null===(_a=this.options)||void 0===_a?void 0:_a.events)||void 0===_b?void 0:_b.onChange)&&(null===(_d=null===(_c=this.options)||void 0===_c?void 0:_c.events)||void 0===_d||_d.onChange({isValid:this.isValid}))}async collectValues(){var _a,_b;return{tokenizedCardData:await this.collectContainer.collect(),storeInstrument:(null===(_a=this.storeCardCheckbox)||void 0===_a?void 0:_a.isChecked)||(null===(_b=this.options)||void 0===_b?void 0:_b.alwaysStoreInstrument)}}}class StoreCardCheckbox extends PayrailsElement{constructor(options){super("span",{id:"payrails-store-card"});const id="payrails-store-card-checkbox",label=(null==options?void 0:options.label)||"Save credit card for future payments";this.element.innerHTML=`<label for="${id}"}"><input type="checkbox" id="${id}" name="${id}" >${label}</label>`,Object.keys((null==options?void 0:options.styles)||{}).forEach((key=>{var _a;this.element.style[key]=null===(_a=null==options?void 0:options.styles)||void 0===_a?void 0:_a[key]})),this.element.addEventListener("change",(e=>{e.stopPropagation(),e.stopImmediatePropagation()}))}get isChecked(){var _a;return null===(_a=this.element.querySelector("input"))||void 0===_a?void 0:_a.checked}}class CardField{constructor(collectContainer,options){this.isValid=!1;const{type:type,label:label,placeholder:placeholder,inputStyles:inputStyles,events:events,format:format}=options,vaultElement=collectContainer.createCollectElement({type:type,label:label,placeholder:placeholder,format:format,inputStyles:inputStyles});(null==events?void 0:events.onFocus)&&vaultElement.on("FOCUS",events.onFocus),vaultElement.on("CHANGE",(e=>{const{isEmpty:isEmpty,isValid:isValid}=e;this.isValid=!isEmpty&&isValid,(null==events?void 0:events.onChange)&&events.onChange(this)}))}}class CardList extends PayrailsElement{constructor(workflowExecution,options){super("div",{id:"payrails-card-list"}),this.workflowExecution=workflowExecution,this.listItems=[],this.workflowExecution.savedCreditCards.forEach((cardData=>{const listItem=new ListItem((()=>{(null==options?void 0:options.onCardChange)&&options.onCardChange(cardData)}),cardData);this.listItems.push(listItem),this.subElements.push(listItem)}))}reset(){this.element.querySelectorAll("input").forEach((e=>e.checked=!1))}}class ListItem extends PayrailsElement{constructor(onClick,cardData){super("div",{className:"payrails-card-list-item",id:`payrails-card-list-item-${cardData.id}`});const{id:id}=cardData,labelText=this.createCardLabel(cardData),label=document.createElement("label");label.setAttribute("for",id),label.addEventListener("click",onClick);const input=document.createElement("input");input.setAttribute("type","radio"),input.setAttribute("name","payment-option"),input.setAttribute("id",id),input.setAttribute("value",id),label.appendChild(input);const text=document.createElement("span");text.innerText=labelText,label.appendChild(text),this.element.appendChild(label)}createCardLabel({data:{suffix:suffix}}){return`****${suffix}`}}let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!getRandomValues))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}const byteToHex=[];for(let i=0;i<256;++i)byteToHex.push((i+256).toString(16).slice(1));var RequestMethod,native={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function v4(options,buf,offset){if(native.randomUUID&&!buf&&!options)return native.randomUUID();const rnds=(options=options||{}).random||(options.rng||rng)();if(rnds[6]=15&rnds[6]|64,rnds[8]=63&rnds[8]|128,buf){offset=offset||0;for(let i=0;i<16;++i)buf[offset+i]=rnds[i];return buf}return function(arr,offset=0){return(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase()}(rnds)}!function(RequestMethod){RequestMethod.GET="GET",RequestMethod.POST="POST"}(RequestMethod||(RequestMethod={}));const payrailsFetch=async({url:url,method:method=RequestMethod.GET,token:token,body:body})=>{const reqInit={method:method,headers:Object.assign(Object.assign({},getIdempotencyHeader()),getAuthorizationHeader(token))};method===RequestMethod.POST&&(reqInit.body=JSON.stringify(body||{}));const req=await fetch(url,reqInit),res=await req.json();if([401,403].includes(req.status))throw new AuthorizationError(url,method);if(!req.ok)throw new UnsuccessfulError(url,method,res);return{ok:req.ok,req:Object.assign({url:url},reqInit),res:res}};class AuthorizationError extends Error{constructor(url,method){super(`[${method}] ${url} unauthorized`)}}class UnsuccessfulError extends Error{constructor(url,method,res){super(`[${method}] ${url} unsuccessful`),this.res=res}}const getAuthorizationHeader=token=>({authorization:`Bearer ${token}`}),getIdempotencyHeader=()=>({"x-idempotency-key":v4()});class PaymentExecutor{constructor(sdkConfig,execution){this.sdkConfig=sdkConfig,this.execution=execution}async pay(paymentComposition){const executionUrl=(await this.authorize(paymentComposition)).res.links.execution;return await this.pollForAuthorizationResult(executionUrl)}async authorize(paymentComposition){if(!this.execution.authorizeLink||!this.sdkConfig.amount)throw new Error("SDK was not initialized with workflow execution");return payrailsFetch({url:this.execution.authorizeLink,method:RequestMethod.POST,token:this.sdkConfig.token,body:{amount:this.sdkConfig.amount,paymentComposition:paymentComposition,returnInfo:{success:"https://www.bootstrap.payrails.io/success"}}})}async pollForAuthorizationResult(url){const execRes=(await this.getExecution(url)).res,statuses=execRes.status,finalStatuses=["authorizePending","authorizeSuccessful","authorizeFailed"],authorizeRequestedStatus=statuses.find((({code:code})=>"authorizeRequested"===code));if(!authorizeRequestedStatus)return await new Promise((resolve=>setTimeout(resolve,300))),this.pollForAuthorizationResult(url);let finalState=statuses.find((({code:code,time:time})=>finalStatuses.includes(code)&&new Date(time)>new Date(authorizeRequestedStatus.time)));if(!finalState){const{res:res}=await this.getExecution(url,void 0,authorizeRequestedStatus.time);return finalState=res.status.find((({code:code,time:time})=>finalStatuses.includes(code)&&new Date(time)>new Date(authorizeRequestedStatus.time))),{finalState:finalState,response:res}}return{finalState:finalState,response:execRes}}async getExecution(url,currentStatuses,statusTime){const pollParams=new URLSearchParams;currentStatuses&¤tStatuses.length>0&&pollParams.append("waitWhile[status]",`[${currentStatuses.map((i=>`"${i}"`)).join(",")}]`),statusTime&&pollParams.append("waitWhile[lastStatusTime]",statusTime);const pollUrl=`${url}${pollParams.toString()?"?":""}${pollParams.toString()}`;return payrailsFetch({url:pollUrl,token:this.sdkConfig.token})}}var PAYMENT_METHOD_CODES,PAYMENT_INSTRUMENT_STATUS;!function(PAYMENT_METHOD_CODES){PAYMENT_METHOD_CODES.CARD="card",PAYMENT_METHOD_CODES.GOOGLE_PAY="googlePay"}(PAYMENT_METHOD_CODES||(PAYMENT_METHOD_CODES={})),function(PAYMENT_INSTRUMENT_STATUS){PAYMENT_INSTRUMENT_STATUS.ENABLED="enabled",PAYMENT_INSTRUMENT_STATUS.CREATED="created"}(PAYMENT_INSTRUMENT_STATUS||(PAYMENT_INSTRUMENT_STATUS={}));class WorkflowExecution{constructor(executionResponse){this.executionResponse=executionResponse}get lookup(){return this.executionResponse.initialResults.find((({body:{name:name}})=>"lookup"===name))}get holderReference(){return this.executionResponse.holderReference}get savedCreditCards(){const cardPayment=this.availablePaymentMethods.find((({paymentMethodCode:paymentMethodCode})=>paymentMethodCode===PAYMENT_METHOD_CODES.CARD));return(null==cardPayment?void 0:cardPayment.paymentInstruments)||[]}get googlePayConfig(){const googlePay=this.availablePaymentMethods.find((({paymentMethodCode:paymentMethodCode})=>paymentMethodCode===PAYMENT_METHOD_CODES.GOOGLE_PAY));if(!googlePay)throw new Error("trying to initialize google pay without config");return googlePay?[googlePay.config]:[]}get url(){return this.response.links.self}get response(){return this.executionResponse}get meta(){return this.executionResponse.meta}get availablePaymentMethods(){var _a;return(null===(_a=this.lookup)||void 0===_a?void 0:_a.body.data.paymentCompositionOptions)||[]}get authorizeLink(){var _a;return null===(_a=this.lookup)||void 0===_a?void 0:_a.body.links.authorize.href}update(response){this.executionResponse=response}}class CardPaymentButton extends PayrailsElement{constructor(sdkConfig,execution,options){var _a;super("button",{id:"payrails-card-payment-button"}),this.sdkConfig=sdkConfig,this.execution=execution,this.options=options,this.selectedCard=null,this.storeInstrument=!1,this.element.innerText=(null===(_a=null==options?void 0:options.translations)||void 0===_a?void 0:_a.label)||"Pay",this.element.addEventListener("click",this.onPay.bind(this)),this.element.addEventListener("mouseenter",(()=>{var _a;this.element.classList.add("hover"),this.setStyles((null===(_a=this.options.styles)||void 0===_a?void 0:_a.hover)||{})})),this.element.addEventListener("mouseleave",(()=>{var _a;this.element.classList.remove("hover"),this.removeStyles((null===(_a=this.options.styles)||void 0===_a?void 0:_a.hover)||{})})),this.paymentExecutor=new PaymentExecutor(this.sdkConfig,this.execution)}setDisabled(isDisabled){var _a,_b,_c;this.element.disabled=isDisabled,isDisabled?(this.element.classList.add("disabled"),(null===(_a=this.options.styles)||void 0===_a?void 0:_a.disabled)&&this.setStyles(this.options.styles.disabled)):(this.element.classList.remove("disabled"),this.removeStyles((null===(_b=this.options.styles)||void 0===_b?void 0:_b.disabled)||{}),(null===(_c=this.options.styles)||void 0===_c?void 0:_c.base)&&this.setStyles(this.options.styles.base))}setStyles(styles){var _a;const stylesToApply=Object.assign(Object.assign({},null===(_a=this.options.styles)||void 0===_a?void 0:_a.base),styles);Object.keys(stylesToApply).forEach((key=>{this.element.style[key]=stylesToApply[key]}))}removeStyles(styles){var _a;const baseKeys=Object.keys((null===(_a=this.options.styles)||void 0===_a?void 0:_a.base)||{});Object.keys(styles).forEach((key=>{var _a,_b;baseKeys.includes(key)?this.element.style[key]=null===(_b=null===(_a=this.options.styles)||void 0===_a?void 0:_a.base)||void 0===_b?void 0:_b[key]:this.element.style[key]=""}))}setLabel(label){this.element.innerText=label}setCardForm(cardForm){this.cardForm=cardForm}triggerLoading(isLoading){var _a,_b,_c,_d;const elementWidth=this.element.offsetWidth;this.element.style.minWidth=`${elementWidth}px`,isLoading?(this.element.innerHTML='<div class="dot-flashing"></div>',this.element.classList.add("loading"),(null===(_a=this.options.styles)||void 0===_a?void 0:_a.loading)&&this.setStyles(this.options.styles.loading)):(this.element.innerText=(null===(_c=null===(_b=this.options)||void 0===_b?void 0:_b.translations)||void 0===_c?void 0:_c.label)||"Pay",this.element.classList.remove("loading"),this.removeStyles((null===(_d=this.options.styles)||void 0===_d?void 0:_d.loading)||{}))}onAuthorizationFailed(){var _a,_b;this.setDisabled(!1),this.triggerLoading(!1),(null===(_a=this.options.events)||void 0===_a?void 0:_a.onAuthorizeFailed)&&(null===(_b=this.options.events)||void 0===_b||_b.onAuthorizeFailed())}async onPay(){var _a,_b,_c,_d;if(this.setDisabled(!0),this.triggerLoading(!0),null===(_a=this.options.events)||void 0===_a?void 0:_a.onPaymentButtonClicked){if(!1===await(null===(_b=this.options.events)||void 0===_b?void 0:_b.onPaymentButtonClicked()))return void this.onAuthorizationFailed()}try{let instrumentId=null===(_c=this.selectedCard)||void 0===_c?void 0:_c.id;if(!instrumentId){instrumentId=(await this.tokenizeCard()).res.id}const paymentComposition=[{paymentMethodCode:PAYMENT_METHOD_CODES.CARD,integrationType:"api",amount:this.sdkConfig.amount,paymentInstrumentId:instrumentId,storeInstrument:this.storeInstrument}],authorizationResult=await this.paymentExecutor.pay(paymentComposition);this.handleAuthorizationResult(authorizationResult)}catch(error){error instanceof AuthorizationError&&(null===(_d=this.options.events)||void 0===_d?void 0:_d.onPaymentSessionExpired)&&this.options.events.onPaymentSessionExpired(),this.onAuthorizationFailed()}}handleAuthorizationResult(result){var _a,_b,_c;switch(null===(_a=null==result?void 0:result.finalState)||void 0===_a?void 0:_a.code){case"authorizeSuccessful":this.triggerLoading(!1),(null===(_b=this.options.events)||void 0===_b?void 0:_b.onAuthorizeSuccess)&&this.options.events.onAuthorizeSuccess();break;case"authorizePending":"3ds"===(null===(_c=null==result?void 0:result.response)||void 0===_c?void 0:_c.actionRequired)&&this.handle3ds(result);break;default:this.onAuthorizationFailed()}}handle3ds(authorizationResult){var _a,_b;const link=null===(_a=null==authorizationResult?void 0:authorizationResult.response)||void 0===_a?void 0:_a.links["3ds"];if(link){const availableSizes=[[250,400],[390,400],[500,600],[600,400]],screenWidth=screen.width,iframeSize=availableSizes.reduce(((prev,curr)=>screenWidth>curr[0]?curr:prev),[250,400]),iframe=document.createElement("iframe");iframe.setAttribute("id","payrails-3ds-frame"),iframe.setAttribute("src",link),iframe.setAttribute("width",iframeSize[0].toString()),iframe.setAttribute("height",iframeSize[1].toString());const popup=document.createElement("div");popup.setAttribute("id","payrails-3ds-challenge"),popup.appendChild(iframe);const popupBackground=document.createElement("div");popupBackground.addEventListener("click",(async()=>{popupBackground.remove()})),popupBackground.setAttribute("id","payrails-3ds-popup-background"),popupBackground.appendChild(popup);const handleMessages=async ev=>{var _a,_b,_c;if(ev.data&&'{"type":"3DS-challenge-completed"}'===ev.data){window.removeEventListener("message",handleMessages),popupBackground.remove();if(!(await this.paymentExecutor.getExecution(this.execution.url)).res.status.find((({code:code})=>"authorizeSuccessful"===code))&&(null===(_a=this.options.events)||void 0===_a?void 0:_a.onAuthorizeFailed))return void this.onAuthorizationFailed();if(null===(_b=this.options.events)||void 0===_b?void 0:_b.onAuthorizeSuccess)return void(null===(_c=this.options.events)||void 0===_c||_c.onAuthorizeSuccess())}};null===(_b=document.querySelector("body"))||void 0===_b||_b.appendChild(popupBackground),window.addEventListener("message",handleMessages),popup.style.width=`${iframeSize[0]+4}px`,popup.style.height=`${iframeSize[1]+4}px`}}async tokenizeCard(){if(!this.cardForm)throw new Error("Trying to tokenize non-existent card form");const{tokenizedCardData:tokenizedCardData,storeInstrument:storeInstrument}=await this.cardForm.collectValues();this.storeInstrument=Boolean(storeInstrument);const{instrumentId:instrumentId,card_number:card_number,cardholder_name:cardholder_name,expiry_month:expiry_month,expiry_year:expiry_year}=tokenizedCardData;return(({url:url,token:token,instrumentId:instrumentId,holderReference:holderReference,providerId:providerId,providerConfigId:providerConfigId,meta:meta,storeInstrument:storeInstrument=!1})=>payrailsFetch({url:url,token:token,method:RequestMethod.POST,body:{holderReference:holderReference,storeInstrument:storeInstrument,paymentMethod:"card",token:{providerId:providerId,providerConfigId:providerConfigId,reference:instrumentId,type:"vault",meta:meta}}}))({url:this.sdkConfig.vaultConfiguration.links.saveInstrument.href,token:this.sdkConfig.token,instrumentId:instrumentId,holderReference:this.execution.holderReference,providerId:this.sdkConfig.vaultConfiguration.providerId,providerConfigId:this.sdkConfig.vaultConfiguration.providerConfigId,meta:{skyflow_id:instrumentId,card_number:card_number,cardholder_name:cardholder_name,expiry_month:expiry_month,expiry_year:expiry_year},storeInstrument:this.storeInstrument})}}class AuthFailMsg extends PayrailsElement{constructor(label="Authorization failed, please try again."){super("div",{id:"authorization-failed-message"}),this.element.innerText=label,this.element.innerHTML=`\n <div>\n <svg class="checkmark-cross" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">\n <circle class="checkmark-cross_circle" cx="26" cy="26" r="25" fill="none"/>\n <path class="checkmark-cross_check" fill="none" d="M14.1 14.1l23.8 23.8 m0,-23.8 l-23.8,23.8"/>\n </svg>\n </div>\n <div>${label}</div>`,this.element.addEventListener("click",(e=>{e.stopImmediatePropagation(),e.stopPropagation(),this.unmount()}))}}class AuthSuccessMsg extends PayrailsElement{constructor(options){var _a;super("div",{id:"payrails-authorization-success-msg"}),this.element.innerHTML=`\n <div class="checkmark-wrapper">\n <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">\n <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/>\n <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>\n </svg>\n </div>\n <div id="payrails-authorization-success">${(null===(_a=null==options?void 0:options.translations)||void 0===_a?void 0:_a.label)||"Payment successful"}</div`}}class DropinElement extends PayrailsElement{constructor(id,label,events){super("div",{id:id,className:"payrails-dropin-item"}),this.events=events,this.isActive=!1;const checkboxId=`payrails-dropin-item-${id}`,labelEl=document.createElement("label");labelEl.setAttribute("for",checkboxId);const input=document.createElement("input");input.setAttribute("type","radio"),input.setAttribute("name","payment-option"),input.setAttribute("id",checkboxId),input.setAttribute("value",checkboxId),this.input=input,labelEl.appendChild(input),this.label=labelEl;const text=document.createElement("span");labelEl.appendChild(text),text.innerText=label,this.element.appendChild(labelEl)}get identifier(){return`payrails-dropin-item-${this.id}`}deactivate(){var _a,_b;this.isActive&&(this.isActive=!1,this.label.style.marginBottom="0",null===(_a=this.component)||void 0===_a||_a.unmount(),(null===(_b=this.events)||void 0===_b?void 0:_b.onDeactivate)&&this.events.onDeactivate())}activate(){var _a,_b;this.isActive||(null===(_a=this.component)||void 0===_a||_a.mount(`#${this.id}`),this.label.style.marginBottom="8px",this.isActive=!0,(null===(_b=this.events)||void 0===_b?void 0:_b.onActivate)&&this.events.onActivate())}}class CreditCardDropin extends DropinElement{constructor(cardForm,paymentButton){super("payrails-credit-card-wrapper","Card"),this.cardForm=cardForm,this.paymentButton=paymentButton,this.cardFormShown=!1,this.component=new CreditCardFormWrapper(cardForm,paymentButton)}activate(){var _a,_b;this.cardFormShown||(this.cardFormShown=!0,null===(_a=this.component)||void 0===_a||_a.mount(`#${this.id}`)),this.isActive||(this.paymentButton.selectedCard=null,this.paymentButton.mount(`#${this.id}`),this.paymentButton.setDisabled(!this.cardForm.isValid),this.paymentButton.mount("#payrails-card-form"),this.input.checked=!0,this.cardForm.show(),this.isActive=!0,(null===(_b=this.events)||void 0===_b?void 0:_b.onActivate)&&this.events.onActivate())}deactivate(){var _a;this.isActive&&(this.paymentButton.unmount(),this.cardForm.hide(),this.isActive=!1,(null===(_a=this.events)||void 0===_a?void 0:_a.onDeactivate)&&this.events.onDeactivate())}}class CreditCardFormWrapper extends PayrailsElement{constructor(cardForm,paymentButton){super("div",{id:"payrails-form-container"}),this.subElements.push(cardForm,paymentButton)}}const GPAY_BASE_REQUEST={apiVersion:2,apiVersionMinor:0};class GooglePayButton extends PayrailsElement{constructor(sdkConfig,execution,options){super("div",{id:"payrails-google-pay-button"}),this.sdkConfig=sdkConfig,this.execution=execution,this.options=options,this.client=null,this.googleButton=null,this.loadScript=null,this.paymentExecutor=new PaymentExecutor(sdkConfig,execution)}async sdkLoaded(){var _a,_b,_c,_d,_e,_f,_g,_h;this.client=new google.payments.api.PaymentsClient({environment:this.options.environment||"TEST"});try{const isReadyToPayRequest=Object.assign({},GPAY_BASE_REQUEST);if(isReadyToPayRequest.allowedPaymentMethods=this.execution.googlePayConfig,!this.client)throw new Error("Google pay client can not be initialized");const{result:result}=await this.client.isReadyToPay(isReadyToPayRequest);if(!result)return;const buttonColor=(null===(_b=null===(_a=this.options)||void 0===_a?void 0:_a.styles)||void 0===_b?void 0:_b.buttonColor)||"black",buttonType=(null===(_d=null===(_c=this.options)||void 0===_c?void 0:_c.styles)||void 0===_d?void 0:_d.buttonType)||"long",buttonSizeMode=(null===(_f=null===(_e=this.options)||void 0===_e?void 0:_e.styles)||void 0===_f?void 0:_f.buttonSizeMode)||"fill",buttonLocale=(null===(_h=null===(_g=this.options)||void 0===_g?void 0:_g.styles)||void 0===_h?void 0:_h.buttonLocale)||void 0;this.googleButton=this.client.createButton({buttonColor:buttonColor,buttonType:buttonType,buttonSizeMode:buttonSizeMode,buttonLocale:buttonLocale,onClick:async()=>{var _a,_b,_c;if(null===(_b=null===(_a=this.options)||void 0===_a?void 0:_a.events)||void 0===_b?void 0:_b.onPaymentButtonClicked){if(!await(null===(_c=this.options)||void 0===_c?void 0:_c.events.onPaymentButtonClicked()))return}this.onPaymentButtonClicked()},allowedPaymentMethods:this.execution.googlePayConfig}),this.element.appendChild(this.googleButton)}catch(e){throw console.error("Google pay can not be initialized",e),new Error(e.message)}}async onLoadPaymentData(data){var _a,_b,_c,_d;const paymentComposition=[{paymentMethodCode:"googlePay",integrationType:"api",paymentInstrumentData:{paymentToken:data.paymentMethodData.tokenizationData.token},amount:this.sdkConfig.amount}],result=await this.paymentExecutor.pay(paymentComposition);(null===(_b=null===(_a=this.options)||void 0===_a?void 0:_a.events)||void 0===_b?void 0:_b.onAuthorizeSuccess)&&(null===(_d=null===(_c=this.options)||void 0===_c?void 0:_c.events)||void 0===_d||_d.onAuthorizeSuccess(result))}async onPaymentButtonClicked(){var _a,_b,_c,_d,_e;const paymentDataRequest=Object.assign({},GPAY_BASE_REQUEST);if(paymentDataRequest.allowedPaymentMethods=this.execution.googlePayConfig,paymentDataRequest.transactionInfo={totalPriceStatus:"FINAL",totalPrice:null===(_a=this.sdkConfig.amount)||void 0===_a?void 0:_a.value,currencyCode:null===(_b=this.sdkConfig.amount)||void 0===_b?void 0:_b.currency,countryCode:null===(_e=null===(_d=null===(_c=this.execution.meta)||void 0===_c?void 0:_c.customer)||void 0===_d?void 0:_d.country)||void 0===_e?void 0:_e.code},!this.client)throw new Error("Google pay client is not initialized");this.client.loadPaymentData(paymentDataRequest).then((paymentData=>{this.onLoadPaymentData(paymentData)})).catch((err=>{var _a,_b,_c;(null===(_b=null===(_a=this.options)||void 0===_a?void 0:_a.events)||void 0===_b?void 0:_b.onAuthorizeFailed)&&(null===(_c=this.options)||void 0===_c||_c.events.onAuthorizeFailed(err))}))}mount(location){super.mount(location),this.loadScript?this.googleButton&&this.element.appendChild(this.googleButton):(this.loadScript=new LoadScript(this.sdkLoaded.bind(this)),this.loadScript.mount("body"))}unmount(){var _a;this.googleButton&&(null===(_a=this.googleButton.parentElement)||void 0===_a||_a.removeChild(this.googleButton)),super.unmount()}}class LoadScript extends PayrailsElement{constructor(onIsLoaded){super("script"),this.loaded=!1,this.loaded||(this.element.setAttribute("async","async"),this.element.setAttribute("src","https://pay.google.com/gp/p/js/pay.js"),this.element.setAttribute("onload","onPayrailsGpayLoaded()"),window.onPayrailsGpayLoaded=()=>{this.loaded||(this.loaded=!0,onIsLoaded())})}}class GooglePayDropin extends DropinElement{constructor(sdkConfig,workflowExecution,options){var _a;super("google-pay-dropin",(null===(_a=options.translations)||void 0===_a?void 0:_a.label)||"Google Pay"),this.component=new GooglePayButton(sdkConfig,workflowExecution,options)}}class SavedCard extends DropinElement{constructor(cardData,paymentButton,onActivate){super(`card-${cardData.id}`,`****${cardData.data.suffix}`,{onActivate:()=>{onActivate(cardData),this.component.setDisabled(!1)}}),this.component=paymentButton}}class Dropin extends PayrailsElement{constructor(collectContainer,dropinConfig,execution,sdkConfig){var _a,_b;super("fieldset",{id:"payrails-dropin-component"}),this.collectContainer=collectContainer,this.dropinConfig=dropinConfig,this.execution=execution,this.sdkConfig=sdkConfig;const savedCardsDisabled=!1===(null===(_b=null===(_a=this.dropinConfig.paymentMethodsConfiguration)||void 0===_a?void 0:_a.cards)||void 0===_b?void 0:_b.showExistingCards),availablePayments=new Map;this.execution.availablePaymentMethods.forEach((({paymentMethodCode:paymentMethodCode})=>{if(paymentMethodCode===PAYMENT_METHOD_CODES.CARD)savedCardsDisabled||this.execution.savedCreditCards.forEach((cardData=>{var _a;this.cardPaymentButton=this.createCardPaymentButton(null===(_a=this.dropinConfig.translations)||void 0===_a?void 0:_a.cardPaymentButton);const savedCard=new SavedCard(cardData,this.cardPaymentButton,(cardData=>{this.cardPaymentButton&&(this.cardPaymentButton.selectedCard=cardData)}));availablePayments.set(savedCard.identifier,savedCard)}))})),this.execution.availablePaymentMethods.forEach((({paymentMethodCode:paymentMethodCode})=>{var _a,_b;switch(paymentMethodCode){case PAYMENT_METHOD_CODES.CARD:this.creditCard=new CreditCardDropin(this.createCardForm(),this.createCardPaymentButton(null===(_a=this.dropinConfig.translations)||void 0===_a?void 0:_a.cardPaymentButton)),availablePayments.set(this.creditCard.identifier,this.creditCard);break;case PAYMENT_METHOD_CODES.GOOGLE_PAY:this.googlePay=new GooglePayDropin(this.sdkConfig,this.execution,{events:{onAuthorizeSuccess:result=>{var _a;if(result)if("authorizeSuccessful"===(null===(_a=null==result?void 0:result.finalState)||void 0===_a?void 0:_a.code))this.onAuthorizeSuccess();else this.onAuthorizeFailed()},onAuthorizeFailed:this.onAuthorizeFailed.bind(this),onPaymentButtonClicked:this.dropinConfig.events.onPaymentButtonClicked},styles:null===(_b=this.dropinConfig.styles)||void 0===_b?void 0:_b.googlePayButton}),availablePayments.set(this.googlePay.identifier,this.googlePay)}})),this.element.addEventListener("change",(e=>{var _a,_b;const elementKey=(null===(_a=null==e?void 0:e.target)||void 0===_a?void 0:_a.value)||"";availablePayments.forEach((val=>{val.deactivate()})),null===(_b=availablePayments.get(elementKey))||void 0===_b||_b.activate()})),this.subElements.push(...Array.from(availablePayments.values()))}createCardForm(){var _a,_b;if(!this.cardForm){const cardConfig=null===(_a=this.dropinConfig.paymentMethodsConfiguration)||void 0===_a?void 0:_a.cards,showStoreInstrumentCheckbox=Boolean(null==cardConfig?void 0:cardConfig.showStoreInstrumentCheckbox),showCardHolderName=Boolean(null==cardConfig?void 0:cardConfig.showCardHolderName),alwaysStoreInstrument=Boolean(null==cardConfig?void 0:cardConfig.alwaysStoreInstrument);this.cardForm=new CardForm(this.collectContainer,{showStoreInstrumentCheckbox:showStoreInstrumentCheckbox,showCardHolderName:showCardHolderName,alwaysStoreInstrument:alwaysStoreInstrument,translations:null===(_b=this.dropinConfig.translations)||void 0===_b?void 0:_b.cardForm,events:{onFocus:()=>{var _a;null===(_a=this.creditCard)||void 0===_a||_a.activate()},onChange:({isValid:isValid})=>{var _a;null===(_a=this.cardPaymentButton)||void 0===_a||_a.setDisabled(!isValid)}}})}return this.cardPaymentButton&&this.cardPaymentButton.setCardForm(this.cardForm),this.cardForm}createCardPaymentButton(translations){return this.cardPaymentButton||(this.cardPaymentButton=new CardPaymentButton(this.sdkConfig,this.execution,{translations:translations,events:{onAuthorizeSuccess:this.onAuthorizeSuccess.bind(this),onAuthorizeFailed:this.onAuthorizeFailed.bind(this),onPaymentButtonClicked:this.dropinConfig.events.onPaymentButtonClicked}})),this.cardForm&&this.cardPaymentButton.setCardForm(this.cardForm),this.cardPaymentButton}onAuthorizeSuccess(){var _a,_b,_c,_d;this.subElements.forEach((i=>i.unmount())),new AuthSuccessMsg({translations:{label:null===(_c=null===(_b=null===(_a=this.dropinConfig)||void 0===_a?void 0:_a.translations)||void 0===_b?void 0:_b.paymentResult)||void 0===_c?void 0:_c.success}}).mount(`#${this.id}`),(null===(_d=this.dropinConfig.events)||void 0===_d?void 0:_d.onAuthorizeSuccess)&&this.dropinConfig.events.onAuthorizeSuccess()}onAuthorizeFailed(){var _a,_b,_c;new AuthFailMsg(null===(_b=null===(_a=this.dropinConfig.translations)||void 0===_a?void 0:_a.paymentResult)||void 0===_b?void 0:_b.fail).mount(`#${this.id}`),this.dropinConfig.events.onAuthorizeFailed&&(null===(_c=this.dropinConfig.events)||void 0===_c||_c.onAuthorizeFailed())}}var Skyflow$1=require("skyflow-js").default;class CollectContainer{constructor(__client,options){this.__container=__client.container(Skyflow$1.ContainerType.COMPOSABLE,options)}get elementToFieldMap(){return new Map([[exports.ElementType.CARD_NUMBER,"card_number"],[exports.ElementType.CARDHOLDER_NAME,"cardholder_name"],[exports.ElementType.CVV,"security_code"],[exports.ElementType.EXPIRATION_MONTH,"expiry_month"],[exports.ElementType.EXPIRATION_YEAR,"expiry_year"]])}createCollectElement(options){return this.__container.create(Object.assign(Object.assign(Object.assign({},DEFAULT_ELEMENT_CONFIG),{column:this.elementToFieldMap.get(options.type)}),options),{format:options.format})}mount(selector){const id="payrails-container-wrapper";this.element=document.createElement("span"),this.element.setAttribute("id",id);const parentEl=document.querySelector(selector);if(!parentEl)throw new Error(`Element with selector ${selector} does not exist`);parentEl.appendChild(this.element),window.setTimeout((()=>{this.__container.mount(`#${id}`)}),50)}unmount(){this.element&&this.element.remove()}async collect(){const{records:records}=await this.__container.collect(),{skyflow_id:skyflow_id,card_number:card_number,cardholder_name:cardholder_name,expiry_month:expiry_month,expiry_year:expiry_year}=records[0].fields;return{instrumentId:skyflow_id,card_number:card_number,cardholder_name:cardholder_name,expiry_month:expiry_month,expiry_year:expiry_year}}}var Skyflow=require("skyflow-js").default;class Payrails{static init(initResponse,options){const deserializedData=JSON.parse(atob(initResponse.data)),{vaultConfiguration:{vaultId:vaultId,vaultUrl:vaultUrl,token:token},execution:execution}=deserializedData,vaultClient=Skyflow.init({vaultID:vaultId,vaultURL:vaultUrl,getBearerToken:()=>Promise.resolve(token)});return new Payrails(deserializedData,vaultClient,new WorkflowExecution(execution),options)}update(execution,amount){this.execution.update(execution),this.sdkConfiguration.amount=amount}collectContainer(containerOptions){if(!containerOptions.layout)throw new Error("Layout configuration is required");return this.__container=new CollectContainer(this.vaultClient,containerOptions),this.__container}googlePayButton(options){var _a;if(!this.execution)throw new Error("SDK was not initialized with workflow execution");return new GooglePayButton(this.sdkConfiguration,this.execution,Object.assign({environment:null===(_a=this.options)||void 0===_a?void 0:_a.environment},options))}cardList(options){return this.__cardList||(this.__cardList=new CardList(this.execution,{onCardChange:selectedCard=>{this.__cardPaymentButton&&(this.__cardPaymentButton.selectedCard=selectedCard,this.__cardPaymentButton.setDisabled(!1)),null==options||options.onCardChange(selectedCard)}})),this.__cardList}cardForm(options){var _a,_b;if(!this.__cardForm){const layout=this.getContainerLayout(null==options?void 0:options.showCardHolderName);this.__container=this.collectContainer(Object.assign(Object.assign({layout:layout,errorTextStyles:{base:{display:"none"}}},null===(_a=null==options?void 0:options.styles)||void 0===_a?void 0:_a.errorTextStyles),{styles:{base:null===(_b=null==options?void 0:options.styles)||void 0===_b?void 0:_b.base}})),this.__cardForm=new CardForm(this.__container,Object.assign(Object.assign({},options),{events:Object.assign(Object.assign({},null==options?void 0:options.events),{onChange:e=>{var _a;this.__cardPaymentButton&&(this.__cardPaymentButton.selectedCard=null,this.__cardForm&&this.__cardPaymentButton.setDisabled(!this.__cardForm.isValid)),(null===(_a=null==options?void 0:options.events)||void 0===_a?void 0:_a.onChange)&&options.events.onChange(e)},onFocus:()=>{var _a;this.__cardList&&this.__cardList.reset(),this.__cardPaymentButton&&(this.__cardPaymentButton.selectedCard=null,this.__cardForm&&this.__cardPaymentButton.setDisabled(!this.__cardForm.isValid)),(null===(_a=null==options?void 0:options.events)||void 0===_a?void 0:_a.onFocus)&&options.events.onFocus()}})}))}return this.__cardPaymentButton&&this.__cardPaymentButton.setCardForm(this.__cardForm),this.__cardForm}constructor(sdkConfiguration,vaultClient,execution,options){var _a;this.sdkConfiguration=sdkConfiguration,this.vaultClient=vaultClient,this.execution=execution,this.options=options,(null===(_a=null==options?void 0:options.events)||void 0===_a?void 0:_a.onClientInitialized)&&options.events.onClientInitialized(this.execution)}dropin(options){var _a,_b;const layout=this.getContainerLayout(null===(_b=null===(_a=options.paymentMethodsConfiguration)||void 0===_a?void 0:_a.cards)||void 0===_b?void 0:_b.showCardHolderName);return this.__container=this.collectContainer({layout:layout,errorTextStyles:{base:{display:"none"}}}),new Dropin(this.__container,options,this.execution,this.sdkConfiguration)}getContainerLayout(showCardHolderName){return showCardHolderName?[1,1,3]:[1,3]}paymentButton(options){return this.__cardPaymentButton||(this.__cardPaymentButton=new CardPaymentButton(this.sdkConfiguration,this.execution,options)),this.__cardPaymentButton.setDisabled(!0),this.__cardForm&&this.__cardPaymentButton.setCardForm(this.__cardForm),this.__cardPaymentButton}}exports.Payrails=Payrails;
|
|
1
|
+
!function(){"use strict";var t;exports.ElementType=void 0,(t=exports.ElementType||(exports.ElementType={})).CARD_NUMBER="CARD_NUMBER",t.CARDHOLDER_NAME="CARDHOLDER_NAME",t.CVV="CVV",t.EXPIRATION_MONTH="EXPIRATION_MONTH",t.EXPIRATION_YEAR="EXPIRATION_YEAR";class e{constructor(t,{id:e="",className:i=""}={}){this.subElements=[];const o=document.createElement(t);e&&(this.id=e,o.setAttribute("id",e)),i&&o.setAttribute("class",i),this.element=o}get parentElement(){return this.element.parentElement}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);e.appendChild(this.element),this.subElements.forEach((t=>{if(!this.id)throw new Error("Sub elements can not be rendered, please set id for the element");t.mount(`#${this.id}`)}))}unmount(){var t;this.subElements.forEach((t=>t.unmount())),null===(t=this.parentElement)||void 0===t||t.removeChild(this.element)}}const{CARD_NUMBER:i,CVV:o,CARDHOLDER_NAME:n,EXPIRATION_MONTH:s,EXPIRATION_YEAR:a}=exports.ElementType,r={base:{border:"none",padding:"10px 16px",color:"#1d1d1d",backgroundColor:"#fff"},invalid:{backgroundColor:"#f9e1e1",borderColor:"#f25226",border:"1px solid"}},l=[{type:n,placeholder:"Card holder",styles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base),{border:"1px solid #eae8ee",padding:"10px 16px",borderTopLeftRadius:"4px",borderTopRightRadius:"4px"})})},{type:i,placeholder:"1234 1234 1234 1234",styles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base),{border:"1px solid #eae8ee",padding:"10px 16px",borderTopLeftRadius:"4px",borderTopRightRadius:"4px",textIndent:"0"}),cardIcon:{position:"absolute",right:"8px",height:"24px",bottom:"calc(50% - 12px)"}})},{type:s,placeholder:"MM",styles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base),{borderBottom:"1px solid #eae8ee",borderLeft:"1px solid #eae8ee",borderRight:"1px solid #eae8ee",borderBottomLeftRadius:"4px"})})},{type:a,placeholder:"YY",format:"YY",styles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base),{borderBottom:"1px solid #eae8ee",borderRight:"1px solid #eae8ee"})})},{type:o,placeholder:"CVC",styles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base),{borderBottom:"1px solid #eae8ee",borderRight:"1px solid #eae8ee",borderBottomRightRadius:"4px"})})}];class d extends e{constructor(t,e){var i,o,n,s,a,r;super("div",{id:"payrails-card-form"}),this.collectContainer=t,this.options=e,this.storeCardCheckbox=null,this.formFields=[],l.forEach((({type:t,styles:i,format:o,placeholder:n,label:s})=>{var a,r,l,d,c;if(!(null===(a=this.options)||void 0===a?void 0:a.showCardHolderName)&&t===exports.ElementType.CARDHOLDER_NAME)return;const h=this.prepareStyles(i,t),v=new u(this.collectContainer,{type:t,label:s,placeholder:(null===(l=null===(r=null==e?void 0:e.translations)||void 0===r?void 0:r.placeholders)||void 0===l?void 0:l[t])||n,inputStyles:h,format:o,events:{onFocus:null===(c=null===(d=this.options)||void 0===d?void 0:d.events)||void 0===c?void 0:c.onFocus,onChange:this.onChange.bind(this)}});this.formFields.push(v)})),this.subElements.push(this.collectContainer),(null===(i=this.options)||void 0===i?void 0:i.showStoreInstrumentCheckbox)&&(this.storeCardCheckbox=new c({label:null===(s=null===(n=null===(o=this.options)||void 0===o?void 0:o.translations)||void 0===n?void 0:n.labels)||void 0===s?void 0:s.saveCreditCard,styles:null===(r=null===(a=this.options)||void 0===a?void 0:a.styles)||void 0===r?void 0:r.storeCardCheckbox}),this.subElements.push(this.storeCardCheckbox))}show(){this.element.style.display="flex"}hide(){this.element.style.display="none"}prepareStyles(t,e){var i;let o=JSON.parse(JSON.stringify(t));return(null===(i=this.options)||void 0===i?void 0:i.showCardHolderName)&&e===exports.ElementType.CARD_NUMBER&&(this.element.setAttribute("class","with-card-holder"),o=Object.assign(Object.assign({},t),{base:Object.assign(Object.assign({},r.base),{border:"1px solid #eae8ee",borderTop:"none",padding:"10px 16px"})})),["base","complete","empty","focus","invalid","cardIcon","copyIcon"].forEach((t=>{var i,n,s,a,r,l,d;o[t]=Object.assign(Object.assign(Object.assign({},o[t]),null===(a=null===(s=null===(n=null===(i=this.options)||void 0===i?void 0:i.styles)||void 0===n?void 0:n.inputFields)||void 0===s?void 0:s.all)||void 0===a?void 0:a[t]),null===(d=null===(l=null===(r=this.options)||void 0===r?void 0:r.styles)||void 0===l?void 0:l.inputFields)||void 0===d?void 0:d[e])})),o}get isValid(){return this.formFields.reduce(((t,e)=>t&&e.isValid),!0)}onChange(){var t,e,i,o;(null===(e=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===e?void 0:e.onChange)&&(null===(o=null===(i=this.options)||void 0===i?void 0:i.events)||void 0===o||o.onChange({isValid:this.isValid}))}async collectValues(){var t,e;return{tokenizedCardData:await this.collectContainer.collect(),storeInstrument:(null===(t=this.storeCardCheckbox)||void 0===t?void 0:t.isChecked)||(null===(e=this.options)||void 0===e?void 0:e.alwaysStoreInstrument)}}}class c extends e{constructor(t){super("span",{id:"payrails-store-card"});const e="payrails-store-card-checkbox",i=(null==t?void 0:t.label)||"Save credit card for future payments";this.element.innerHTML=`<label for="${e}"}"><input type="checkbox" id="${e}" name="${e}" >${i}</label>`,Object.keys((null==t?void 0:t.styles)||{}).forEach((e=>{var i;this.element.style[e]=null===(i=null==t?void 0:t.styles)||void 0===i?void 0:i[e]})),this.element.addEventListener("change",(t=>{t.stopPropagation(),t.stopImmediatePropagation()}))}get isChecked(){var t;return null===(t=this.element.querySelector("input"))||void 0===t?void 0:t.checked}}class u{constructor(t,e){this.isValid=!1;const{type:i,label:o,placeholder:n,inputStyles:s,events:a,format:r}=e,l=t.createCollectElement({type:i,label:o,placeholder:n,format:r,inputStyles:s});(null==a?void 0:a.onFocus)&&l.on("FOCUS",a.onFocus),l.on("CHANGE",(t=>{const{isEmpty:e,isValid:i}=t;this.isValid=!e&&i,(null==a?void 0:a.onChange)&&a.onChange(this)}))}}class h extends e{constructor(t,e){super("div",{id:"payrails-card-list"}),this.workflowExecution=t,this.listItems=[],this.workflowExecution.savedCreditCards.forEach((t=>{const i=new v((()=>{(null==e?void 0:e.onCardChange)&&e.onCardChange(t)}),t);this.listItems.push(i),this.subElements.push(i)}))}reset(){this.element.querySelectorAll("input").forEach((t=>t.checked=!1))}}class v extends e{constructor(t,e){super("div",{className:"payrails-card-list-item",id:`payrails-card-list-item-${e.id}`});const{id:i}=e,o=this.createCardLabel(e),n=document.createElement("label");n.setAttribute("for",i),n.addEventListener("click",t);const s=document.createElement("input");s.setAttribute("type","radio"),s.setAttribute("name","payment-option"),s.setAttribute("id",i),s.setAttribute("value",i),n.appendChild(s);const a=document.createElement("span");a.innerText=o,n.appendChild(a),this.element.appendChild(n)}createCardLabel({data:{suffix:t}}){return`****${t}`}}let p;const m=new Uint8Array(16);function y(){if(!p&&(p="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!p))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return p(m)}const g=[];for(let t=0;t<256;++t)g.push((t+256).toString(16).slice(1));var b,C={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function f(t,e,i){if(C.randomUUID&&!e&&!t)return C.randomUUID();const o=(t=t||{}).random||(t.rng||y)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,e){i=i||0;for(let t=0;t<16;++t)e[i+t]=o[t];return e}return function(t,e=0){return(g[t[e+0]]+g[t[e+1]]+g[t[e+2]]+g[t[e+3]]+"-"+g[t[e+4]]+g[t[e+5]]+"-"+g[t[e+6]]+g[t[e+7]]+"-"+g[t[e+8]]+g[t[e+9]]+"-"+g[t[e+10]]+g[t[e+11]]+g[t[e+12]]+g[t[e+13]]+g[t[e+14]]+g[t[e+15]]).toLowerCase()}(o)}!function(t){t.GET="GET",t.POST="POST"}(b||(b={}));const x=async({url:t,method:e=b.GET,token:i,body:o})=>{const n={method:e,headers:Object.assign(Object.assign({},k()),_(i))};e===b.POST&&(n.body=JSON.stringify(o||{}));const s=await fetch(t,n),a=await s.json();if([401,403].includes(s.status))throw new w(t,e);if(!s.ok)throw new E(t,e,a);return{ok:s.ok,req:Object.assign({url:t},n),res:a}};class w extends Error{constructor(t,e){super(`[${e}] ${t} unauthorized`)}}class E extends Error{constructor(t,e,i){super(`[${e}] ${t} unsuccessful`),this.res=i}}const _=t=>({authorization:`Bearer ${t}`}),k=()=>({"x-idempotency-key":f()});class A{constructor(t,e){this.sdkConfig=t,this.execution=e}async pay(t){const e=(await this.authorize(t)).res.links.execution;return await this.pollForAuthorizationResult(e)}async authorize(t){if(!this.execution.authorizeLink||!this.sdkConfig.amount)throw new Error("SDK was not initialized with workflow execution");return x({url:this.execution.authorizeLink,method:b.POST,token:this.sdkConfig.token,body:{amount:this.sdkConfig.amount,paymentComposition:t,returnInfo:{success:"https://www.bootstrap.payrails.io/success"}}})}async pollForAuthorizationResult(t){const e=(await this.getExecution(t)).res,i=e.status,o=["authorizePending","authorizeSuccessful","authorizeFailed"],n=i.find((({code:t})=>"authorizeRequested"===t));if(!n)return await new Promise((t=>setTimeout(t,300))),this.pollForAuthorizationResult(t);let s=i.find((({code:t,time:e})=>o.includes(t)&&new Date(e)>new Date(n.time)));if(!s){const{res:e}=await this.getExecution(t,void 0,n.time);return s=e.status.find((({code:t,time:e})=>o.includes(t)&&new Date(e)>new Date(n.time))),{finalState:s,response:e}}return{finalState:s,response:e}}async getExecution(t,e,i){const o=new URLSearchParams;e&&e.length>0&&o.append("waitWhile[status]",`[${e.map((t=>`"${t}"`)).join(",")}]`),i&&o.append("waitWhile[lastStatusTime]",i);const n=`${t}${o.toString()?"?":""}${o.toString()}`;return x({url:n,token:this.sdkConfig.token})}}var P,S;!function(t){t.CARD="card",t.GOOGLE_PAY="googlePay"}(P||(P={})),function(t){t.ENABLED="enabled",t.CREATED="created"}(S||(S={}));class O{constructor(t){this.executionResponse=t}get lookup(){return this.executionResponse.initialResults.find((({body:{name:t}})=>"lookup"===t))}get holderReference(){return this.executionResponse.holderReference}get savedCreditCards(){const t=this.availablePaymentMethods.find((({paymentMethodCode:t})=>t===P.CARD));return(null==t?void 0:t.paymentInstruments)||[]}get googlePayConfig(){const t=this.availablePaymentMethods.find((({paymentMethodCode:t})=>t===P.GOOGLE_PAY));if(!t)throw new Error("trying to initialize google pay without config");return t?[t.config]:[]}get url(){return this.response.links.self}get response(){return this.executionResponse}get meta(){return this.executionResponse.meta}get availablePaymentMethods(){var t;return(null===(t=this.lookup)||void 0===t?void 0:t.body.data.paymentCompositionOptions)||[]}get authorizeLink(){var t;return null===(t=this.lookup)||void 0===t?void 0:t.body.links.authorize.href}update(t){this.executionResponse=t}}class B extends e{constructor(t,e,i){var o;super("button",{id:"payrails-card-payment-button"}),this.sdkConfig=t,this.execution=e,this.options=i,this.selectedCard=null,this.storeInstrument=!1,this.element.innerText=(null===(o=null==i?void 0:i.translations)||void 0===o?void 0:o.label)||"Pay",this.element.addEventListener("click",this.onPay.bind(this)),this.element.addEventListener("mouseenter",(()=>{var t;this.element.classList.add("hover"),this.setStyles((null===(t=this.options.styles)||void 0===t?void 0:t.hover)||{})})),this.element.addEventListener("mouseleave",(()=>{var t;this.element.classList.remove("hover"),this.removeStyles((null===(t=this.options.styles)||void 0===t?void 0:t.hover)||{})})),this.paymentExecutor=new A(this.sdkConfig,this.execution)}setDisabled(t){var e,i,o;this.element.disabled=t,t?(this.element.classList.add("disabled"),(null===(e=this.options.styles)||void 0===e?void 0:e.disabled)&&this.setStyles(this.options.styles.disabled)):(this.element.classList.remove("disabled"),this.removeStyles((null===(i=this.options.styles)||void 0===i?void 0:i.disabled)||{}),(null===(o=this.options.styles)||void 0===o?void 0:o.base)&&this.setStyles(this.options.styles.base))}setStyles(t){var e;const i=Object.assign(Object.assign({},null===(e=this.options.styles)||void 0===e?void 0:e.base),t);Object.keys(i).forEach((t=>{this.element.style[t]=i[t]}))}removeStyles(t){var e;const i=Object.keys((null===(e=this.options.styles)||void 0===e?void 0:e.base)||{});Object.keys(t).forEach((t=>{var e,o;i.includes(t)?this.element.style[t]=null===(o=null===(e=this.options.styles)||void 0===e?void 0:e.base)||void 0===o?void 0:o[t]:this.element.style[t]=""}))}setLabel(t){this.element.innerText=t}setCardForm(t){this.cardForm=t}triggerLoading(t){var e,i,o,n;const s=this.element.offsetWidth;this.element.style.minWidth=`${s}px`,t?(this.element.innerHTML='<div class="dot-flashing"></div>',this.element.classList.add("loading"),(null===(e=this.options.styles)||void 0===e?void 0:e.loading)&&this.setStyles(this.options.styles.loading)):(this.element.innerText=(null===(o=null===(i=this.options)||void 0===i?void 0:i.translations)||void 0===o?void 0:o.label)||"Pay",this.element.classList.remove("loading"),this.removeStyles((null===(n=this.options.styles)||void 0===n?void 0:n.loading)||{}))}onAuthorizationFailed(){var t,e;this.setDisabled(!1),this.triggerLoading(!1),(null===(t=this.options.events)||void 0===t?void 0:t.onAuthorizeFailed)&&(null===(e=this.options.events)||void 0===e||e.onAuthorizeFailed())}async onPay(){var t,e,i,o;if(this.setDisabled(!0),this.triggerLoading(!0),null===(t=this.options.events)||void 0===t?void 0:t.onPaymentButtonClicked){if(!1===await(null===(e=this.options.events)||void 0===e?void 0:e.onPaymentButtonClicked()))return void this.onAuthorizationFailed()}try{let t=null===(i=this.selectedCard)||void 0===i?void 0:i.id;if(!t){t=(await this.tokenizeCard()).res.id}const e=[{paymentMethodCode:P.CARD,integrationType:"api",amount:this.sdkConfig.amount,paymentInstrumentId:t,storeInstrument:this.storeInstrument}],o=await this.paymentExecutor.pay(e);this.handleAuthorizationResult(o)}catch(t){t instanceof w&&(null===(o=this.options.events)||void 0===o?void 0:o.onPaymentSessionExpired)&&this.options.events.onPaymentSessionExpired(),this.onAuthorizationFailed()}}handleAuthorizationResult(t){var e,i,o;switch(null===(e=null==t?void 0:t.finalState)||void 0===e?void 0:e.code){case"authorizeSuccessful":this.triggerLoading(!1),(null===(i=this.options.events)||void 0===i?void 0:i.onAuthorizeSuccess)&&this.options.events.onAuthorizeSuccess();break;case"authorizePending":"3ds"===(null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.actionRequired)&&this.handle3ds(t);break;default:this.onAuthorizationFailed()}}handle3ds(t){var e,i;const o=null===(e=null==t?void 0:t.response)||void 0===e?void 0:e.links["3ds"];if(o){const t=[[250,400],[390,400],[500,600],[600,400]],e=screen.width,n=t.reduce(((t,i)=>e>i[0]?i:t),[250,400]),s=document.createElement("iframe");s.setAttribute("id","payrails-3ds-frame"),s.setAttribute("src",o),s.setAttribute("width",n[0].toString()),s.setAttribute("height",n[1].toString());const a=document.createElement("div");a.setAttribute("id","payrails-3ds-challenge"),a.appendChild(s);const r=document.createElement("div");r.addEventListener("click",(async()=>{r.remove()})),r.setAttribute("id","payrails-3ds-popup-background"),r.appendChild(a);const l=async t=>{var e,i,o;if(t.data&&'{"type":"3DS-challenge-completed"}'===t.data){window.removeEventListener("message",l),r.remove();if(!(await this.paymentExecutor.getExecution(this.execution.url)).res.status.find((({code:t})=>"authorizeSuccessful"===t))&&(null===(e=this.options.events)||void 0===e?void 0:e.onAuthorizeFailed))return void this.onAuthorizationFailed();if(null===(i=this.options.events)||void 0===i?void 0:i.onAuthorizeSuccess)return void(null===(o=this.options.events)||void 0===o||o.onAuthorizeSuccess())}};null===(i=document.querySelector("body"))||void 0===i||i.appendChild(r),window.addEventListener("message",l),a.style.width=`${n[0]+4}px`,a.style.height=`${n[1]+4}px`}}async tokenizeCard(){if(!this.cardForm)throw new Error("Trying to tokenize non-existent card form");const{tokenizedCardData:t,storeInstrument:e}=await this.cardForm.collectValues();this.storeInstrument=Boolean(e);const{instrumentId:i,card_number:o,cardholder_name:n,expiry_month:s,expiry_year:a}=t;return(({url:t,token:e,instrumentId:i,holderReference:o,providerId:n,providerConfigId:s,meta:a,storeInstrument:r=!1})=>x({url:t,token:e,method:b.POST,body:{holderReference:o,storeInstrument:r,paymentMethod:"card",token:{providerId:n,providerConfigId:s,reference:i,type:"vault",meta:a}}}))({url:this.sdkConfig.vaultConfiguration.links.saveInstrument.href,token:this.sdkConfig.token,instrumentId:i,holderReference:this.execution.holderReference,providerId:this.sdkConfig.vaultConfiguration.providerId,providerConfigId:this.sdkConfig.vaultConfiguration.providerConfigId,meta:{skyflow_id:i,card_number:o,cardholder_name:n,expiry_month:s,expiry_year:a},storeInstrument:this.storeInstrument})}}class R extends e{constructor(t="Authorization failed, please try again."){super("div",{id:"authorization-failed-message"}),this.element.innerText=t,this.element.innerHTML=`\n <div>\n <svg class="checkmark-cross" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">\n <circle class="checkmark-cross_circle" cx="26" cy="26" r="25" fill="none"/>\n <path class="checkmark-cross_check" fill="none" d="M14.1 14.1l23.8 23.8 m0,-23.8 l-23.8,23.8"/>\n </svg>\n </div>\n <div>${t}</div>`,this.element.addEventListener("click",(t=>{t.stopImmediatePropagation(),t.stopPropagation(),this.unmount()}))}}class F extends e{constructor(t){var e;super("div",{id:"payrails-authorization-success-msg"}),this.element.innerHTML=`\n <div class="checkmark-wrapper">\n <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">\n <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/>\n <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>\n </svg>\n </div>\n <div id="payrails-authorization-success">${(null===(e=null==t?void 0:t.translations)||void 0===e?void 0:e.label)||"Payment successful"}</div`}}class z extends e{constructor(t,e,i){super("div",{id:t,className:"payrails-dropin-item"}),this.events=i,this.isActive=!1;const o=`payrails-dropin-item-${t}`,n=document.createElement("label");n.setAttribute("for",o);const s=document.createElement("input");s.setAttribute("type","radio"),s.setAttribute("name","payment-option"),s.setAttribute("id",o),s.setAttribute("value",o),this.input=s,n.appendChild(s),this.label=n;const a=document.createElement("span");n.appendChild(a),a.innerText=e,this.element.appendChild(n)}get identifier(){return`payrails-dropin-item-${this.id}`}deactivate(){var t,e;this.isActive&&(this.isActive=!1,this.label.style.marginBottom="0",null===(t=this.component)||void 0===t||t.unmount(),(null===(e=this.events)||void 0===e?void 0:e.onDeactivate)&&this.events.onDeactivate())}activate(){var t,e;this.isActive||(null===(t=this.component)||void 0===t||t.mount(`#${this.id}`),this.label.style.marginBottom="8px",this.isActive=!0,(null===(e=this.events)||void 0===e?void 0:e.onActivate)&&this.events.onActivate())}}class I extends z{constructor(t,e){super("payrails-credit-card-wrapper","Card"),this.cardForm=t,this.paymentButton=e,this.cardFormShown=!1,this.component=new T(t,e)}activate(){var t,e;this.cardFormShown||(this.cardFormShown=!0,null===(t=this.component)||void 0===t||t.mount(`#${this.id}`)),this.isActive||(this.paymentButton.selectedCard=null,this.paymentButton.mount(`#${this.id}`),this.paymentButton.setDisabled(!this.cardForm.isValid),this.paymentButton.mount("#payrails-card-form"),this.input.checked=!0,this.cardForm.show(),this.isActive=!0,(null===(e=this.events)||void 0===e?void 0:e.onActivate)&&this.events.onActivate())}deactivate(){var t;this.isActive&&(this.paymentButton.unmount(),this.cardForm.hide(),this.isActive=!1,(null===(t=this.events)||void 0===t?void 0:t.onDeactivate)&&this.events.onDeactivate())}}class T extends e{constructor(t,e){super("div",{id:"payrails-form-container"}),this.subElements.push(t,e)}}const L={apiVersion:2,apiVersionMinor:0};class D extends e{constructor(t,e,i){super("div",{id:"payrails-google-pay-button"}),this.sdkConfig=t,this.execution=e,this.options=i,this.client=null,this.googleButton=null,this.loadScript=null,this.paymentExecutor=new A(t,e)}async sdkLoaded(){var t,e,i,o,n,s,a,r;this.client=new google.payments.api.PaymentsClient({environment:this.options.environment||"TEST"});try{const l=Object.assign({},L);if(l.allowedPaymentMethods=this.execution.googlePayConfig,!this.client)throw new Error("Google pay client can not be initialized");const{result:d}=await this.client.isReadyToPay(l);if(!d)return;const c=(null===(e=null===(t=this.options)||void 0===t?void 0:t.styles)||void 0===e?void 0:e.buttonColor)||"black",u=(null===(o=null===(i=this.options)||void 0===i?void 0:i.styles)||void 0===o?void 0:o.buttonType)||"long",h=(null===(s=null===(n=this.options)||void 0===n?void 0:n.styles)||void 0===s?void 0:s.buttonSizeMode)||"fill",v=(null===(r=null===(a=this.options)||void 0===a?void 0:a.styles)||void 0===r?void 0:r.buttonLocale)||void 0;this.googleButton=this.client.createButton({buttonColor:c,buttonType:u,buttonSizeMode:h,buttonLocale:v,onClick:async()=>{var t,e,i;if(null===(e=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===e?void 0:e.onPaymentButtonClicked){if(!await(null===(i=this.options)||void 0===i?void 0:i.events.onPaymentButtonClicked()))return}this.onPaymentButtonClicked()},allowedPaymentMethods:this.execution.googlePayConfig}),this.element.appendChild(this.googleButton)}catch(t){throw console.error("Google pay can not be initialized",t),new Error(t.message)}}async onLoadPaymentData(t){var e,i,o,n;const s=[{paymentMethodCode:"googlePay",integrationType:"api",paymentInstrumentData:{paymentToken:t.paymentMethodData.tokenizationData.token},amount:this.sdkConfig.amount}],a=await this.paymentExecutor.pay(s);(null===(i=null===(e=this.options)||void 0===e?void 0:e.events)||void 0===i?void 0:i.onAuthorizeSuccess)&&(null===(n=null===(o=this.options)||void 0===o?void 0:o.events)||void 0===n||n.onAuthorizeSuccess(a))}async onPaymentButtonClicked(){var t,e,i,o,n;const s=Object.assign({},L);if(s.allowedPaymentMethods=this.execution.googlePayConfig,s.transactionInfo={totalPriceStatus:"FINAL",totalPrice:null===(t=this.sdkConfig.amount)||void 0===t?void 0:t.value,currencyCode:null===(e=this.sdkConfig.amount)||void 0===e?void 0:e.currency,countryCode:null===(n=null===(o=null===(i=this.execution.meta)||void 0===i?void 0:i.customer)||void 0===o?void 0:o.country)||void 0===n?void 0:n.code},!this.client)throw new Error("Google pay client is not initialized");this.client.loadPaymentData(s).then((t=>{this.onLoadPaymentData(t)})).catch((t=>{var e,i,o;(null===(i=null===(e=this.options)||void 0===e?void 0:e.events)||void 0===i?void 0:i.onAuthorizeFailed)&&(null===(o=this.options)||void 0===o||o.events.onAuthorizeFailed(t))}))}mount(t){super.mount(t),this.loadScript?this.googleButton&&this.element.appendChild(this.googleButton):(this.loadScript=new j(this.sdkLoaded.bind(this)),this.loadScript.mount("body"))}unmount(){var t;this.googleButton&&(null===(t=this.googleButton.parentElement)||void 0===t||t.removeChild(this.googleButton)),super.unmount()}}class j extends e{constructor(t){super("script"),this.loaded=!1,this.loaded||(this.element.setAttribute("async","async"),this.element.setAttribute("src","https://pay.google.com/gp/p/js/pay.js"),this.element.setAttribute("onload","onPayrailsGpayLoaded()"),window.onPayrailsGpayLoaded=()=>{this.loaded||(this.loaded=!0,t())})}}class M extends z{constructor(t,e,i){var o;super("google-pay-dropin",(null===(o=i.translations)||void 0===o?void 0:o.label)||"Google Pay"),this.component=new D(t,e,i)}}class N extends z{constructor(t,e,i){super(`card-${t.id}`,`****${t.data.suffix}`,{onActivate:()=>{i(t),this.component.setDisabled(!1)}}),this.component=e}}class $ extends e{constructor(t,e,i,o){var n,s;super("fieldset",{id:"payrails-dropin-component"}),this.collectContainer=t,this.dropinConfig=e,this.execution=i,this.sdkConfig=o;const a=!1===(null===(s=null===(n=this.dropinConfig.paymentMethodsConfiguration)||void 0===n?void 0:n.cards)||void 0===s?void 0:s.showExistingCards),r=new Map;this.execution.availablePaymentMethods.forEach((({paymentMethodCode:t})=>{if(t===P.CARD)a||this.execution.savedCreditCards.forEach((t=>{var e;this.cardPaymentButton=this.createCardPaymentButton(null===(e=this.dropinConfig.translations)||void 0===e?void 0:e.cardPaymentButton);const i=new N(t,this.cardPaymentButton,(t=>{this.cardPaymentButton&&(this.cardPaymentButton.selectedCard=t)}));r.set(i.identifier,i)}))})),this.execution.availablePaymentMethods.forEach((({paymentMethodCode:t})=>{var e,i;switch(t){case P.CARD:this.creditCard=new I(this.createCardForm(),this.createCardPaymentButton(null===(e=this.dropinConfig.translations)||void 0===e?void 0:e.cardPaymentButton)),r.set(this.creditCard.identifier,this.creditCard);break;case P.GOOGLE_PAY:this.googlePay=new M(this.sdkConfig,this.execution,{events:{onAuthorizeSuccess:t=>{var e;if(t)if("authorizeSuccessful"===(null===(e=null==t?void 0:t.finalState)||void 0===e?void 0:e.code))this.onAuthorizeSuccess();else this.onAuthorizeFailed()},onAuthorizeFailed:this.onAuthorizeFailed.bind(this),onPaymentButtonClicked:this.dropinConfig.events.onPaymentButtonClicked},styles:null===(i=this.dropinConfig.styles)||void 0===i?void 0:i.googlePayButton}),r.set(this.googlePay.identifier,this.googlePay)}})),this.element.addEventListener("change",(t=>{var e,i;const o=(null===(e=null==t?void 0:t.target)||void 0===e?void 0:e.value)||"";r.forEach((t=>{t.deactivate()})),null===(i=r.get(o))||void 0===i||i.activate()})),this.subElements.push(...Array.from(r.values()))}createCardForm(){var t,e;if(!this.cardForm){const i=null===(t=this.dropinConfig.paymentMethodsConfiguration)||void 0===t?void 0:t.cards,o=Boolean(null==i?void 0:i.showStoreInstrumentCheckbox),n=Boolean(null==i?void 0:i.showCardHolderName),s=Boolean(null==i?void 0:i.alwaysStoreInstrument);this.cardForm=new d(this.collectContainer,{showStoreInstrumentCheckbox:o,showCardHolderName:n,alwaysStoreInstrument:s,translations:null===(e=this.dropinConfig.translations)||void 0===e?void 0:e.cardForm,events:{onFocus:()=>{var t;null===(t=this.creditCard)||void 0===t||t.activate()},onChange:({isValid:t})=>{var e;null===(e=this.cardPaymentButton)||void 0===e||e.setDisabled(!t)}}})}return this.cardPaymentButton&&this.cardPaymentButton.setCardForm(this.cardForm),this.cardForm}createCardPaymentButton(t){return this.cardPaymentButton||(this.cardPaymentButton=new B(this.sdkConfig,this.execution,{translations:t,events:{onAuthorizeSuccess:this.onAuthorizeSuccess.bind(this),onAuthorizeFailed:this.onAuthorizeFailed.bind(this),onPaymentButtonClicked:this.dropinConfig.events.onPaymentButtonClicked}})),this.cardForm&&this.cardPaymentButton.setCardForm(this.cardForm),this.cardPaymentButton}onAuthorizeSuccess(){var t,e,i,o;this.subElements.forEach((t=>t.unmount())),new F({translations:{label:null===(i=null===(e=null===(t=this.dropinConfig)||void 0===t?void 0:t.translations)||void 0===e?void 0:e.paymentResult)||void 0===i?void 0:i.success}}).mount(`#${this.id}`),(null===(o=this.dropinConfig.events)||void 0===o?void 0:o.onAuthorizeSuccess)&&this.dropinConfig.events.onAuthorizeSuccess()}onAuthorizeFailed(){var t,e,i;new R(null===(e=null===(t=this.dropinConfig.translations)||void 0===t?void 0:t.paymentResult)||void 0===e?void 0:e.fail).mount(`#${this.id}`),this.dropinConfig.events.onAuthorizeFailed&&(null===(i=this.dropinConfig.events)||void 0===i||i.onAuthorizeFailed())}}var V=require("skyflow-js").default;class H{constructor(t,e){this.__container=t.container(V.ContainerType.COMPOSABLE,e)}get elementToFieldMap(){return new Map([[exports.ElementType.CARD_NUMBER,"card_number"],[exports.ElementType.CARDHOLDER_NAME,"cardholder_name"],[exports.ElementType.CVV,"security_code"],[exports.ElementType.EXPIRATION_MONTH,"expiry_month"],[exports.ElementType.EXPIRATION_YEAR,"expiry_year"]])}createCollectElement(t){return this.__container.create(Object.assign({table:"cards",labelStyles:{},errorTextStyles:{},column:this.elementToFieldMap.get(t.type)},t),{format:t.format})}mount(t){const e="payrails-container-wrapper";this.element=document.createElement("span"),this.element.setAttribute("id",e);const i=document.querySelector(t);if(!i)throw new Error(`Element with selector ${t} does not exist`);i.appendChild(this.element),window.setTimeout((()=>{this.__container.mount(`#${e}`)}),50)}unmount(){this.element&&this.element.remove()}async collect(){const{records:t}=await this.__container.collect(),{skyflow_id:e,card_number:i,cardholder_name:o,expiry_month:n,expiry_year:s}=t[0].fields;return{instrumentId:e,card_number:i,cardholder_name:o,expiry_month:n,expiry_year:s}}}var U=require("skyflow-js").default;class G{static init(t,e){const i=JSON.parse(atob(t.data)),{vaultConfiguration:{vaultId:o,vaultUrl:n,token:s},execution:a}=i,r=U.init({vaultID:o,vaultURL:n,getBearerToken:()=>Promise.resolve(s)});return new G(i,r,new O(a),e)}update(t,e){this.execution.update(t),this.sdkConfiguration.amount=e}collectContainer(t){if(!t.layout)throw new Error("Layout configuration is required");return this.__container=new H(this.vaultClient,t),this.__container}googlePayButton(t){var e;if(!this.execution)throw new Error("SDK was not initialized with workflow execution");return new D(this.sdkConfiguration,this.execution,Object.assign({environment:null===(e=this.options)||void 0===e?void 0:e.environment},t))}cardList(t){return this.__cardList||(this.__cardList=new h(this.execution,{onCardChange:e=>{this.__cardPaymentButton&&(this.__cardPaymentButton.selectedCard=e,this.__cardPaymentButton.setDisabled(!1)),null==t||t.onCardChange(e)}})),this.__cardList}cardForm(t){var e,i;if(!this.__cardForm){const o=this.getContainerLayout(null==t?void 0:t.showCardHolderName);this.__container=this.collectContainer(Object.assign(Object.assign({layout:o,errorTextStyles:{base:{display:"none"}}},null===(e=null==t?void 0:t.styles)||void 0===e?void 0:e.errorTextStyles),{styles:{base:null===(i=null==t?void 0:t.styles)||void 0===i?void 0:i.base}})),this.__cardForm=new d(this.__container,Object.assign(Object.assign({},t),{events:Object.assign(Object.assign({},null==t?void 0:t.events),{onChange:e=>{var i;this.__cardPaymentButton&&(this.__cardPaymentButton.selectedCard=null,this.__cardForm&&this.__cardPaymentButton.setDisabled(!this.__cardForm.isValid)),(null===(i=null==t?void 0:t.events)||void 0===i?void 0:i.onChange)&&t.events.onChange(e)},onFocus:()=>{var e;this.__cardList&&this.__cardList.reset(),this.__cardPaymentButton&&(this.__cardPaymentButton.selectedCard=null,this.__cardForm&&this.__cardPaymentButton.setDisabled(!this.__cardForm.isValid)),(null===(e=null==t?void 0:t.events)||void 0===e?void 0:e.onFocus)&&t.events.onFocus()}})}))}return this.__cardPaymentButton&&this.__cardPaymentButton.setCardForm(this.__cardForm),this.__cardForm}constructor(t,e,i,o){var n;this.sdkConfiguration=t,this.vaultClient=e,this.execution=i,this.options=o,(null===(n=null==o?void 0:o.events)||void 0===n?void 0:n.onClientInitialized)&&o.events.onClientInitialized(this.execution)}dropin(t){var e,i;const o=this.getContainerLayout(null===(i=null===(e=t.paymentMethodsConfiguration)||void 0===e?void 0:e.cards)||void 0===i?void 0:i.showCardHolderName);return this.__container=this.collectContainer({layout:o,errorTextStyles:{base:{display:"none"}}}),new $(this.__container,t,this.execution,this.sdkConfiguration)}getContainerLayout(t){return t?[1,1,3]:[1,3]}paymentButton(t){return this.__cardPaymentButton||(this.__cardPaymentButton=new B(this.sdkConfiguration,this.execution,t)),this.__cardPaymentButton.setDisabled(!0),this.__cardForm&&this.__cardPaymentButton.setCardForm(this.__cardForm),this.__cardPaymentButton}}exports.Payrails=G}();
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payrails/web-sdk",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.7",
|
|
4
4
|
"description": "SDK providing tokenization options on the client for merchants",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "payrails.d.ts",
|
|
7
7
|
"type": "commonjs",
|
|
8
8
|
"scripts": {},
|
|
9
9
|
"author": "Petr Prchal <petr@payrails.com>",
|
|
10
|
-
"license": "
|
|
10
|
+
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"skyflow-js": "1.25.0"
|
|
13
13
|
}
|