-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathebanx-1.8.1.min.js
46 lines (42 loc) · 19.1 KB
/
ebanx-1.8.1.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* EBANX Pay Lib JS for local payments
* Bundle of @ebanx/lib-js-local
* Generated: 2020-09-15
* Version: 1.7.3
*/
/**
* The MIT License
*
* Copyright (c) 2010-current EBANX Pay, https://www.ebanxpay.com/br
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).EBANX=t()}(this,(function(){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */var e=function(t,r){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(t,r)};function t(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{u(n.next(e))}catch(e){i(e)}}function s(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){e.done?o(e.value):new r((function(t){t(e.value)})).then(a,s)}u((n=n.apply(e,t||[])).next())}))}function r(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}function n(e){return t(this,void 0,void 0,(function(){var t,n;return r(this,(function(r){switch(r.label){case 0:return t=new URL("/ws/threedsecureserver-generateToken",EBANX.utils.api.path()),n={totalAmount:e.totalAmount,currency:e.currency,orderNumber:null,consumerAuthenticationInformation:{overridePaymentMethod:"DEBIT"}},[4,fetch(t.toString(),{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify(n)})];case 1:return[4,r.sent().json()];case 2:return[2,r.sent().data[0]]}}))}))}function o(e,n,o,i,a){return void 0===a&&(a="1"),t(this,void 0,void 0,(function(){var t,s;return r(this,(function(r){switch(r.label){case 0:return t={token:e.accessToken,merchantTrackId:e.paymentId,additionalData:JSON.stringify({publicIntegrationKey:EBANX.config.getPublishableKey()}),orderInformation:n,consumerAuthenticationInformation:{installmentTotalCount:a,overridePaymentMethod:"DEBIT"},personalIdentification:i,paymentInformation:o},s=new URL("/ws/threedsecureserver-authentications",EBANX.utils.api.path()),[4,fetch(s.toString(),{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify(t)})];case 1:return[4,r.sent().json()];case 2:return[2,r.sent().data[0]]}}))}))}function i(e,n,o,i){return t(this,void 0,void 0,(function(){var t,a;return r(this,(function(r){switch(r.label){case 0:return t=new URL("/ws/threedsecureserver-authentication-results",EBANX.utils.api.path()),a={token:e.accessToken,tokenChallenge:i,merchantTrackId:e.paymentId,paymentInformation:o,consumerAuthenticationInformation:{overridePaymentMethod:"DEBIT"},orderInformation:n},[4,fetch(t.toString(),{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify(a)})];case 1:return[4,r.sent().json()];case 2:return[2,r.sent().data[0]]}}))}))}function a(e,n){var o;return t(this,void 0,void 0,(function(){return r(this,(function(t){return null===(o=document.getElementById("Cardinal-ElementContainer"))||void 0===o||o.remove(),Cardinal.configure({timeout:"8000",maxRequestRetries:"10",logging:{level:"off"},payment:{view:"modal",framework:"boostrap3",displayLoading:!0,displayExitButton:!0}}),Cardinal.setup("init",{jwt:e.accessToken}),Cardinal.on("payments.setupComplete",(function(){Cardinal.trigger("bin.process",n)})),[2]}))}))}var s=function(t){function r(e){var n=t.call(this,e)||this;return Error.captureStackTrace(n,n.constructor),Object.setPrototypeOf(n,r.prototype),n}return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(r,t),r}(Error);function u(e){var t=e.consumerAuthenticationInformation,r=t.eci,n=t.eciRaw;if(r)return r;if(n)return n;throw new s}function c(e){var t=e.consumerAuthenticationInformation,r=t.ucaf,n=t.ucafAuthenticationData;if(r)return r;if(n)return n;throw new s}function l(e){return e.consumerAuthenticationInformation.pareq}function d(e){return e.consumerAuthenticationInformation.authenticationTransactionId}function f(e){return e.consumerAuthenticationInformation.version}function h(e){return e.consumerAuthenticationInformation.directoryServerTransactionId}function p(e){var t;return Cardinal.continue("cca",{AcsUrl:(t=e,t.consumerAuthenticationInformation.acsUrl),Payload:l(e)},{OrderDetails:{TransactionId:d(e)}}),new Promise((function(e,t){setTimeout((function(){return t(new Error("Waited too much for payment validation"))}),6e4),Cardinal.on("payments.validated",(function(r,n){n?e(n):t(new s("Error to validate payment"))}))}))}function v(e){if("AUTHENTICATION_SUCCESSFUL"!==e.status)throw new s(e.status);return{threeds_eci:u(e),threeds_cryptogram:c(e),threeds_xid:(t=e,t.consumerAuthenticationInformation.xid),threeds_version:f(e),threeds_trxid:h(e)};var t}var m=Object.freeze({__proto__:null,run:function(e){var s=e.orderInformation,u=e.paymentInformation,c=e.personalIdentification,l=e.installmentTotalCount,d=void 0===l?"1":l;return t(this,void 0,void 0,(function(){function e(e,n){return t(this,void 0,void 0,(function(){var t,o;return r(this,(function(r){switch(r.label){case 0:return[4,p(n)];case 1:return t=r.sent(),o=v,[4,i(e,s,u,t)];case 2:return[2,o.apply(void 0,[r.sent()])]}}))}))}function l(e){return t(this,void 0,void 0,(function(){var t;return r(this,(function(r){switch(r.label){case 0:return t=v,[4,i(e,s,u)];case 1:return[2,t.apply(void 0,[r.sent()])]}}))}))}var f,h;return r(this,(function(t){switch(t.label){case 0:return[4,n(s.amountDetails)];case 1:return[4,a(f=t.sent(),u.card)];case 2:return t.sent(),[4,o(f,s,u,c,d)];case 3:switch((h=t.sent()).status){case"PENDING_AUTHENTICATION":return[2,e(f,h)];case"VALIDATION_NEEDED":return[2,l(f)];case"AUTHENTICATION_FAILED":case"AUTHENTICATION_SUCCESSFUL":default:return[2,v(h)]}return[2]}}))}))},getCardType:function(e){switch(e){case"visa":return"001";case"mastercard":return"002";case"maestro":return"042";case"elo":return"054";default:throw new s("Schema not mapped")}},checkIfShouldAuthenticate:function(e){return t(this,void 0,void 0,(function(){var t,n;return r(this,(function(r){return t=["506722","509023","509030","509105"],n=e.paymentInformation.card.number.substr(0,6),[2,!t.includes(n)]}))}))}}),y={"BP-DR-101":"¡Lo sentimos!, vuelva a intentarlo con otra tarjeta.","BP-DR-102":"¡Ups!, algo salió mal, vuelve a intentarlo con otra tarjeta.","BP-DR-76":"País não informado.","BP-DR-77":"País não permitido.","BP-DR-75":"El número de la tarjeta es invalido. Confirma si no hay un error de escritura y vuelva a intentarlo.","BP-DR-S-75":"El bandera de tarjeta de crédito es inválido.","BP-DR-51":"¡Ups!, faltó llenar este campo. Llénalo con el nombre que aparece en tu tarjeta.","BP-DR-55":"El código de tarjeta de crédito es inválido.","BP-DR-57":"Por favor, escribe la fecha en el formato MM/AAAA.","BP-DR-M-57":"El mes de tarjeta de crédito es inválido.","BP-DR-Y-57":"El año de tarjeta de crédito es inválido."},g={"BP-DR-101":"Ops! Esse cartão não está liberado para fazer compras na internet. Entre em contato com o seu banco para mais informações.","BP-DR-102":"Ops, algo deu errado. Tente novamente com outro cartão.","BP-DR-76":"País não informado.","BP-DR-77":"País não permitido.","BP-DR-75":"O número do cartão informado é inválido. Confira se não houve um erro de digitação e tente de novo.","BP-DR-S-75":"A bandeira do cartão de crédito é inválida.","BP-DR-51":"Ei, faltou uma informação aqui! Preencha com o nome que aparece em seu cartão.","BP-DR-55":"O código do cartão de crédito é inválido.","BP-DR-57":"A data do cartão de crédito deve estar no formato mes/ano, por exemplo, 12/2020.","BP-DR-M-57":"O mês data do cartão de crédito é inválido.","BP-DR-Y-57":"O ano data do cartão de crédito é inválido."};const b=function(){var e={},t={country:"",mode:"test",publicKey:""};if(e.config={isLive:function(){return"production"===t.mode},setPublishableKey:function(e){t.publicKey=String(e)},setCountry:function(e){b.validator.config.validateCountry(e),t.country=String(e)},setMode:function(e){b.validator.config.validateMode(e),t.mode=e},getMode:function(){return t.mode},getPublishableKey:function(){if(""===t.publicKey.trim())throw new b.errors.InvalidConfigurationError("Missing publishable key. You need set publishable key using the method EBANX.config.setPublishableKey.","publicKey");return t.publicKey},getCountry:function(){return t.country||(t.country="br"),t.country},getLocale:function(){return{br:"pt_BR",mx:"es",co:"es",ar:"es"}[b.config.getCountry()]}},e.config.isLive()&&"https:"!==location.protocol)throw"EBANXInvalidConfigurationError: Your protocol needs to be https.";return e}();var w,P;return b.errors={summary:{pt_BR:g,es:y},InvalidValueFieldError:function(e,t){this.message=b.errors.summary[b.config.getLocale()][e]||e,this.field=t,this.name="InvalidValueFieldError"},InvalidConfigurationError:function(e,t){this.message=b.errors.summary[b.config.getLocale()][e]||e,this.invalidConfiguration=t,this.name="InvalidConfigurationError"}},b.validator=(w={publicKey:{}},{config:{validatePublishableKey:function(e,t){var r=b.utils.api.resources.validPublicIntegrationKey();w.publicKey[e]?t(w.publicKey[e]):b.http.ajax.request({url:r.url,method:r.method,raw:!0,data:{public_integration_key:e}}).always((function(r){w.publicKey[e]=r,t(r)}))},validateCountry:function(e){if(-1===b.utils.availableCountries.indexOf(e))throw new b.errors.InvalidValueFieldError("BP-DR-77","country")},validateMode:function(e){if(null===e.match(/^(test|production)$/))throw new b.errors.InvalidConfigurationError('Invalid mode, please, use "test" or "production" as test mode.',"mode")}},card:{validateNumber:function(e){if(!this.luhnAlgCheck(String(e)))throw new b.errors.InvalidValueFieldError("BP-DR-75","card_number")},validateName:function(e){if("string"!=typeof e||0===e.length||null!==e.match(/[0-9]+/))throw new b.errors.InvalidValueFieldError("BP-DR-51","card_name")},luhnAlgCheck:function(e){var t,r,n,o;for(n=+e[t=e.length-1],o=0;t--;)r=+e[t],n+=++o%2?2*r%10+(r>4):r;return n%10==0},validateCvv:function(e){var t=new RegExp("^[0-9]{3,4}$");if(!String(e).match(t))throw new b.errors.InvalidValueFieldError("BP-DR-55","card_cvv")},validateDueDate:function(e){var t=(e+"").split("/");if(t={now:new Date,year:t[1],month:t[0]},!0!==/^\d+$/.test(t.month)||parseInt(t.month,10)<=12!=1)throw new b.errors.InvalidValueFieldError("BP-DR-M-57","card_due_date");if(!/^\d+$/.test(t.year))throw new b.errors.InvalidValueFieldError("BP-DR-Y-57","card_due_date");if(t.expiration=new Date(t.year,t.month),t.expiration.setMonth(t.expiration.getMonth()-1),t.expiration.setMonth(t.expiration.getMonth()+1,1),t.expiration>t.now!=1)throw new b.errors.InvalidValueFieldError("BP-DR-57","card_due_date")},validate:function(e){this.validateName(e.card_name),this.validateNumber(e.card_number),this.validateDueDate(e.card_due_date),this.validateCvv(e.card_cvv)}}}),b.tokenize={card:{token:function(e,t,r){var n=b.utils.api.resources.createToken();b.http.ajax.request({url:n.url,method:n.method,data:JSON.stringify({public_integration_key:b.config.getPublishableKey(),payment_type_code:b.utils.creditCardScheme(e.card_number),country:b.config.getCountry(),card:e})}).always((function(e){return"ERROR"!==e.status&&"token"in e?t(e):r(e)}))}}},b.utils=((P={api:{path:function(){return b.config.isLive()?"https://api.ebanx.com.br/":"https://staging.ebanx.com.br/"}},availableCountries:["br","mx","co","ar","pe","cl","ec","bo"].join(", "),creditCardScheme:function(e){b.validator.card.validateNumber(e);var t={br:{aura:/^50[0-9]{14,17}$/,elo:/^(4011|438935|45(1416|76|7393)|50(4175|6699|67|90[4-7])|63(6297|6368))/,diners:/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,discover:/^6(?:011|5[0-9]{2})[0-9]{12}$/,hipercard:/^(38|60)[0-9]{11,17}$/},mx:{carnet:/^5[0-9][0-9]{14}$/,mastercard__2:/^2[2-7][0-9]{14}$/},co:{diners:/^36[0-9]{12}$/},ar:{mastercard__all:/^[0-9]{16}$/},cl:{magna:/^(568009)/},all:{amex:/^3[47][0-9]{13}$/,mastercard:/^5[1-5][0-9]{14}$/,visa:/^4[0-9]{12}(?:[0-9]{3})?$/}},r={};for(var n in t[b.config.getCountry()])r[n]=t[b.config.getCountry()][n];for(var n in t.all)r[n]=t.all[n];for(var o in r)if(r[o].test(e)){var i=o,a=o.indexOf("__");return-1!==a&&(i=o.substr(0,a)),i}throw new b.errors.InvalidValueFieldError("BP-DR-S-75","card_number")}}).api.url=function(){return P.api.path()+"ws"},P.api.resources={createToken:function(){return{url:P.api.url()+"/token",method:"post"}},validPublicIntegrationKey:function(){return{url:P.api.url()+"/merchantIntegrationProperties/isValidPublicIntegrationKey",method:"get"}},fingerPrintResource:function(){return{url:P.api.path()+"fingerprint/",method:"get"}},fingerPrintProvidersResource:function(){return{url:P.api.path()+"fingerprint/provider",method:"get"}}},P),b.http={normalize:{q:function(e,t){var r=function e(t,r){var n=[];return r=r||[],Object.keys(t).forEach((function(o){if(t.hasOwnProperty(o)){var i=r.slice();i.push(o);var a=[];"object"==typeof t[o]?a=e(t[o],i):a.push({path:i,val:t[o]}),a.forEach((function(e){return n.push(e)}))}})),n}(e),n=(r=r.map((function(e){if(1==e.path.length)e.path=e.path[0];else{var t=e.path[0],r=e.path.slice(1);e.path=t+"["+r.join("][")+"]"}return e}))).map((function(e){return e.path+"="+e.val})).join("&");return t?encodeURIComponent(n):n}},ajax:{request:function(e){return"string"==typeof e&&(e={url:e}),e.url=e.url||"",e.method=e.method||"get",e.data=e.data||{},{host:{},process:function(e){var t=this;return this.xhr=null,window.ActiveXObject?this.xhr=new window.ActiveXObject("Microsoft.XMLHTTP"):window.XMLHttpRequest&&(this.xhr=new XMLHttpRequest),this.xhr&&(this.xhr.onreadystatechange=function(){var r=t.xhr.responseText||"{}";if(4==t.xhr.readyState){try{void 0===e.raw&&"undefined"!=typeof JSON&&(r=JSON.parse(r))}catch(e){r={}}t.alwaysCallback&&t.alwaysCallback.apply(t.host,[r,t.xhr])}}),"GET"==e.method.toUpperCase()&&(e.url+="?"+b.http.normalize.q(e.data),delete e.data),this.xhr.open(e.method.toUpperCase(),e.url,!0),setTimeout((function(){t.xhr.send(e.data)}),20),this},always:function(e){return this.alwaysCallback=e,this}}.process(e)}},injectJS:function(e,t){let r=document.createElement("script");r.type="text/javascript",r.async=!0,r.onload=t,r.src=e,document.getElementsByTagName("head")[0].appendChild(r)}},b.card={createToken:function(e,t){var r={data:{},error:{}},n=function(e){r.data=e,b.deviceFingerprint.setup((function(e){return r.data.deviceId=e,t(r)}),(function(e){return r.data.deviceId="",t(r)}))},o=function(e){return r.error.err=e,t(r)},i="";try{i=b.config.getPublishableKey()}catch(e){r.error.err=e,t(r)}b.validator.config.validatePublishableKey(i,(function(i){var a=JSON.parse(i);if(!a.success)return r.error.err={status:"ERROR",status_code:"",status_message:a.body.error},void t(r);try{b.validator.card.validate(e),b.tokenize.card.token(e,n,o)}catch(e){r.error.err=e,t(r)}}))}},b.deviceFingerprint={ebanxSessionId:null,providerSessionList:[],postProvidersRemaining:0,onSuccessCallback:null,onErrorCallback:null,setup:function(e,t){this.onSuccessCallback=e||console.log,this.onErrorCallback=t||console.error,this.getList(function(e){try{if(!e)throw new Error("EBANX.deviceFingerprint.setup - providersList is missing");if(!e.ebanx_session_id)throw new Error("EBANX.deviceFingerprint.setup - ebanx_session_id is missing");if(!e.providers||!e.providers.length)return this.onSuccessCallback(e.ebanx_session_id);this.ebanxSessionId=e.ebanx_session_id,this.postProvidersRemaining=e.providers.length,e.providers.forEach(function(e){this.loadProvider(e,this.saveProviderSessionList.bind(this))}.bind(this))}catch(e){this.onErrorCallback(e)}}.bind(this))},getList:function(e){b.http.ajax.request({url:b.utils.api.resources.fingerPrintResource().url,data:{publicIntegrationKey:b.config.getPublishableKey(),country:b.config.getCountry()}}).always(e)},saveProviderSessionList:function(e){this.postProvidersRemaining--,this.providerSessionList.push(e),this.postProvidersRemaining||this.postProviderSessionList()},postProviderSessionList:function(){var e=this.ebanxSessionId,t=this.providerSessionList,r=this.onSuccessCallback,n=this.onErrorCallback;this.ebanxSessionId=null,this.providerSessionList=[],this.onSuccessCallback=null,this.onErrorCallback=null;var o={publicIntegrationKey:b.config.getPublishableKey(),ebanx_session_id:e,providers:t},i=b.utils.api.resources.fingerPrintProvidersResource();b.http.ajax.request({url:i.url,method:i.method,data:o}).always((function(t,o){200==o.status?r(e):n(new Error("postProviderSessionList - xhr.status != 200, received value: "+o.status))}))},loadProvider:function(e,t){b.http.injectJS(e.source,(function(){b.deviceFingerprint[e.provider].setup(e.settings,(function(r){t({provider:e.provider,session_id:r})}))}))}},Object.assign(b,{threedsecure:m}),b}));