diff --git a/assets/animations/new_notification.gif b/assets/animations/new_notification.gif new file mode 100644 index 0000000..07708f7 Binary files /dev/null and b/assets/animations/new_notification.gif differ diff --git a/assets/css/style.css b/assets/css/style.css new file mode 100644 index 0000000..9f5dbb6 --- /dev/null +++ b/assets/css/style.css @@ -0,0 +1,49 @@ +li.wc_payment_method.payment_method_woocommerce_wompi_pse > label[for=payment_method_woocommerce_wompi_pse] > img { + margin-left: 6px; + margin-top: -7px; + max-height: 40px; +} + +li.wc_payment_method.payment_method_woocommerce_wompi_credit_cards > label[for=payment_method_woocommerce_wompi_credit_cards] > img { + margin-left: 6px; + margin-top: -7px; + max-height: 40px; +} + +li.wc_payment_method.payment_method_payulatam_co > label[for=payment_method_payulatam_co] > img { + margin-left: 6px; + margin-top: -7px; + max-height: 40px; +} + +li.wc_payment_method.payment_method_woocommerce_wompi_cash_bancolombia > label[for=payment_method_woocommerce_wompi_cash_bancolombia] > img { + margin-left: 6px; + margin-top: -7px; + max-height: 40px; +} + +li.wc_payment_method.payment_method_woocommerce_wompi_bancolombia_button > label[for=payment_method_woocommerce_wompi_bancolombia_button] > img { + margin-left: 6px; + margin-top: -7px; + max-height: 40px; +} +li.wc_payment_method.payment_method_woocommerce_wompi_nequi > label[for=payment_method_woocommerce_wompi_nequi] > img { + margin-left: 6px; + margin-top: -7px; + max-height: 40px; +} + +div.card-js > .installments-wrapper > select { + padding-left: 10px; +} + +.card-js .installments-wrapper { + -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.7), inset 0 1px 0 rgba(255,255,255,.7); + -moz-box-shadow: 0 1px 0 rgba(255,255,255,.7),inset 0 1px 0 rgba(255,255,255,.7); + -ms-box-shadow: 0 1px 0 rgba(255,255,255,.7),inset 0 1px 0 rgba(255,255,255,.7); + -o-box-shadow: 0 1px 0 rgba(255,255,255,.7),inset 0 1px 0 rgba(255,255,255,.7); + box-shadow: 0 1px 0 rgba(255,255,255,.7), inset 0 1px 0 rgba(255,255,255,.7); + position: relative; + display: inline-block; + width: 100%; +} \ No newline at end of file diff --git a/assets/js/wompi-payments-plugin-card-js.js b/assets/js/wompi-payments-plugin-card-js.js new file mode 100644 index 0000000..79ec5ee --- /dev/null +++ b/assets/js/wompi-payments-plugin-card-js.js @@ -0,0 +1,50 @@ +(function($){ + 'use strict'; + $( 'body' ).on( 'updated_checkout', function() { + $(".card-js").CardJs(); + } ); + + + var checkout_form = $( 'form.checkout' ); + + $(document.body).on('checkout_error', function () { + swal.close(); + Cookies.remove('woocommerce_wompi_credit_cards_intent'); + }); + + checkout_form.on( 'checkout_place_order', function() { + + var form_checkout_payment = $('form[name="checkout"] input[name="payment_method"]:checked'); + + if(form_checkout_payment.val() === 'woocommerce_wompi_credit_cards'){ + + if( typeof Cookies.get('woocommerce_wompi_credit_cards_intent') === 'undefined' ){ + var inFiveMinutes = new Date(new Date().getTime() + 5 * 60 * 1000); + Cookies.set('woocommerce_wompi_credit_cards_intent', 0, { expires: inFiveMinutes, path: '/' }) + } + + //Sweetalert to show the loading spinner + Swal.fire({ + title: 'Procesando tu pago', + html: 'Por favor espera un momento...', + imageWidth: "200px", + timerProgressBar: true, + allowOutsideClick: false, + allowEscapeKey: false, + allowEnterKey: false, + showCancelButton: false, + showConfirmButton: false, + showCloseButton: false, + didOpen: () => { + Swal.showLoading(); + } + }) + } + }); + + + + +})(jQuery); + + diff --git a/assets/js/wompi-payments-plugin-core.js b/assets/js/wompi-payments-plugin-core.js new file mode 100644 index 0000000..77272cf --- /dev/null +++ b/assets/js/wompi-payments-plugin-core.js @@ -0,0 +1,10 @@ +(function($){ + 'use strict'; + if( typeof Cookies.get('wompi_sessionId') === 'undefined' ){ + $wompi.initialize( function ( data, error ) { + if ( error === null ) { + Cookies.set('wompi_sessionId', data.sessionId, { expires: 90, path: '/' }) + } + }) + } +})(jQuery); \ No newline at end of file diff --git a/assets/js/wompi-payments-plugin-nequi.js b/assets/js/wompi-payments-plugin-nequi.js new file mode 100644 index 0000000..a76e8b8 --- /dev/null +++ b/assets/js/wompi-payments-plugin-nequi.js @@ -0,0 +1,54 @@ +;(function( $ ) { + 'use strict'; + + const checkout_form = $( 'form.checkout' ); + + $(document.body).on('checkout_error', function () { + swal.close(); + }); + + checkout_form.on( 'checkout_place_order', function() { + + const form_checkout_payment = $('form[name="checkout"] input[name="payment_method"]:checked'); + + if(form_checkout_payment.val() === 'woocommerce_wompi_nequi'){ + + Swal.fire({ + title: 'Verifica tu celular', + html: wompi_payments_plugin_nequi.check_your_phone_msg, + imageUrl: wompi_payments_plugin_nequi.logo_url, + imageWidth: "200px", + timer: wompi_payments_plugin_nequi.seconds_to_wait * 1000, + timerProgressBar: true, + allowOutsideClick: false, + allowEscapeKey: false, + allowEnterKey: false, + showCancelButton: false, + showConfirmButton: false, + showCloseButton: false, + didOpen: () => { + Swal.showLoading(); + const timer = Swal.getPopup().querySelector("b"); + timerInterval = setInterval(() => { + const timerLeft = Swal.getTimerLeft(); + let minutes = Math.floor(timerLeft / 60000); + let seconds = Math.floor((timerLeft % 60000) / 1000); + + if(minutes < 10){ minutes = `0${minutes}`; } + if(seconds < 10){ seconds = `0${seconds}`; } + timer.textContent = `${minutes}:${seconds}`; + + }, 500); + }, + willClose: () => { + if(typeof timerInterval !== 'undefined'){ + clearInterval(timerInterval); + } + } + }) + } + }); + + + +})( jQuery ); \ No newline at end of file diff --git a/assets/libs/card-js/card-js.min.css b/assets/libs/card-js/card-js.min.css new file mode 100644 index 0000000..be2167f --- /dev/null +++ b/assets/libs/card-js/card-js.min.css @@ -0,0 +1 @@ +.card-js input.card-number{padding-right:48px}.card-js .card-number-wrapper .card-type-icon{height:23px;width:32px;position:absolute;display:block;right:8px;top:7px;background:url(https://cardjs.co.uk/img/cards.png) 0 23px no-repeat;pointer-events:none;opacity:0;-webkit-transition:opacity .15s linear;-moz-transition:opacity .15s linear;-ms-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.card-js .card-number-wrapper .show{opacity:1}.card-js .card-number-wrapper .card-type-icon.visa{background-position:0 0}.card-js .card-number-wrapper .card-type-icon.master-card{background-position:-32px 0}.card-js .card-number-wrapper .card-type-icon.american-express{background-position:-64px 0}.card-js .card-number-wrapper .card-type-icon.discover{background-position:-96px 0}.card-js .card-number-wrapper .card-type-icon.diners{background-position:-128px 0}.card-js .card-number-wrapper .card-type-icon.jcb{background-position:-160px 0}.card-js .cvc-container{width:50%;float:right}.card-js .cvc-wrapper{box-sizing:border-box;margin-left:5px}.card-js .cvc-wrapper .cvc{display:block;width:100%}.card-js .expiry-container{width:50%;float:left}.card-js .expiry-wrapper{box-sizing:border-box;margin-right:5px}.card-js .expiry-wrapper .expiry{display:block;width:100%}.card-js .expiry-wrapper .expiry-month{border-top-right-radius:0;border-bottom-right-radius:0;padding-left:30px}.card-js .expiry-wrapper .expiry-year{border-top-left-radius:0;border-bottom-left-radius:0;border-left:0}.card-js .expiry-wrapper .expiry-month,.card-js .expiry-wrapper .expiry-year{display:inline-block}.card-js .expiry-wrapper .expiry{padding-left:38px}.card-js .icon{position:absolute;display:block;width:24px;height:17px;left:8px;top:10px;pointer-events:none}.card-js .icon.right{right:8px;left:auto}.card-js .icon.popup{cursor:pointer;pointer-events:auto}.card-js .icon .svg{fill:#888}.card-js .icon.popup .svg{fill:#aaa!important}.card-js .card-number-wrapper,.card-js .name-wrapper{margin-bottom:15px;width:100%}.card-js .card-number-wrapper,.card-js .cvc-wrapper,.card-js .expiry-wrapper,.card-js .name-wrapper{-webkit-box-shadow:0 1px 0 rgba(255,255,255,.7),inset 0 1px 0 rgba(255,255,255,.7);-moz-box-shadow:0 1px 0 rgba(255,255,255,.7),inset 0 1px 0 rgba(255,255,255,.7);-ms-box-shadow:0 1px 0 rgba(255,255,255,.7),inset 0 1px 0 rgba(255,255,255,.7);-o-box-shadow:0 1px 0 rgba(255,255,255,.7),inset 0 1px 0 rgba(255,255,255,.7);box-shadow:0 1px 0 rgba(255,255,255,.7),inset 0 1px 0 rgba(255,255,255,.7);position:relative}.card-js .card-number-wrapper,.card-js .cvc-container,.card-js .expiry-container,.card-js .name-wrapper{display:inline-block}.card-js::after{content:' ';display:table;clear:both}.card-js input,.card-js select{color:#676767;font-size:15px;font-weight:300;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;height:36px;border:1px solid #d9d9d9;border-radius:4px;box-shadow:none;background-color:#FDFDFD;box-sizing:border-box;padding:0;-webkit-transition:border-color .15s linear,box-shadow .15s linear;-moz-transition:border-color .15s linear,box-shadow .15s linear;-ms-transition:border-color .15s linear,box-shadow .15s linear;-o-transition:border-color .15s linear,box-shadow .15s linear;transition:border-color .15s linear,box-shadow .15s linear}.card-js select{-moz-appearance:none;text-indent:.01px;text-overflow:''}.card-js input[disabled],.card-js select[disabled]{background-color:#eee;color:#555}.card-js select option[hidden]{color:#ABA9A9}.card-js input:focus,.card-js select:focus{background-color:#fff;outline:0;border-color:#66afe9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.card-js input[readonly=readonly]:not([disabled]),.card-js input[readonly]:not([disabled]){background-color:#fff;cursor:pointer}.card-js .has-error input,.card-js .has-error input:focus{border-color:#F64B2F;box-shadow:none}.card-js input.card-number,.card-js input.cvc,.card-js input.name{padding-left:38px;width:100%}.card-js.stripe .icon .svg{fill:#559A28} \ No newline at end of file diff --git a/assets/libs/card-js/card-js.min.js b/assets/libs/card-js/card-js.min.js new file mode 100644 index 0000000..aeaf761 --- /dev/null +++ b/assets/libs/card-js/card-js.min.js @@ -0,0 +1,696 @@ +(function($) { + function CardJs(elem) { + this.elem = jQuery(elem), + this.captureName = this.elem.data("capture-name") ? this.elem.data("capture-name") : !1, + this.captureInstallments = this.elem.data("capture-installments") ? this.elem.data("capture-installments") : !1, + this.iconColour = this.elem.data("icon-colour") ? this.elem.data("icon-colour") : !1, + this.stripe = this.elem.data("stripe") ? this.elem.data("stripe") : !1, + this.stripe && (this.captureName = !1), + this.initCardNumberInput(), + this.initNameInput(), + this.initExpiryMonthInput(), + this.initExpiryYearInput(), + this.initCvcInput(), + this.initInstallmentsInput(), + this.elem.empty(), + this.setupCardNumberInput(), + this.setupNameInput(), + this.setupExpiryInput(), + this.setupCvcInput(), + this.setupInstallmentsInput(), + this.iconColour && this.setIconColour(this.iconColour), + this.refreshCreditCardTypeIcon() + } + !function($) { + var methods = { + init: function() { + return this.data("cardjs", new CardJs(this)), + this + }, + cardNumber: function() { + return this.data("cardjs").getCardNumber() + }, + cardType: function() { + return this.data("cardjs").getCardType() + }, + name: function() { + return this.data("cardjs").getName() + }, + expiryMonth: function() { + return this.data("cardjs").getExpiryMonth() + }, + expiryYear: function() { + return this.data("cardjs").getExpiryYear() + }, + cvc: function() { + return this.data("cardjs").getCvc() + } + }; + $.fn.CardJs = function(methodOrOptions) { + return methods[methodOrOptions] ? methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1)) : "object" != typeof methodOrOptions && methodOrOptions ? void $.error("Method " + methodOrOptions + " does not exist on jQuery.CardJs") : methods.init.apply(this, arguments) + } + }(jQuery), + $(function() { + $(".card-js").each(function(i, obj) { + $(obj).CardJs() + }) + }), + CardJs.prototype.constructor = CardJs, + CardJs.KEYS = { + 0: 48, + 9: 57, + NUMPAD_0: 96, + NUMPAD_9: 105, + DELETE: 46, + BACKSPACE: 8, + ARROW_LEFT: 37, + ARROW_RIGHT: 39, + ARROW_UP: 38, + ARROW_DOWN: 40, + HOME: 36, + END: 35, + TAB: 9, + A: 65, + X: 88, + C: 67, + V: 86 + }, + CardJs.CREDIT_CARD_NUMBER_DEFAULT_MASK = "XXXX XXXX XXXX XXXX", + CardJs.CREDIT_CARD_NUMBER_VISA_MASK = "XXXX XXXX XXXX XXXX", + CardJs.CREDIT_CARD_NUMBER_MASTERCARD_MASK = "XXXX XXXX XXXX XXXX", + CardJs.CREDIT_CARD_NUMBER_DISCOVER_MASK = "XXXX XXXX XXXX XXXX", + CardJs.CREDIT_CARD_NUMBER_JCB_MASK = "XXXX XXXX XXXX XXXX", + CardJs.CREDIT_CARD_NUMBER_AMEX_MASK = "XXXX XXXXXX XXXXX", + CardJs.CREDIT_CARD_NUMBER_DINERS_MASK = "XXXX XXXX XXXX XX", + CardJs.prototype.creditCardNumberMask = CardJs.CREDIT_CARD_NUMBER_DEFAULT_MASK, + CardJs.CREDIT_CARD_NUMBER_PLACEHOLDER = "Card number", + CardJs.NAME_PLACEHOLDER = "Name on card", + CardJs.EXPIRY_MASK = "XX / XX", + CardJs.EXPIRY_PLACEHOLDER = "MM / YY", + CardJs.EXPIRY_USE_DROPDOWNS = !1, + CardJs.EXPIRY_NUMBER_OF_YEARS = 10, + CardJs.CVC_MASK_3 = "XXX", + CardJs.CVC_MASK_4 = "XXXX", + CardJs.CVC_PLACEHOLDER = "CVC", + CardJs.CREDIT_CARD_SVG = '', + CardJs.LOCK_SVG = '', + CardJs.CALENDAR_SVG = '', + CardJs.USER_SVG = '', + CardJs.MAIL_SVG = '', + CardJs.INFORMATION_SVG = '', + CardJs.keyCodeFromEvent = function(e) { + return e.which || e.keyCode + } + , + CardJs.keyIsCommandFromEvent = function(e) { + return e.ctrlKey || e.metaKey + } + , + CardJs.keyIsNumber = function(e) { + return CardJs.keyIsTopNumber(e) || CardJs.keyIsKeypadNumber(e) + } + , + CardJs.keyIsTopNumber = function(e) { + var keyCode = CardJs.keyCodeFromEvent(e); + return keyCode >= CardJs.KEYS[0] && keyCode <= CardJs.KEYS[9] + } + , + CardJs.keyIsKeypadNumber = function(e) { + var keyCode = CardJs.keyCodeFromEvent(e); + return keyCode >= CardJs.KEYS.NUMPAD_0 && keyCode <= CardJs.KEYS.NUMPAD_9 + } + , + CardJs.keyIsDelete = function(e) { + return CardJs.keyCodeFromEvent(e) == CardJs.KEYS.DELETE + } + , + CardJs.keyIsBackspace = function(e) { + return CardJs.keyCodeFromEvent(e) == CardJs.KEYS.BACKSPACE + } + , + CardJs.keyIsDeletion = function(e) { + return CardJs.keyIsDelete(e) || CardJs.keyIsBackspace(e) + } + , + CardJs.keyIsArrow = function(e) { + var keyCode = CardJs.keyCodeFromEvent(e); + return keyCode >= CardJs.KEYS.ARROW_LEFT && keyCode <= CardJs.KEYS.ARROW_DOWN + } + , + CardJs.keyIsNavigation = function(e) { + var keyCode = CardJs.keyCodeFromEvent(e); + return keyCode == CardJs.KEYS.HOME || keyCode == CardJs.KEYS.END + } + , + CardJs.keyIsKeyboardCommand = function(e) { + var keyCode = CardJs.keyCodeFromEvent(e); + return CardJs.keyIsCommandFromEvent(e) && (keyCode == CardJs.KEYS.A || keyCode == CardJs.KEYS.X || keyCode == CardJs.KEYS.C || keyCode == CardJs.KEYS.V) + } + , + CardJs.keyIsTab = function(e) { + return CardJs.keyCodeFromEvent(e) == CardJs.KEYS.TAB + } + , + CardJs.copyAllElementAttributes = function(source, destination) { + $.each(source[0].attributes, function(idx, attr) { + destination.attr(attr.nodeName, attr.nodeValue) + }) + } + , + CardJs.numbersOnlyString = function(string) { + for (var numbersOnlyString = "", i = 0; i < string.length; i++) { + var currentChar = string.charAt(i) + , isValid = !isNaN(parseInt(currentChar)); + isValid && (numbersOnlyString += currentChar) + } + return numbersOnlyString + } + , + CardJs.applyFormatMask = function(string, mask) { + for (var formattedString = "", numberPos = 0, j = 0; j < mask.length; j++) { + var currentMaskChar = mask[j]; + if ("X" == currentMaskChar) { + var digit = string.charAt(numberPos); + if (!digit) + break; + formattedString += string.charAt(numberPos), + numberPos++ + } else + formattedString += currentMaskChar + } + return formattedString + } + , + CardJs.cardTypeFromNumber = function(number) { + if (re = new RegExp("^30[0-5]"), + null != number.match(re)) + return "Diners - Carte Blanche"; + if (re = new RegExp("^(30[6-9]|36|38)"), + null != number.match(re)) + return "Diners"; + if (re = new RegExp("^35(2[89]|[3-8][0-9])"), + null != number.match(re)) + return "JCB"; + if (re = new RegExp("^3[47]"), + null != number.match(re)) + return "AMEX"; + if (re = new RegExp("^(4026|417500|4508|4844|491(3|7))"), + null != number.match(re)) + return "Visa Electron"; + var re = new RegExp("^4"); + return null != number.match(re) ? "Visa" : (re = new RegExp("^5[1-5]"), + null != number.match(re) ? "Mastercard" : (re = new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)"), + null != number.match(re) ? "Discover" : "")) + } + , + CardJs.caretStartPosition = function(element) { + return "number" == typeof element.selectionStart ? element.selectionStart : !1 + } + , + CardJs.caretEndPosition = function(element) { + return "number" == typeof element.selectionEnd ? element.selectionEnd : !1 + } + , + CardJs.setCaretPosition = function(element, caretPos) { + if (null != element) + if (element.createTextRange) { + var range = element.createTextRange(); + range.move("character", caretPos), + range.select() + } else + element.selectionStart ? (element.focus(), + element.setSelectionRange(caretPos, caretPos)) : element.focus() + } + , + CardJs.normaliseCaretPosition = function(mask, caretPosition) { + var numberPos = 0; + if (0 > caretPosition || caretPosition > mask.length) + return 0; + for (var i = 0; i < mask.length; i++) { + if (i == caretPosition) + return numberPos; + "X" == mask[i] && numberPos++ + } + return numberPos + } + , + CardJs.denormaliseCaretPosition = function(mask, caretPosition) { + var numberPos = 0; + if (0 > caretPosition || caretPosition > mask.length) + return 0; + for (var i = 0; i < mask.length; i++) { + if (numberPos == caretPosition) + return i; + "X" == mask[i] && numberPos++ + } + return mask.length + } + , + CardJs.filterNumberOnlyKey = function(e) { + var isNumber = CardJs.keyIsNumber(e) + , isDeletion = CardJs.keyIsDeletion(e) + , isArrow = CardJs.keyIsArrow(e) + , isNavigation = CardJs.keyIsNavigation(e) + , isKeyboardCommand = CardJs.keyIsKeyboardCommand(e) + , isTab = CardJs.keyIsTab(e); + isNumber || isDeletion || isArrow || isNavigation || isKeyboardCommand || isTab || e.preventDefault() + } + , + CardJs.digitFromKeyCode = function(keyCode) { + return keyCode >= CardJs.KEYS[0] && keyCode <= CardJs.KEYS[9] ? keyCode - CardJs.KEYS[0] : keyCode >= CardJs.KEYS.NUMPAD_0 && keyCode <= CardJs.KEYS.NUMPAD_9 ? keyCode - CardJs.KEYS.NUMPAD_0 : null + } + , + CardJs.handleMaskedNumberInputKey = function(e, mask) { + CardJs.filterNumberOnlyKey(e); + var keyCode = e.which || e.keyCode + , element = e.target + , caretStart = CardJs.caretStartPosition(element) + , caretEnd = CardJs.caretEndPosition(element) + , normalisedStartCaretPosition = CardJs.normaliseCaretPosition(mask, caretStart) + , normalisedEndCaretPosition = CardJs.normaliseCaretPosition(mask, caretEnd) + , newCaretPosition = caretStart + , isNumber = CardJs.keyIsNumber(e) + , isDelete = CardJs.keyIsDelete(e) + , isBackspace = CardJs.keyIsBackspace(e); + if (isNumber || isDelete || isBackspace) { + e.preventDefault(); + var rawText = $(element).val() + , numbersOnly = CardJs.numbersOnlyString(rawText) + , digit = CardJs.digitFromKeyCode(keyCode) + , rangeHighlighted = normalisedEndCaretPosition > normalisedStartCaretPosition; + rangeHighlighted && (numbersOnly = numbersOnly.slice(0, normalisedStartCaretPosition) + numbersOnly.slice(normalisedEndCaretPosition)), + caretStart != mask.length && (isNumber && rawText.length <= mask.length && (numbersOnly = numbersOnly.slice(0, normalisedStartCaretPosition) + digit + numbersOnly.slice(normalisedStartCaretPosition), + newCaretPosition = Math.max(CardJs.denormaliseCaretPosition(mask, normalisedStartCaretPosition + 1), CardJs.denormaliseCaretPosition(mask, normalisedStartCaretPosition + 2) - 1)), + isDelete && (numbersOnly = numbersOnly.slice(0, normalisedStartCaretPosition) + numbersOnly.slice(normalisedStartCaretPosition + 1))), + 0 != caretStart && isBackspace && !rangeHighlighted && (numbersOnly = numbersOnly.slice(0, normalisedStartCaretPosition - 1) + numbersOnly.slice(normalisedStartCaretPosition), + newCaretPosition = CardJs.denormaliseCaretPosition(mask, normalisedStartCaretPosition - 1)), + $(element).val(CardJs.applyFormatMask(numbersOnly, mask)), + CardJs.setCaretPosition(element, newCaretPosition) + } + } + , + CardJs.handleCreditCardNumberKey = function(e, cardMask) { + CardJs.handleMaskedNumberInputKey(e, cardMask) + } + , + CardJs.handleCreditCardNumberChange = function(e) {} + , + CardJs.handleExpiryKey = function(e) { + CardJs.handleMaskedNumberInputKey(e, CardJs.EXPIRY_MASK) + } + , + CardJs.prototype.getCardNumber = function() { + return this.cardNumberInput.val() + } + , + CardJs.prototype.getCardType = function() { + return CardJs.cardTypeFromNumber(this.getCardNumber()) + } + , + CardJs.prototype.getName = function() { + return this.nameInput.val() + } + , + CardJs.prototype.getExpiryMonth = function() { + return this.expiryMonthInput.val() + } + , + CardJs.prototype.getExpiryYear = function() { + return this.expiryYearInput.val() + } + , + CardJs.prototype.getCvc = function() { + return this.cvcInput.val() + } + , + CardJs.prototype.setIconColour = function(colour) { + this.elem.find(".icon .svg").css({ + fill: colour + }) + } + , + CardJs.prototype.setIconColour = function(colour) { + this.elem.find(".icon .svg").css({ + fill: colour + }) + } + , + CardJs.prototype.refreshCreditCardTypeIcon = function() { + this.setCardTypeIconFromNumber(CardJs.numbersOnlyString(this.cardNumberInput.val())) + } + , + CardJs.prototype.refreshCreditCardNumberFormat = function() { + var numbersOnly = CardJs.numbersOnlyString($(this.cardNumberInput).val()) + , formattedNumber = CardJs.applyFormatMask(numbersOnly, this.creditCardNumberMask); + $(this.cardNumberInput).val(formattedNumber) + } + , + CardJs.prototype.refreshExpiryMonthYearInput = function() { + var numbersOnly = CardJs.numbersOnlyString($(this.expiryMonthYearInput).val()) + , formattedNumber = CardJs.applyFormatMask(numbersOnly, CardJs.EXPIRY_MASK); + $(this.expiryMonthYearInput).val(formattedNumber) + } + , + CardJs.prototype.refreshCvc = function() { + var numbersOnly = CardJs.numbersOnlyString($(this.cvcInput).val()) + , formattedNumber = CardJs.applyFormatMask(numbersOnly, this.creditCardNumberMask); + $(this.cvcInput).val(formattedNumber) + } + , + CardJs.prototype.setCardTypeIconFromNumber = function(number) { + switch (CardJs.cardTypeFromNumber(number)) { + case "Visa Electron": + case "Visa": + this.setCardTypeAsVisa(); + break; + case "Mastercard": + this.setCardTypeAsMasterCard(); + break; + case "AMEX": + this.setCardTypeAsAmericanExpress(); + break; + case "Discover": + this.setCardTypeAsDiscover(); + break; + case "Diners - Carte Blanche": + case "Diners": + this.setCardTypeAsDiners(); + break; + case "JCB": + this.setCardTypeAsJcb(); + break; + default: + this.clearCardType() + } + } + , + CardJs.prototype.setCardMask = function(cardMask) { + this.creditCardNumberMask = cardMask, + this.cardNumberInput.attr("maxlength", cardMask.length) + } + , + CardJs.prototype.setCvc3 = function() { + this.cvcInput.attr("maxlength", CardJs.CVC_MASK_3.length) + } + , + CardJs.prototype.setCvc4 = function() { + this.cvcInput.attr("maxlength", CardJs.CVC_MASK_4.length) + } + , + CardJs.prototype.clearCardTypeIcon = function() { + this.elem.find(".card-number-wrapper .card-type-icon").removeClass("show") + } + , + CardJs.prototype.setCardTypeIconAsVisa = function() { + this.elem.find(".card-number-wrapper .card-type-icon").attr("class", "card-type-icon show visa") + } + , + CardJs.prototype.setCardTypeIconAsMasterCard = function() { + this.elem.find(".card-number-wrapper .card-type-icon").attr("class", "card-type-icon show master-card") + } + , + CardJs.prototype.setCardTypeIconAsAmericanExpress = function() { + this.elem.find(".card-number-wrapper .card-type-icon").attr("class", "card-type-icon show american-express") + } + , + CardJs.prototype.setCardTypeIconAsDiscover = function() { + this.elem.find(".card-number-wrapper .card-type-icon").attr("class", "card-type-icon show discover") + } + , + CardJs.prototype.setCardTypeIconAsDiners = function() { + this.elem.find(".card-number-wrapper .card-type-icon").attr("class", "card-type-icon show diners") + } + , + CardJs.prototype.setCardTypeIconAsJcb = function() { + this.elem.find(".card-number-wrapper .card-type-icon").attr("class", "card-type-icon show jcb") + } + , + CardJs.prototype.clearCardType = function() { + this.clearCardTypeIcon(), + this.setCardMask(CardJs.CREDIT_CARD_NUMBER_DEFAULT_MASK), + this.setCvc3() + } + , + CardJs.prototype.setCardTypeAsVisa = function() { + this.setCardTypeIconAsVisa(), + this.setCardMask(CardJs.CREDIT_CARD_NUMBER_VISA_MASK), + this.setCvc3() + } + , + CardJs.prototype.setCardTypeAsMasterCard = function() { + this.setCardTypeIconAsMasterCard(), + this.setCardMask(CardJs.CREDIT_CARD_NUMBER_MASTERCARD_MASK), + this.setCvc3() + } + , + CardJs.prototype.setCardTypeAsAmericanExpress = function() { + this.setCardTypeIconAsAmericanExpress(), + this.setCardMask(CardJs.CREDIT_CARD_NUMBER_AMEX_MASK), + this.setCvc4() + } + , + CardJs.prototype.setCardTypeAsDiscover = function() { + this.setCardTypeIconAsDiscover(), + this.setCardMask(CardJs.CREDIT_CARD_NUMBER_DISCOVER_MASK), + this.setCvc3() + } + , + CardJs.prototype.setCardTypeAsDiners = function() { + this.setCardTypeIconAsDiners(), + this.setCardMask(CardJs.CREDIT_CARD_NUMBER_DINERS_MASK), + this.setCvc3() + } + , + CardJs.prototype.setCardTypeAsJcb = function() { + this.setCardTypeIconAsJcb(), + this.setCardMask(CardJs.CREDIT_CARD_NUMBER_JCB_MASK), + this.setCvc3() + } + , + CardJs.prototype.initCardNumberInput = function() { + this.cardNumberInput = CardJs.detachOrCreateElement(this.elem, ".card-number", ""), + CardJs.elementHasAttribute(this.cardNumberInput, "name") || this.cardNumberInput.attr("name", "card-number"), + CardJs.elementHasAttribute(this.cardNumberInput, "placeholder") || this.cardNumberInput.attr("placeholder", CardJs.CREDIT_CARD_NUMBER_PLACEHOLDER), + this.cardNumberInput.attr("type", "tel"), + this.cardNumberInput.attr("maxlength", this.creditCardNumberMask.length), + this.cardNumberInput.attr("x-autocompletetype", "cc-number"), + this.cardNumberInput.attr("autocompletetype", "cc-number"), + this.cardNumberInput.attr("autocorrect", "off"), + this.cardNumberInput.attr("spellcheck", "off"), + this.cardNumberInput.attr("autocapitalize", "off"); + var $this = this; + this.cardNumberInput.keydown(function(e) { + CardJs.handleCreditCardNumberKey(e, $this.creditCardNumberMask) + }), + this.cardNumberInput.keyup(function() { + $this.refreshCreditCardTypeIcon() + }), + this.cardNumberInput.on("paste", function() { + setTimeout(function() { + $this.refreshCreditCardNumberFormat(), + $this.refreshCreditCardTypeIcon() + }, 1) + }) + } + , + CardJs.prototype.initNameInput = function() { + this.captureName = null != this.elem.find(".name")[0], + this.nameInput = CardJs.detachOrCreateElement(this.elem, ".name", ""), + CardJs.elementHasAttribute(this.nameInput, "name") || this.nameInput.attr("name", "card-number"), + CardJs.elementHasAttribute(this.nameInput, "placeholder") || this.nameInput.attr("placeholder", CardJs.NAME_PLACEHOLDER) + } + , + CardJs.prototype.initExpiryMonthInput = function() { + this.expiryMonthInput = CardJs.detachOrCreateElement(this.elem, ".expiry-month", "") + } + , + CardJs.prototype.initExpiryYearInput = function() { + this.expiryYearInput = CardJs.detachOrCreateElement(this.elem, ".expiry-year", "") + } + , + CardJs.prototype.initInstallmentsInput = function() { + if (this.captureInstallments) { + this.installmentsInput = CardJs.detachOrCreateElement(this.elem, ".installments", ""), + CardJs.elementHasAttribute(this.cvcInput, "placeholder") || this.cvcInput.attr("placeholder", CardJs.CVC_PLACEHOLDER), + this.cvcInput.attr("type", "tel"), + this.cvcInput.attr("maxlength", CardJs.CVC_MASK_3.length), + this.cvcInput.attr("x-autocompletetype", "cc-csc"), + this.cvcInput.attr("autocompletetype", "cc-csc"), + this.cvcInput.attr("autocorrect", "off"), + this.cvcInput.attr("spellcheck", "off"), + this.cvcInput.attr("autocapitalize", "off"); + var $this = this; + this.cvcInput.keydown(CardJs.filterNumberOnlyKey), + this.cvcInput.on("paste", function() { + setTimeout(function() { + $this.refreshCvc() + }, 1) + }) + } + , + CardJs.prototype.setupCardNumberInput = function() { + this.stripe && this.cardNumberInput.attr("data-stripe", "number"), + this.elem.append("
"); + var wrapper = this.elem.find(".card-number-wrapper"); + wrapper.append(this.cardNumberInput), + wrapper.append("
"), + wrapper.append("
"), + wrapper.find(".icon").append(CardJs.CREDIT_CARD_SVG) + } + , + CardJs.prototype.setupInstallmentsInput = function() { + if (this.captureInstallments) { + this.elem.append("

"+woocommerce_wompi_payments_cardjs.installments_title+"

"); + var wrapper = this.elem.find(".installments-wrapper"); + wrapper.append(this.installmentsInput); + var installments_select = this.elem.find(".installments-select"); + installments_select.append(""); + installments_select.append(""); + installments_select.append(""); + installments_select.append(""); + installments_select.append(""); + installments_select.append(""); + installments_select.append(""); + installments_select.append(""); + } + } + , + CardJs.prototype.setupNameInput = function() { + if (this.captureName) { + this.elem.append("
"); + var wrapper = this.elem.find(".name-wrapper"); + wrapper.append(this.nameInput), + wrapper.append("
"), + wrapper.find(".icon").append(CardJs.USER_SVG) + } + } + , + CardJs.prototype.setupExpiryInput = function() { + this.elem.append("
"); + var expiryInput, wrapper = this.elem.find(".expiry-wrapper"); + if (this.EXPIRY_USE_DROPDOWNS) { + expiryInput = $("
"); + var expiryMonthNew = $("") + , expiryMonthOld = this.expiryMonthInput; + CardJs.copyAllElementAttributes(expiryMonthOld, expiryMonthNew), + this.expiryMonthInput.remove(), + this.expiryMonthInput = expiryMonthNew; + for (var expiryYearNew = $(""), currentYear = parseInt((new Date).getFullYear().toString().substring(2, 4)), i = 0; i < CardJs.EXPIRY_NUMBER_OF_YEARS; i++) + expiryYearNew.append(""), + currentYear = (currentYear + 1) % 100; + var expiryYearOld = this.expiryYearInput; + CardJs.copyAllElementAttributes(expiryYearOld, expiryYearNew), + this.expiryYearInput.remove(), + this.expiryYearInput = expiryYearNew, + expiryInput.append(this.expiryMonthInput), + expiryInput.append(this.expiryYearInput) + } else { + expiryInput = $("
"), + "hidden" != this.expiryMonthInput.attr("type") && this.expiryMonthInput.attr("type", "hidden"), + "hidden" != this.expiryYearInput.attr("type") && this.expiryYearInput.attr("type", "hidden"), + this.stripe && (this.expiryMonthInput.attr("data-stripe", "exp-month"), + this.expiryYearInput.attr("data-stripe", "exp-year")), + this.expiryMonthYearInput = CardJs.detachOrCreateElement(this.elem, ".expiry", ""), + CardJs.elementHasAttribute(this.expiryMonthYearInput, "placeholder") || this.expiryMonthYearInput.attr("placeholder", CardJs.EXPIRY_PLACEHOLDER), + this.expiryMonthYearInput.attr("type", "tel"), + this.expiryMonthYearInput.attr("maxlength", CardJs.EXPIRY_MASK.length), + this.expiryMonthYearInput.attr("x-autocompletetype", "cc-exp"), + this.expiryMonthYearInput.attr("autocompletetype", "cc-exp"), + // this.expiryMonthYearInput.attr("autocomplete", "off"), + this.expiryMonthYearInput.attr("autocorrect", "off"), + this.expiryMonthYearInput.attr("spellcheck", "off"), + this.expiryMonthYearInput.attr("autocapitalize", "off"); + var $this = this; + this.expiryMonthYearInput.keydown(function(e) { + CardJs.handleExpiryKey(e); + var val = $this.expiryMonthYearInput.val(); + 1 == val.length && parseInt(val) > 1 && CardJs.keyIsNumber(e) && $this.expiryMonthYearInput.val(CardJs.applyFormatMask("0" + val, CardJs.EXPIRY_MASK)), + $this.EXPIRY_USE_DROPDOWNS || null == $this.expiryMonthYearInput || ($this.expiryMonthInput.val($this.expiryMonth()), + $this.expiryYearInput.val(7 == val.length ? val.substr(5, 2) : null)) + }), + this.expiryMonthYearInput.blur(function() { + var val = $this.expiryMonthYearInput.val(); + 1 == val.length && parseInt(val) > 1 && CardJs.keyIsNumber(e) && $this.expiryMonthYearInput.val(CardJs.applyFormatMask("0" + val, CardJs.EXPIRY_MASK)), + $this.EXPIRY_USE_DROPDOWNS || null == $this.expiryMonthYearInput || ($this.expiryMonthInput.val($this.expiryMonth()), + $this.expiryYearInput.val(7 == val.length ? val.substr(5, 2) : null)) + + $this.refreshExpiryMonthValidation() + }), + this.expiryMonthYearInput.on("paste", function() { + setTimeout(function() { + $this.refreshExpiryMonthYearInput() + }, 1) + }), + expiryInput.append(this.expiryMonthYearInput), + expiryInput.append(this.expiryMonthInput), + expiryInput.append(this.expiryYearInput) + } + wrapper.append(expiryInput), + wrapper.append("
"), + wrapper.find(".icon").append(CardJs.CALENDAR_SVG) + } + , + CardJs.prototype.setupCvcInput = function() { + this.stripe && this.cvcInput.attr("data-stripe", "cvc"), + this.elem.append("
"); + var wrapper = this.elem.find(".cvc-wrapper"); + wrapper.append(this.cvcInput), + wrapper.append("
"), + wrapper.find(".icon").append(CardJs.LOCK_SVG) + } + , + CardJs.prototype.expiryMonth = function() { + if (!this.EXPIRY_USE_DROPDOWNS && null != this.expiryMonthYearInput) { + var val = this.expiryMonthYearInput.val(); + return val.length >= 2 ? parseInt(val.substr(0, 2)) : null + } + return null + } + , + CardJs.prototype.refreshExpiryMonthValidation = function() { + CardJs.isExpiryValid(this.getExpiryMonth(), this.getExpiryYear()) ? this.setExpiryMonthAsValid() : this.setExpiryMonthAsInvalid() + } + , + CardJs.prototype.setExpiryMonthAsValid = function() { + this.EXPIRY_USE_DROPDOWNS || this.expiryMonthYearInput.parent().removeClass("has-error") + } + , + CardJs.prototype.setExpiryMonthAsInvalid = function() { + this.EXPIRY_USE_DROPDOWNS || this.expiryMonthYearInput.parent().addClass("has-error") + } + , + CardJs.elementHasAttribute = function(element, attributeName) { + var attr = $(element).attr(attributeName); + return "undefined" != typeof attr && attr !== !1 + } + , + CardJs.detachOrCreateElement = function(parentElement, selector, html) { + var element = parentElement.find(selector); + return element[0] ? element.detach() : element = $(html), + element + } + , + CardJs.isValidMonth = function(expiryMonth) { + return expiryMonth >= 1 && 12 >= expiryMonth + } + , + CardJs.isExpiryValid = function(month, year) { + var today = new Date + , currentMonth = today.getMonth() + 1 + , currentYear = "" + today.getFullYear(); + return 2 == ("" + year).length && (year = currentYear.substring(0, 2) + "" + year), + currentMonth = parseInt(currentMonth), + currentYear = parseInt(currentYear), + month = parseInt(month), + year = parseInt(year), + CardJs.isValidMonth(month) && (year > currentYear || year == currentYear && month >= currentMonth) + } + ; +} +)(jQuery); diff --git a/assets/logos/bancolombia_logo.png b/assets/logos/bancolombia_logo.png new file mode 100644 index 0000000..ceabb8c Binary files /dev/null and b/assets/logos/bancolombia_logo.png differ diff --git a/assets/logos/cash_bancolombia_logo.png b/assets/logos/cash_bancolombia_logo.png new file mode 100644 index 0000000..d0bd700 Binary files /dev/null and b/assets/logos/cash_bancolombia_logo.png differ diff --git a/assets/logos/credit_cards.png b/assets/logos/credit_cards.png new file mode 100644 index 0000000..6c9922f Binary files /dev/null and b/assets/logos/credit_cards.png differ diff --git a/assets/logos/nequi_logo.png b/assets/logos/nequi_logo.png new file mode 100644 index 0000000..58a03ee Binary files /dev/null and b/assets/logos/nequi_logo.png differ diff --git a/assets/logos/pse_logo.png b/assets/logos/pse_logo.png new file mode 100644 index 0000000..974c40b Binary files /dev/null and b/assets/logos/pse_logo.png differ diff --git a/assets/logos/pse_logo_2.png b/assets/logos/pse_logo_2.png new file mode 100644 index 0000000..bf246e4 Binary files /dev/null and b/assets/logos/pse_logo_2.png differ diff --git a/includes/class-woocommerce-wompi-payments-plugin.php b/includes/class-woocommerce-wompi-payments-plugin.php new file mode 100644 index 0000000..6a1b1f9 --- /dev/null +++ b/includes/class-woocommerce-wompi-payments-plugin.php @@ -0,0 +1,217 @@ +file = $file; + $this->version = $version; + $this->name = $name; + // Path. + $this->plugin_path = trailingslashit( plugin_dir_path( $this->file ) ); + $this->plugin_url = trailingslashit( plugin_dir_url( $this->file ) ); + $this->includes_path = $this->plugin_path . trailingslashit( 'includes' ); + $this->lib_path = $this->plugin_path . trailingslashit( 'lib' ); + $this->payment_methods_path = $this->plugin_path . trailingslashit( 'payment-methods' ); + $this->logger = new WC_Logger(); + } + + public function run_woocommerce_wompi_payments() + { + try{ + if ($this->_bootstrapped){ + throw new Exception( $this->name . ' solamente puede ser llamado una sola vez!'); + } + $this->_run(); + $this->_bootstrapped = true; + }catch (Exception $e){ + if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { + wompi_payments_admin_notices('Wompi Payments:: ' . $e->getMessage()); + } + } + } + + protected function _run() + { + require_once ($this->payment_methods_path . 'class-wompi-payment-pse.php'); + require_once ($this->includes_path . 'class-woocommerce-wompi-payments.php'); + require_once ($this->payment_methods_path . 'class-wompi-payment-credit-cards.php'); + require_once ($this->payment_methods_path . 'class-wompi-payment-bancolombia-button.php'); + require_once ($this->payment_methods_path . 'class-wompi-payment-nequi.php'); + require_once ($this->payment_methods_path . 'class-wompi-payment-cash-bancolombia.php'); + + add_filter( 'woocommerce_payment_gateways', array($this, 'woocommerce_wompi_payments_add_gateway')); + // // add_filter( 'woocommerce_billing_fields', array($this, 'custom_woocommerce_billing_fields')); + add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); + add_action( 'wp_head', array( $this, 'enqueue_head_scripts' ) ); + + } + + + public function woocommerce_wompi_payments_add_gateway($methods) + { + $methods[] = 'WC_Wompi_PSE'; + $methods[] = 'WC_Wompi_Credit_Cards'; + $methods[] = 'WC_Wompi_Bancolombia_Button'; + $methods[] = 'WC_Wompi_Nequi'; + $methods[] = 'WC_Wompi_Cash_Bancolombia'; + return $methods; + } + + public function nameClean($domain = false) + { + $name = ($domain) ? str_replace(' ', '-', $this->name) : str_replace(' ', '', $this->name); + return strtolower($name); + } + + public function enqueue_head_scripts(){ + + if( !is_admin() ){ + + $wompi_payments = new Woocommerce_Wompi_Payments(); + + if( ! $wompi_payments->isTest ){ + ?> + + + plugin_url . 'assets/css/style.css', array(), $this->version ); + } + + $available_payment_gateways = array_keys( WC()->payment_gateways->get_available_payment_gateways() ); + + if( in_array( 'woocommerce_wompi_credit_cards', $available_payment_gateways ) ) { + + wp_enqueue_script( 'woocommerce-wompi-payments-plugin-core', $this->plugin_url . 'assets/js/wompi-payments-plugin-core.js', array( 'jquery' ), $this->version, true ); + + if( is_checkout() ){ + + wp_enqueue_script( 'woocommerce-wompi-payments-cardjs', $this->plugin_url . 'assets/libs/card-js/card-js.min.js', array( 'jquery' ), $this->version, true ); + wp_enqueue_style('woocommerce-wompi-payments-cardcss', $this->plugin_url . 'assets/libs/card-js/card-js.min.css', array(), $this->version ); + wp_enqueue_script( 'woocommerce-wompi-payments-plugin-card-js', $this->plugin_url . 'assets/js/wompi-payments-plugin-card-js.js', array( 'jquery', 'woocommerce-wompi-payments-cardjs' ), $this->version, true ); + + wp_localize_script( 'woocommerce-wompi-payments-cardjs', 'woocommerce_wompi_payments_cardjs', [ + 'installments_title' => __('Número de cuotas', 'woocommerce-wompi-payments-plugin') + ]); + } + } + + if( in_array( 'woocommerce_wompi_nequi', $available_payment_gateways ) ) { + + if( is_checkout() ){ + wp_enqueue_script( 'woocommerce-wompi-payments-nequi-sa', "https://cdn.jsdelivr.net/npm/sweetalert2@11", array( 'jquery' ), $this->version, true ); + wp_enqueue_script( 'woocommerce-wompi-payments-plugin-nequi', $this->plugin_url . 'assets/js/wompi-payments-plugin-nequi.js', array( 'jquery', 'woocommerce-wompi-payments-nequi-sa' ), $this->version, true ); + + wp_localize_script( 'woocommerce-wompi-payments-plugin-nequi', 'wompi_payments_plugin_nequi', [ + 'logo_url' => $this->plugin_url . 'assets/animations/new_notification.gif', + 'check_your_phone_msg' => __('Se ha enviado una notificación a tu celular, ingresa a la App de Nequi para continuar la aprobación del pago

00:59', 'woocommerce-wompi-payments-plugin'), + 'seconds_to_wait' => 90, + ]); + } + } + } + + public function log($message = '') { + if (is_array($message) || is_object($message)) + $message = print_r($message, true); + + $this->logger->add('woocommerce-wompi-payments-plugin', $message); + } + + public function get_available_payment() + { + $activated_ones = array_keys( WC()->payment_gateways->get_available_payment_gateways() ); + + return in_array( 'woocommerce_wompi_pse', $activated_ones ); + } + + public function createUrl( $sandbox ) + { + if ( $sandbox ){ + + $url = "https://sandbox.wompi.co/v1/"; + + }else{ + + $url = "https://production.wompi.co/v1/"; + } + + return $url; + } + + public function getDefaultCountry() + { + $woo_countries = new WC_Countries(); + $default_country = $woo_countries->get_base_country(); + + return $default_country; + } + +} \ No newline at end of file diff --git a/includes/class-woocommerce-wompi-payments.php b/includes/class-woocommerce-wompi-payments.php new file mode 100644 index 0000000..8fa54b8 --- /dev/null +++ b/includes/class-woocommerce-wompi-payments.php @@ -0,0 +1,738 @@ + 'Número de seguridad (CVC)', + 'card_holder' => 'Nombre del titular', + 'exp_month' => 'Mes de expiración', + 'exp_year' => 'Año de expiración', + 'number' => 'Número de tarjeta', + ]; + + public function __construct( $payment_method_id = null ){ + parent::__construct(); + + if( !is_null( $payment_method_id ) ){ + $this->id = $payment_method_id; + } + } + + /**Obtiene el listado de bancos disponibles */ + public function get_banks( $isTest = false ){ + + $this->isSandBox = $isTest; + + $url = $this->get_payment_url() . 'pse/financial_institutions/'; + + $args = array( + 'method' => 'GET', + 'timeout' => 5, + 'headers' => array( + 'authorization' => 'Bearer ' . $this->get_public_key(), + ), + 'sslverify' => false + ); + + $request = wp_remote_post( $url, $args ); + + if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) { + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, print_r( $request, true ) ); + } + + return false; + + } else { + + $response = json_decode( wp_remote_retrieve_body( $request ) ); + + return $response; + } + } + + public function proccess_wc_api_enpoint(){ + + global $wp; + + $body = file_get_contents('php://input'); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, '_GET => ' . print_r( $_GET, true ) ); + $this->log->add( $this->id, 'body => ' . print_r( $body, true ) ); + } + + if ( ! empty( $body ) && !isset( $_GET['order_id'] ) ) { + + try { + + $body = json_decode ($body, null, 512 ); + + if ( json_last_error() !== JSON_ERROR_NONE ) { + header( 'HTTP/1.1 400' ); + echo(json_encode(['error' => true, 'msg' => json_last_error_msg()])); + exit; + } + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, 'body => ' . print_r( $body, true ) ); + } + + header( 'HTTP/1.1 200 OK' ); + + $this->proccess_payment_response( $body ); + + } catch (Exception $e) { + + header( 'HTTP/1.1 400' ); + echo(json_encode(['error' => true, 'msg' => 'Error decoding json: ' . $e->GetMessage()])); + exit; + } + + /**Is from redirect (is client) */ + } elseif( isset( $_GET['order_id'] ) && empty( $body ) ){ + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= IS CLIENT ===========" ); + } + + $order_id = explode( '?', $_GET['order_id'] )[0]; + + $order = wc_get_order($order_id); + + if( $order ){ + + $wompi_transferId = get_post_meta($order->get_id(), 'wompi_transferId', true); + + if( $wompi_transferId ){ + + $payment_info = $this->get_payment_info($wompi_transferId); + + if( $payment_info && isset( $payment_info->status ) ){ + + $payment_info_status = $payment_info->status; + + if( 'APPROVED' === $payment_info_status ){ + + $url_checkout = $this->get_return_url( $order ); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, 'url_checkout => ' . print_r( $url_checkout, true ) ); + } + + WC()->cart->empty_cart(); + wp_redirect($url_checkout); + + exit; + + } else { + + if( !empty( $payment_info->status_message ) ){ + + $order->add_order_note( $wompi_transferId . ' - ' . $payment_info->status_message ); + wc_add_notice( $payment_info->status_message, 'error' ); + } + } + } + + wp_redirect( wc_get_checkout_url() ); + exit; + } + } + + } else { + + header( 'HTTP/1.1 400' ); + echo(json_encode(['error' => true, 'msg' => 'Bad request'])); + exit; + } + } + + private function validate_checksum( $posted ){ + + $remote_checksum = $posted->signature->checksum; + + $local_checksum = hash ("sha256", trim( $posted->data->transaction->id . $posted->data->transaction->status . $posted->data->transaction->amount_in_cents . $posted->timestamp . $this->get_events_key() ) ); + + return $remote_checksum === $local_checksum; + + } + + /**Procesa el pago de acuerdo a la respuesta de Wompi */ + public function proccess_payment_response( $posted ) { + + global $woocommerce, $wp_filesystem; + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, 'posted => ' . print_r( $posted, true ) ); + } + + if( + !$posted->data->transaction->id + || !$posted->data->transaction->reference + || !$posted->data->transaction->status + || !$posted->event + ){ + $response = 'Bad request'; + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + echo(json_encode(['error' => true, 'msg' => $response])); + + exit; + } + + if( !$this->validate_checksum( $posted ) ){ + $response = 'Invalid checksum'; + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + echo(json_encode(['error' => true, 'msg' => $response])); + exit; + } + + $order_id = explode( '-', $posted->data->transaction->reference )[0]; + + $order = wc_get_order($order_id); + + if( !$order ){ + + $response = 'Invalid order'; + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + + echo(json_encode(['error' => true, 'msg' => $response])); + exit; + } + + $wompi_transferId = get_post_meta($order->get_id(), 'wompi_transferId', true); + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'wompi_transferId => ' . print_r($wompi_transferId, true)); + + if( !$wompi_transferId || empty( $wompi_transferId ) ){ + $response = 'Invalid payment method'; + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + + echo(json_encode(['error' => true, 'msg' => $response])); + exit; + } + + $order_wompi_reference = $posted->data->transaction->id; + $order_wompi_status = $posted->data->transaction->status; + $order_wompi_status_msg = $posted->data->transaction->status_message; + $environment = $posted->environment; + + if( ! $order->needs_payment() && $order_wompi_status !== 'VOIDED' ){ + + $response = 'Order already processed'; + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + + echo(json_encode(['error' => true, 'msg' => $response])); + exit; + } + + + if( 'APPROVED' === $order_wompi_status && $order->needs_payment() && 'prod' === $environment){ + + $order->payment_complete( $order_wompi_reference, sprintf('Pago completado mediante %s, ID de la transaccion %s', $posted->data->transaction->payment_method_type, $order_wompi_reference)); + $order->reduce_order_stock(); + + $response = 'Order processed (APPROVED)'; + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + + echo(json_encode(['error' => false, 'msg' => $response])); + exit; + + } elseif( 'VOIDED' === $order_wompi_status && !$order->needs_payment() && 'prod' === $environment ){ + + $order->update_status( 'cancelled', 'Pago anulado en Wompi de manera manual, pedido pasado a Cancelado'); + + $response = 'Order processed ('.$order_wompi_status.')'; + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + + echo(json_encode(['error' => false, 'msg' => $response])); + exit; + + } elseif( ( in_array( $order_wompi_status, ['ERROR', 'DECLINED'] ) ) && $order->needs_payment() && 'prod' === $environment ){ + + $order->update_status( 'failed', 'Pago fallido en Wompi, pedido pasado a Fallido'); + + $response = 'Order processed ('.$order_wompi_status.')'; + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + + echo(json_encode(['error' => false, 'msg' => $response])); + exit; + + } else { + + if( !is_null($order_wompi_status_msg) ){ + + $response = $order_wompi_status_msg . ' ('.$order_wompi_status.')'; + + } else { + + $response = 'Order processed ('.$order_wompi_status.')'; + } + + $order->add_order_note( $order_wompi_reference . ' - ' . $response ); + + + if ( $this->debug_mode() ) + $this->log->add( $this->id, 'response => ' . $response); + + echo(json_encode(['error' => false, 'msg' => $response])); + exit; + + } + + die(json_encode(['error' => false, 'msg' => 'Success'])); + + } + + /**Crea la transaccion en wompi para posteriormente consultar la URL y redirigir */ + public function registry_payment_intent( $order_id, $wompi_args ) { + + $url = $this->get_payment_url() . 'transactions'; + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $order_id . " - " . "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, $order_id . " - " . 'wompi_args => ' . print_r( $wompi_args, true ) ); + } + + $order = wc_get_order($order_id); + + $order->add_order_note( 'Nuevo intento de pago via ' . $wompi_args['payment_method']['type'] ); + + $args = array( + 'method' => 'POST', + 'timeout' => 5, + 'sslverify' => false, + 'headers' => array( + 'authorization' => 'Bearer ' . $this->get_public_key(), + ), + 'body' => json_encode($wompi_args, JSON_UNESCAPED_SLASHES ), + ); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $order_id . " - " . 'args => ' . print_r( $args, true ) ); + } + + $request = wp_remote_request( $url, $args ); + + $response = json_decode(wp_remote_retrieve_body( $request )); + + if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 201 ) { + + $this->log->add('error_' . $this->id, $order_id . " - " . "============================================"); + $this->log->add('error_' . $this->id, $order_id . " - " . "============= payment_intent url ==========="); + $this->log->add('error_' . $this->id, $order_id . " - " . print_r( $url, true ) ); + + $this->log->add('error_' . $this->id, $order_id . " - " . "============= payment_intent args ==========="); + $this->log->add('error_' . $this->id, $order_id . " - " . print_r( $args, true ) ); + + // $this->log->add('error_' . $this->id, $order_id . " - " . "============= payment_intent request ==========="); + // $this->log->add('error_' . $this->id, $order_id . " - " . print_r( $request, true ) ); + + $this->log->add('error_' . $this->id, $order_id . " - " . "============= payment_intent response ==========="); + $this->log->add('error_' . $this->id, $order_id . " - " . print_r( $response, true ) ); + + $order->add_order_note( 'Se presento un error generando el intento de pago ' . print_r( $response, true )); + + if ( $this->debug_mode() ){ + $this->log->add( __FUNCTION__ . '_errors', $order_id . " - " . 'response => ' . print_r( $response, true ) ); + } + + + if( isset( $response->error->type ) ){ + + if( isset( $response->error->messages ) ){ + + foreach( $response->error->messages as $field => $message ){ + + foreach( $message as $msg ){ + + if( 'reference' === $field && 'La referencia ya ha sido usada' == $msg ){ + return ['error' => true, 'response' => $msg ]; + } + } + } + } + + return ['error' => true, 'response' => "Se presentó un error, por favor verifica la información ingresada e inténtalo nuevamente."]; + } else { + return ['error' => true, 'response' => 'Se presentó un error, por favor verifica la información ingresada e inténtalo nuevamente']; + } + } + + if( isset( $response->data->id ) ){ + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $order_id . " - " . 'response => ' . print_r( $response, true ) ); + } + + update_post_meta( $order_id, 'wompi_transferId', $response->data->id ); + + $order->add_order_note( 'Intento de pago generado exitosamente: ' . $response->data->id ); + + return [ + 'error' => false, + 'response' => [ + 'transferId' => $response->data->id, + ] + ]; + } + + return ['error' => true, 'response' => 'Se presento un error, por favor intentalo nuevamente (402)']; + + } + + public function get_wompi_args( $order_id ){ + + global $woocommerce; + + $presigned_acceptance_token = $this->get_presigned_acceptance_token(); + + if( ! $presigned_acceptance_token ){ + return false; + } + + $order = new WC_Order( $order_id ); + + $order_total = intval ( get_post_meta ( $order -> get_id(), '_order_total', true) ) * 100; + + $url_checkout = get_site_url(); + $url_checkout = add_query_arg( 'wc-api', get_parent_class( $this ), $url_checkout ); + $url_checkout = add_query_arg( 'order_id', $order_id, $url_checkout ); + + // $url_checkout = $this->get_return_url( $order ); + + $unique_reference = $order_id . '-' . time(); + + $description = get_bloginfo( 'name' )." Pedido No. {$order_id}"; + + $wompi_args = [ + 'acceptance_token' => (string)$presigned_acceptance_token, + 'amount_in_cents' => (int)$order_total, + 'currency' => $order->get_currency(), + 'signature' => $this->generate_signature($unique_reference), + 'customer_email' => $order->get_billing_email(), + 'reference' => (string)$unique_reference, + 'order_id' => (string)$order_id, + 'redirect_url' => $url_checkout, + 'payment_method' => [ + 'payment_description' => $description, + // 'ecommerce_url' => $url_checkout, + ], + 'customer_data' => [ + 'phone_number' => str_replace(["+", " ", "-", "(", ")"], "", $order->get_billing_phone() ), + 'full_name' => mb_convert_case( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(), MB_CASE_TITLE), + 'legal_id_type' => sanitize_text_field( get_post_meta($order_id, 'billing_tipo_documento', true) ), + 'legal_id' => sanitize_text_field( get_post_meta($order_id, 'billing_documento_ident', true) ), + ], + ]; + + if( isset( $_COOKIE['wompi_sessionId'] ) && !empty( $_COOKIE['wompi_sessionId'] ) ){ + $wompi_args['session_id'] = $_COOKIE['wompi_sessionId']; + } + + if( $this->isSandBox ) { + $wompi_args['payment_method']['sandbox_status'] = "APPROVED"; + } + + return $wompi_args; + } + + public function tokenize_card( $_args ){ + + $url = $this->get_payment_url() . 'tokens/cards'; + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, 'url => ' . print_r( $url, true ) ); + } + + $args = array( + 'method' => 'POST', + 'timeout' => 5, + 'sslverify' => false, + 'headers' => array( + 'authorization' => 'Bearer ' . $this->get_public_key(), + ), + 'body' => json_encode($_args, JSON_UNESCAPED_SLASHES ), + ); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, 'args => ' . print_r( $args, true ) ); + } + + $request = wp_remote_request( $url, $args ); + + $response = json_decode(wp_remote_retrieve_body( $request )); + + if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 201 ) { + + if( isset( $response->error ) && $response->error->type === 'INPUT_VALIDATION_ERROR' && isset( $response->error->messages )){ + + foreach( $response->error->messages as $field => $message ){ + + foreach( $message as $msg ){ + + $msg = str_replace( 'Luhn check falló.', '', $msg ); + + if(isset( self::$card_field[$field] ) && !str_contains( $msg, 'patron' ) ){ + wc_add_notice( '' . self::$card_field[$field] . ': ' . ucfirst( $msg ), 'error' ); + } else { + wc_add_notice( '' . self::$card_field[$field] . ': Campo no válido', 'error' ); + } + } + } + } + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, "============= payment_intent url ==========="); + $this->log->add( $this->id, print_r( $url, true ) ); + + $this->log->add( $this->id, "============= payment_intent args ==========="); + $this->log->add( $this->id, print_r( $args, true ) ); + + $this->log->add( $this->id, "============= payment_intent response ==========="); + $this->log->add( $this->id, print_r( $response, true ) ); + } + + $this->log->add('error_' . $this->id, "============================================"); + $this->log->add('error_' . $this->id, "============= payment_intent url ==========="); + $this->log->add('error_' . $this->id, print_r( $url, true ) ); + + $this->log->add('error_' . $this->id, "============= payment_intent args ==========="); + $this->log->add('error_' . $this->id, print_r( $args, true ) ); + + $this->log->add('error_' . $this->id, "============= payment_intent response ==========="); + $this->log->add('error_' . $this->id, print_r( $response, true ) ); + + } else { + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, " - " . 'response => ' . print_r( $response, true ) ); + } + + if( isset( $response->status ) && $response->status === 'CREATED' ){ + + do_action('wc_wompi_on_token_created', $_args, $response->data->id ); + + return $response->data->id; + } + } + + return false; + } + + private function get_presigned_acceptance_token(){ + + $url = $this->get_payment_url() . 'merchants/' . $this->get_public_key(); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, 'url => ' . print_r( $url, true ) ); + } + + $args = array( + 'method' => 'GET', + 'timeout' => 5, + 'sslverify' => false + ); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, 'args => ' . print_r( $args, true ) ); + } + + $request = wp_remote_post( $url, $args ); + + $response = json_decode(wp_remote_retrieve_body( $request )); + + if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) { + + $this->log->add('error_' . $this->id, "======================".__FUNCTION__."======================"); + $this->log->add('error_' . $this->id, "============= payment_intent url ==========="); + $this->log->add('error_' . $this->id, print_r( $url, true ) ); + + $this->log->add('error_' . $this->id, "============= payment_intent args ==========="); + $this->log->add('error_' . $this->id, print_r( $args, true ) ); + + // $this->log->add('error_' . $this->id, "============= payment_intent request ==========="); + // $this->log->add('error_' . $this->id, print_r( $request, true ) ); + + $this->log->add('error_' . $this->id, "============= payment_intent response ==========="); + $this->log->add('error_' . $this->id, print_r( $response, true ) ); + + return false; + + } else { + + $this->acceptance_token = $response->data->presigned_acceptance->acceptance_token; + + return $this->acceptance_token; + } + + return false; + + } + + public function get_payment_info( $transferId ){ + + $url = $this->get_payment_url() . 'transactions/'; + + $url = $url . $transferId; + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $transferId . " - " . "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, $transferId . " - " . 'url => ' . print_r( $url, true ) ); + } + + $args = array( + 'method' => 'GET', + 'timeout' => 5, + 'sslverify' => false, + 'headers' => array( + 'authorization' => 'Bearer ' . $this->get_public_key(), + ) + ); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $transferId . " - " . 'args => ' . print_r( $args, true ) ); + } + + $request = wp_remote_post( $url, $args ); + + $response = json_decode(wp_remote_retrieve_body( $request )); + + if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) { + + $this->log->add('error_' . $this->id, "============================================"); + $this->log->add('error_' . $this->id, "============= payment_intent url ==========="); + $this->log->add('error_' . $this->id, print_r( $url, true ) ); + + $this->log->add('error_' . $this->id, "============= payment_intent args ==========="); + $this->log->add('error_' . $this->id, print_r( $args, true ) ); + + // $this->log->add('error_' . $this->id, "============= payment_intent request ==========="); + // $this->log->add('error_' . $this->id, print_r( $request, true ) ); + + $this->log->add('error_' . $this->id, "============= payment_intent response ==========="); + $this->log->add('error_' . $this->id, print_r( $response, true ) ); + + return false; + + } else { + + if( isset( $response->data ) && !empty( $response->data ) ){ + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $transferId . " - " . 'response => ' . print_r( $response->data, true ) ); + } + + return $response->data; + } + + return false; + } + } + + private function generate_signature( $unique_reference ){ + + global $woocommerce; + + // $order = new WC_Order( $order_id ); + + $order_id = explode('-', $unique_reference)[0]; + + $order_total = intval(get_post_meta($order_id, '_order_total', true)) . '00'; + $order_currency = get_post_meta($order_id, '_order_currency', true); + + $signature = $unique_reference . $order_total . $order_currency . $this->integrity_key; + + $signature_sha256 = hash ("sha256", $signature); + + return $signature_sha256; + + } + + + public function get_payment_url_for_transferId( $transferId ){ + + sleep(1); + + $url = $this->get_payment_url(). 'transactions/'; + + $url = $url . $transferId; + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $transferId . " - " . "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, $transferId . " - " . 'url => ' . print_r( $url, true ) ); + } + + $args = array( + 'method' => 'GET', + 'timeout' => 5, + 'sslverify' => false, + 'headers' => array( + 'authorization' => 'Bearer ' . $this->get_public_key(), + ) + ); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $transferId . " - " . 'args => ' . print_r( $args, true ) ); + } + + $request = wp_remote_post( $url, $args ); + + $response = json_decode(wp_remote_retrieve_body( $request )); + + if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) { + + $this->log->add('error_' . $this->id, "============================================"); + $this->log->add('error_' . $this->id, "============= payment_intent url ==========="); + $this->log->add('error_' . $this->id, print_r( $url, true ) ); + + $this->log->add('error_' . $this->id, "============= payment_intent args ==========="); + $this->log->add('error_' . $this->id, print_r( $args, true ) ); + + // $this->log->add('error_' . $this->id, "============= payment_intent request ==========="); + // $this->log->add('error_' . $this->id, print_r( $request, true ) ); + + $this->log->add('error_' . $this->id, "============= payment_intent response ==========="); + $this->log->add('error_' . $this->id, print_r( $response, true ) ); + + return false; + + } else { + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, $transferId . " - " . 'response => ' . print_r( $response, true ) ); + } + + if( isset( $response->data->payment_method->extra->async_payment_url ) && !empty( $response->data->payment_method->extra->async_payment_url ) ){ + + return $response->data->payment_method->extra->async_payment_url; + } + + return false; + } + } + + private function get_payment_url(){ + + return $this->createUrl(); + + } + +} \ No newline at end of file diff --git a/payment-methods/class-wompi-payment-bancolombia-button.php b/payment-methods/class-wompi-payment-bancolombia-button.php new file mode 100644 index 0000000..838c86b --- /dev/null +++ b/payment-methods/class-wompi-payment-bancolombia-button.php @@ -0,0 +1,134 @@ +id = 'woocommerce_wompi_bancolombia_button'; + + $this->method_title = 'Boton Bancolombia (Wompi)'; + $this->has_fields = true; + $this->method_description = 'Recibe pagos mediante Boton Bancolombia con Wompi'; + $this->has_fields = false; + + $this->icon = plugins_url( '../assets/logos/bancolombia_logo.png', __FILE__ ); + + $this->init_form_fields(); + $this->init_settings(); + + $this->wompi_payments = new Woocommerce_Wompi_Payments( $this->id ); + + $this->title = $this->wompi_payments->isTest ? $this->settings['title'] . ' (Testmode)' : $this->settings['title']; + $this->description = $this->wompi_payments->isTest ? $this->settings['description'] . ' (Testmode)' : $this->settings['description']; + + add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); + + } + + function init_form_fields(){ + $this->form_fields = array( + 'enabled' => array( + 'title' => 'Habilitar', + 'type' => 'checkbox', + 'label' => '', + 'default' => 'no', + 'description' => 'Mostrar este metodo de pago como una opcion en el checkout.' + ), + 'title' => array( + 'title' => 'Titulo', + 'type' => 'text', + 'default' => 'Boton Bancolombia (Wompi)', + ), + 'description' => array( + 'title' => 'Descripcion', + 'type' => 'textarea', + 'default' => 'Realiza tu pago mediante Boton Bancolombia con Wompi', + ), + ); + + } + + public function payment_fields() { + + if ( $description = $this->get_description()) + echo wp_kses_post( wpautop( wptexturize( $description ) ) ); + } + + public function admin_options(){ + + echo ''; + $this->generate_settings_html(); + echo '
'; + } + + /**Genera un intento de pago despues de darle click en Finalizar Compra y redirige al cliente a PSE*/ + public function process_payment( $order_id ) { + + if ( $this->wompi_payments->debug_mode() ){ + $this->wompi_payments->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->wompi_payments->log->add( $this->id, 'order_id => ' . print_r( $order_id, true ) ); + } + + $args = $this->wompi_payments->get_wompi_args( $order_id ); + + $args['payment_method']['type'] = 'BANCOLOMBIA_TRANSFER'; + $args['payment_method']['user_type'] = 'PERSON'; + + $payment_intent = $this->wompi_payments->registry_payment_intent( $order_id, $args ); + + if ( $this->wompi_payments->debug_mode() ){ + $this->wompi_payments->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->wompi_payments->log->add( $this->id, 'payment_intent => ' . print_r( $payment_intent, true ) ); + } + + if( $payment_intent['error'] ){ + + wc_add_notice( $payment_intent['response'], 'error' ); + return parent::process_payment( $order_id ); + } + + $wompi_transferId = $payment_intent['response']['transferId']; + + for($intent = 1; $intent < 5; $intent ++){ + + $payment_url = $this->wompi_payments->get_payment_url_for_transferId( $wompi_transferId ); + + if( $payment_url !== false ){ + + $payment_url = add_query_arg('intent', $intent, $payment_url); + + return array( + 'result' => 'success', + 'redirect' => $payment_url + ); + } + } + + wc_add_notice( 'No se logro obtener la URL de pago, intentalo nuevamente', 'error' ); + + return parent::process_payment( $order_id ); + } + + public function is_valid_currency() { + if ( ! in_array( get_woocommerce_currency(), array( 'COP' ) ) ) return false; + + return true; + } + + public function is_available() { + global $woocommerce; + + if ( $this->enabled=="yes" ) : + + if ( !$this->is_valid_currency()) return false; + return true; + + endif; + + return false; + } +} \ No newline at end of file diff --git a/payment-methods/class-wompi-payment-cash-bancolombia.php b/payment-methods/class-wompi-payment-cash-bancolombia.php new file mode 100644 index 0000000..6030797 --- /dev/null +++ b/payment-methods/class-wompi-payment-cash-bancolombia.php @@ -0,0 +1,133 @@ +id = 'woocommerce_wompi_cash_bancolombia'; + + $this->method_title = 'Corresponsal Bancolombia (Wompi)'; + $this->has_fields = true; + $this->method_description = 'Recibe pagos en cualquier corresponsal Bancolombia'; + $this->has_fields = false; + + $this->icon = plugins_url( '../assets/logos/cash_bancolombia_logo.png', __FILE__ ); + + $this->init_form_fields(); + $this->init_settings(); + + $this->wompi_payments = new Woocommerce_Wompi_Payments( $this->id ); + + $this->title = $this->wompi_payments->isTest ? $this->settings['title'] . ' (Testmode)' : $this->settings['title']; + $this->description = $this->wompi_payments->isTest ? $this->settings['description'] . ' (Testmode)' : $this->settings['description']; + + add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); + + } + + public function payment_fields() { + if ( $description = $this->get_description()) + echo wp_kses_post( wpautop( wptexturize( $description ) ) ); + } + + function init_form_fields(){ + $this->form_fields = array( + 'enabled' => array( + 'title' => 'Habilitar', + 'type' => 'checkbox', + 'label' => '', + 'default' => 'no', + 'description' => 'Mostrar este metodo de pago como una opcion en el checkout.' + ), + 'title' => array( + 'title' => 'Titulo', + 'type' => 'text', + 'default' => 'Corresponsal Bancolombia', + ), + 'description' => array( + 'title' => 'Descripcion', + 'type' => 'textarea', + 'default' => 'Realiza el pago de tu pedido en cualquier corresponsal Bancolombia', + ), + ); + } + + public function admin_options(){ + + echo ''; + $this->generate_settings_html(); + echo '
'; + } + + /**Genera un intento de pago despues de darle click en Finalizar Compra y redirige al cliente a PSE*/ + public function process_payment( $order_id ) { + + global $woocommerce; + + if ( $this->wompi_payments->debug_mode() ){ + $this->wompi_payments->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->wompi_payments->log->add( $this->id, 'order_id => ' . print_r( $order_id, true ) ); + $this->wompi_payments->log->add( $this->id, '_POST => ' . print_r( $_POST, true ) ); + } + + $args = $this->wompi_payments->get_wompi_args( $order_id ); + + $args['payment_method']['type'] = 'BANCOLOMBIA_COLLECT'; + + $payment_intent = $this->wompi_payments->registry_payment_intent( $order_id, $args ); + + if ( $this->wompi_payments->debug_mode() ){ + $this->wompi_payments->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->wompi_payments->log->add( $this->id, 'payment_intent => ' . print_r( $payment_intent, true ) ); + } + + $order = wc_get_order( $order_id ); + + if( $payment_intent['error'] ){ + + wc_add_notice( $payment_intent['response'], 'error' ); + + $redirect_url = $this->get_return_url( $order ); + WC()->cart->empty_cart(); + + return array( + 'result' => 'success', + 'redirect' => $redirect_url + ); + // return parent::process_payment( $order_id ); + } + + $wompi_transferId = $payment_intent['response']['transferId']; + + + // wc_add_notice( 'No se logro procesar el pago. Intentalo nuevamente.', 'error' ); + + return parent::process_payment( $order_id ); + } + + public function is_valid_currency() { + if ( ! in_array( get_woocommerce_currency(), array( 'COP' ) ) ) return false; + + return true; + } + + public function is_available() { + global $woocommerce; + + if ( $this->enabled=="yes" ) : + + if ( !$this->is_valid_currency()) return false; + return true; + + endif; + + return false; + } + + + +} diff --git a/payment-methods/class-wompi-payment-credit-cards.php b/payment-methods/class-wompi-payment-credit-cards.php new file mode 100644 index 0000000..e389b3c --- /dev/null +++ b/payment-methods/class-wompi-payment-credit-cards.php @@ -0,0 +1,231 @@ +id = 'woocommerce_wompi_credit_cards'; + + $this->method_title = 'Tarjetas de Crédito/Débito (Wompi)'; + $this->has_fields = true; + $this->method_description = 'Recibe pagos mediante tarjetas de Crédito/Débito con Wompi'; + $this->has_fields = true; + + $this->icon = plugins_url( '../assets/logos/credit_cards.png', __FILE__ ); + + $this->init_form_fields(); + $this->init_settings(); + + $this->wompi_payments = new Woocommerce_Wompi_Payments( $this->id ); + + $this->title = $this->wompi_payments->isTest ? $this->settings['title'] . ' (Testmode)' : $this->settings['title']; + $this->description = $this->wompi_payments->isTest ? $this->settings['description'] . ' (Testmode)' : $this->settings['description']; + + add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); + + } + + public function payment_fields() { + + $installments_enabled = $this->settings['installments_enabled'] == 'yes' ? "true" : "false"; + if ( $description = $this->get_description()) + echo wp_kses_post( wpautop( wptexturize( $description ) ) ); + ?> +
+ + + + + + +
+ form_fields = array( + 'enabled' => array( + 'title' => 'Habilitar', + 'type' => 'checkbox', + 'label' => '', + 'default' => 'no', + 'description' => 'Mostrar este metodo de pago como una opcion en el checkout.' + ), + 'title' => array( + 'title' => 'Titulo', + 'type' => 'text', + 'default' => 'Tarjeta de Crédito/Débito', + ), + 'description' => array( + 'title' => 'Descripcion', + 'type' => 'textarea', + 'default' => 'Paga con tu tarjeta de Crédito/Débito', + ), + 'installments_enabled' => array( + 'title' => 'Habilitar pago a Cuotas', + 'type' => 'checkbox', + 'label' => '', + 'default' => 'no', + ), + ); + } + + public function admin_options(){ + + echo ''; + $this->generate_settings_html(); + echo '
'; + } + + //function to validate the fields before processing the payment + public function validate_fields() { + + /**Tokenize card */ + $tokenize_args = []; + + $tokenize_args['number'] = (string) str_replace([" ", "-"], "", sanitize_text_field( $_POST['card-number'] )); + $tokenize_args['cvc'] = (string) sanitize_text_field( $_POST['card-cvc'] ); + $tokenize_args['exp_month'] = intval(sanitize_text_field( $_POST['card-expiry-month'] )) < 10 ? '0' . intval(sanitize_text_field( $_POST['card-expiry-month'] )) : (string) intval(sanitize_text_field( $_POST['card-expiry-month'] )); + $tokenize_args['exp_year'] = (string) sanitize_text_field( $_POST['card-expiry-year'] ); + $tokenize_args['card_holder'] = sanitize_text_field( $_POST['card-holder-name'] ); + + $tokenize = $this->wompi_payments->tokenize_card( $tokenize_args ); + + if( !$tokenize ){ + return false; + } + + $this->card_token = $tokenize; + + return true; + + } + + /**Genera un intento de pago despues de darle click en Finalizar Compra y redirige al cliente a PSE*/ + public function process_payment( $order_id ) { + + if ( $this->wompi_payments->debug_mode() ){ + $this->wompi_payments->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->wompi_payments->log->add( $this->id, 'order_id => ' . print_r( $order_id, true ) ); + $this->wompi_payments->log->add( $this->id, '_POST => ' . print_r( $_POST, true ) ); + } + + if( $this->card_token !== null ){ + + $args = $this->wompi_payments->get_wompi_args( $order_id ); + + $args['payment_method']['type'] = 'CARD'; + $args['payment_method']['token'] = $this->card_token; + $args['payment_method']['installments'] = intval( $_POST['card-installments']) === 0 ? 1 : intval( $_POST['card-installments']); + + $payment_intent = $this->wompi_payments->registry_payment_intent( $order_id, $args ); + + if ( $this->wompi_payments->debug_mode() ){ + $this->wompi_payments->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->wompi_payments->log->add( $this->id, 'payment_intent => ' . print_r( $payment_intent, true ) ); + } + + if( $payment_intent['error'] ){ + + wc_add_notice( $payment_intent['response'], 'error' ); + + return parent::process_payment( $order_id ); + } + + $wompi_transferId = $payment_intent['response']['transferId']; + + $order = wc_get_order( $order_id ); + + $limit = 8; + + for($intent = 1; $intent <= $limit; $intent ++) { + + $payment_info = $this->wompi_payments->get_payment_info($wompi_transferId); + + if( $payment_info && isset( $payment_info->status ) ) { + if( $payment_info->status == 'APPROVED' ){ + + do_action('wc_wompi_on_payment_approved', $args ); + + $redirect_url = $this->get_return_url( $order ); + $redirect_url = add_query_arg( 'wompi_payment', 'approved', $redirect_url ); + $redirect_url = add_query_arg( 'intent', $intent, $redirect_url ); + + update_post_meta( $order_id, 'franchise', $payment_info->payment_method->extra->brand ); + update_post_meta( $order_id, 'cc_number', $payment_info->payment_method->extra->last_four ); + update_post_meta( $order_id, 'payment_method_name', $payment_info->payment_method->extra->brand ); + update_post_meta( $order_id, 'card_type', $payment_info->payment_method->extra->card_type ); + + WC()->cart->empty_cart(); + + return array( + 'result' => 'success', + 'redirect' => $redirect_url + ); + } + + if( $intent === $limit && $payment_info->status == 'PENDING' ){ + + $redirect_url = $this->get_return_url( $order ); + $redirect_url = add_query_arg( 'wompi_payment', 'pending', $redirect_url ); + $redirect_url = add_query_arg( 'intent', $intent, $redirect_url ); + + WC()->cart->empty_cart(); + + return array( + 'result' => 'success', + 'redirect' => $redirect_url + ); + } + + if( $payment_info->status == 'DECLINED' ){ + + // $order->add_order_note( $wompi_transferId . ' - ' . $payment_info->status_message ); + wc_add_notice( $payment_info->status_message, 'error' ); + wc_add_notice( 'Transacción rechazada, consulta los datos de la tarjeta e intenta nuevamente.', 'error' ); + + $order->update_status( 'failed', $wompi_transferId . ' - ' . $payment_info->status_message ); + + return; + } + } + + sleep(3); + } + + return parent::process_payment( $order_id ); + + } else { + + wc_add_notice( 'No se pudo procesar el pago, por favor intentalo nuevamente.', 'error' ); + } + + return parent::process_payment( $order_id ); + + } + + public function is_valid_currency() { + if ( ! in_array( get_woocommerce_currency(), array( 'COP' ) ) ) return false; + + return true; + } + + public function is_available() { + global $woocommerce; + + if ( $this->enabled=="yes" ) : + + if ( !$this->is_valid_currency()) return false; + return true; + + endif; + + return false; + } +} diff --git a/payment-methods/class-wompi-payment-nequi.php b/payment-methods/class-wompi-payment-nequi.php new file mode 100644 index 0000000..6883fff --- /dev/null +++ b/payment-methods/class-wompi-payment-nequi.php @@ -0,0 +1,200 @@ +id = 'woocommerce_wompi_nequi'; + + $this->method_title = 'Nequi (Wompi)'; + $this->has_fields = true; + $this->method_description = 'Recibe pagos mediante Nequi'; + $this->has_fields = false; + + $this->icon = plugins_url( '../assets/logos/nequi_logo.png', __FILE__ ); + + $this->init_form_fields(); + $this->init_settings(); + + $this->wompi_payments = new Woocommerce_Wompi_Payments( $this->id ); + + $this->title = $this->wompi_payments->isTest ? $this->settings['title'] . ' (Testmode)' : $this->settings['title']; + $this->description = $this->wompi_payments->isTest ? $this->settings['description'] . ' (Testmode)' : $this->settings['description']; + + add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); + + } + + public function payment_fields() { + if ( $description = $this->get_description()) + echo wp_kses_post( wpautop( wptexturize( $description ) ) ); + } + + function init_form_fields(){ + $this->form_fields = array( + 'enabled' => array( + 'title' => 'Habilitar', + 'type' => 'checkbox', + 'label' => '', + 'default' => 'no', + 'description' => 'Mostrar este metodo de pago como una opcion en el checkout.' + ), + 'title' => array( + 'title' => 'Titulo', + 'type' => 'text', + 'default' => 'Nequi', + ), + 'description' => array( + 'title' => 'Descripcion', + 'type' => 'textarea', + 'default' => 'Paga desde tu cuenta Nequi, recibiras una notificacion en tu celular para aprobar el pago.', + ), + 'debug' => array( + 'title' => 'Registrar logs', + 'description' => '', + 'type' => 'checkbox', + 'default' => 'no', + ), + ); + } + + public function admin_options(){ + + echo ''; + $this->generate_settings_html(); + echo '
'; + } + + /**Genera un intento de pago despues de darle click en Finalizar Compra y redirige al cliente a PSE*/ + public function process_payment( $order_id ) { + + global $woocommerce; + + if ( $this->wompi_payments->debug_mode() ){ + $this->wompi_payments->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->wompi_payments->log->add( $this->id, 'order_id => ' . print_r( $order_id, true ) ); + $this->wompi_payments->log->add( $this->id, '_POST => ' . print_r( $_POST, true ) ); + } + + $args = $this->wompi_payments->get_wompi_args( $order_id ); + + $order = wc_get_order( $order_id ); + + $phone_number = $order->get_billing_phone(); + + //Extrae los 10 ultimos digitos del numero de telefono + $phone_number = substr(str_replace( [' ', '-', '(', ')'], '', $phone_number ) , -10); + + $args['payment_method']['type'] = 'NEQUI'; + $args['payment_method']['phone_number'] = $phone_number; + + $payment_intent = $this->wompi_payments->registry_payment_intent( $order_id, $args ); + + if ( $this->wompi_payments->debug_mode() ){ + $this->wompi_payments->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->wompi_payments->log->add( $this->id, 'payment_intent => ' . print_r( $payment_intent, true ) ); + } + + + + if( $payment_intent['error'] ){ + + wc_add_notice( $payment_intent['response'], 'error' ); + + $redirect_url = $this->get_return_url( $order ); + WC()->cart->empty_cart(); + + return array( + 'result' => 'success', + 'redirect' => $redirect_url + ); + // return parent::process_payment( $order_id ); + } + + $wompi_transferId = $payment_intent['response']['transferId']; + + $limit = 30; + + for($intent = 1; $intent <= $limit; $intent ++) { + + $payment_info = $this->wompi_payments->get_payment_info($wompi_transferId); + + if( $payment_info && isset( $payment_info->status ) ) { + + if( $payment_info->status == 'APPROVED' ){ + + $redirect_url = $this->get_return_url( $order ); + $redirect_url = add_query_arg( 'wompi_payment', 'approved', $redirect_url ); + $redirect_url = add_query_arg( 'intent', $intent, $redirect_url ); + + WC()->cart->empty_cart(); + + return array( + 'result' => 'success', + 'redirect' => $redirect_url + ); + } + + if( $intent === $limit && $payment_info->status == 'PENDING' ){ + + $redirect_url = $this->get_return_url( $order ); + $redirect_url = add_query_arg( 'wompi_payment', 'pending', $redirect_url ); + $redirect_url = add_query_arg( 'intent', $intent, $redirect_url ); + + WC()->cart->empty_cart(); + + return array( + 'result' => 'success', + 'redirect' => $redirect_url + ); + } + + if( $payment_info->status == 'DECLINED' ){ + + $order->add_order_note( $wompi_transferId . ' - ' . $payment_info->status_message ); + wc_add_notice( $payment_info->status_message, 'error' ); + + WC()->cart->empty_cart(); + $redirect_url = WC()->cart->get_cart_url(); + + return array( + 'result' => 'success', + 'redirect' => $redirect_url + ); + } + } + + sleep(3); + } + + wc_add_notice( 'No se logro procesar el pago. Intentalo nuevamente.', 'error' ); + + return parent::process_payment( $order_id ); + } + + public function is_valid_currency() { + if ( ! in_array( get_woocommerce_currency(), array( 'COP' ) ) ) return false; + + return true; + } + + public function is_available() { + global $woocommerce; + + if ( $this->enabled=="yes" ) : + + if ( !$this->is_valid_currency()) return false; + return true; + + endif; + + return false; + } + + + +} diff --git a/payment-methods/class-wompi-payment-pse.php b/payment-methods/class-wompi-payment-pse.php new file mode 100644 index 0000000..bb6bd07 --- /dev/null +++ b/payment-methods/class-wompi-payment-pse.php @@ -0,0 +1,416 @@ + 'Transacción rechazada', + 'APPROVED' => 'Transacción aprobada', + 'PENDING' => 'Transacción pendiente', + ]; + + public $isTest = false; + + private $public_key; + private $debug; + + public function __construct(){ + + global $woocommerce; + + $this->id = 'woocommerce_wompi_pse'; + + $this->method_title = 'PSE (Wompi)'; + $this->has_fields = true; + $this->method_description = 'Recibe desde cualquier banco colombiano mediante PSE'; + $this->has_fields = true; + + $this->icon = plugins_url( '../assets/logos/pse_logo_2.png', __FILE__ ); + + $this->init_form_fields(); + $this->init_settings(); + + $this->testmode = $this->settings['testmode']; + + $this->liveurl = 'https://production.wompi.co/v1/'; + $this->testurl = 'https://sandbox.wompi.co/v1/'; + $this->view_transaction_url = 'https://comercios.wompi.co/transactions/%s'; + + if( 'yes' === $this->testmode ){ + + $this->isTest = true; + + $this->public_key = $this->settings['public_key_test']; + $this->private_key = $this->settings['private_key_test']; + $this->events_key = $this->settings['events_key_test']; + $this->integrity_key = $this->settings['integrity_key_test']; + + } else { + + $this->isTest = false; + + $this->public_key = $this->settings['public_key']; + $this->private_key = $this->settings['private_key']; + $this->events_key = $this->settings['events_key']; + $this->integrity_key = $this->settings['integrity_key']; + } + + + $this->title = $this->isTest ? $this->settings['title'] . ' (Testmode)' : $this->settings['title']; + $this->description = $this->isTest ? $this->settings['description'] . ' (Testmode)' : $this->settings['description']; + + $this->debug = $this->settings['debug']; + + if(version_compare( WOOCOMMERCE_VERSION, '2.1', '>=')){ + $this->log = new WC_Logger(); + } else { + $this->log = $woocommerce->logger(); + } + + + /**Recibe la respuesta del pedido desde BC */ + add_action( 'woocommerce_api_' . strtolower( get_class( $this ) ), array( $this, 'check_payment_response' ) ); + + add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); + + // add_action( 'template_redirect', array( $this, 'fix_redirect_thank_you_page' ) ); + + /**Muestra el texto del resultado de la trx en el thankyou page */ + if ( 'yes' === $this->enabled ) { + add_filter( 'woocommerce_thankyou_order_received_text', array( $this, 'order_received_text' ), 10, 2 ); + } + } + + public function payment_fields() { + + if ( $description = $this->get_description()) + echo wp_kses_post( wpautop( wptexturize( $description ) ) ); + + $wompi_payments = new Woocommerce_Wompi_Payments(); + + $banks = $wompi_payments->get_banks( $this->isTest ); + + if ($banks){ + + echo('

Tipo de persona:

'); + echo ""; + + + echo('

Banco:

'); + echo ""; + } + } + + function init_form_fields(){ + $this->form_fields = array( + 'enabled' => array( + 'title' => 'Habilitar', + 'type' => 'checkbox', + 'label' => 'Habilitar PSE', + 'default' => 'no', + 'description' => 'Mostrar este metodo de pago como una opcion en el checkout.' + ), + 'title' => array( + 'title' => 'Titulo', + 'type' => 'text', + 'default' => 'PSE', + ), + 'description' => array( + 'title' => 'Descripcion', + 'type' => 'textarea', + 'default' => 'Paga desde tu cuenta bancaria', + ), + 'events_url' => array( + 'title' => 'URL de eventos', + 'type' => 'text', + 'disabled' => true, + 'default' => add_query_arg('wc-api', get_class( $this ), get_site_url()), + 'description' => 'Copia la URL y pégala en el campo \'URL de Eventos\' en la seccion \'Desarrolladores\' de Wompi', + ), + 'public_key' => array( + 'title' => 'Llave pública', + 'type' => 'text', + 'description' => 'Llave pública', + 'desc_tip' => true + ), + 'private_key' => array( + 'title' => 'Llave privada', + 'type' => 'text', + 'description' => 'Llave privada', + 'desc_tip' => true + ), + 'events_key' => array( + 'title' => 'Eventos', + 'type' => 'text', + 'description' => 'Eventos', + 'desc_tip' => true + ), + 'integrity_key' => array( + 'title' => 'Integridad', + 'type' => 'text', + 'description' => 'Integridad', + 'desc_tip' => true + ), + 'public_key_test' => array( + 'title' => 'Llave pública (Pruebas)', + 'type' => 'text', + 'description' => 'Llave pública', + 'desc_tip' => true + ), + 'private_key_test' => array( + 'title' => 'Llave privada (Pruebas)', + 'type' => 'text', + 'description' => 'Llave privada', + 'desc_tip' => true + ), + 'events_key_test' => array( + 'title' => 'Eventos (Pruebas)', + 'type' => 'text', + 'description' => 'Eventos', + 'desc_tip' => true + ), + 'integrity_key_test' => array( + 'title' => 'Integridad (Pruebas)', + 'type' => 'text', + 'description' => 'Integridad', + 'desc_tip' => true + ), + 'testmode' => array( + 'title' => 'Modo de pruebas', + 'description' => 'Habilitar el modo Sandbox', + 'type' => 'checkbox', + 'default' => 'no', + ), + 'debug' => array( + 'title' => 'Registrar logs', + 'description' => '', + 'type' => 'checkbox', + 'default' => 'no', + ), + ); + + } + + public function admin_options(){ + + echo ''; + $this->generate_settings_html(); + echo '
'; + } + + public function fix_redirect_thank_you_page(){ + + global $wp; + + if ( is_wc_endpoint_url( 'thank-you' ) && isset( $_GET['key'] ) && !isset( $_GET['redirect'] ) ) { + + $order_id = intval( str_replace( 'finalizar-compra/thank-you/', '', $wp->request ) ); + + $order = new WC_Order( $order_id ); + + if ( $order ) { + + $wompi_transferId = get_post_meta($order->get_id(), 'wompi_transferId', true); + + if( $wompi_transferId ){ + + $url_checkout = $this->get_return_url( $order ); + + $url_checkout = add_query_arg( 'redirect', 1, $url_checkout ); + + wp_redirect($url_checkout); + + exit; + } + } + } + } + + public function order_received_text( $text, $order ) { + + if ( $order ) { + + $wompi_transferId = get_post_meta($order->get_id(), 'wompi_transferId', true); + + if( $wompi_transferId ){ + + $wompi_payments = new Woocommerce_Wompi_Payments(); + $payment_info = $wompi_payments->get_payment_info($wompi_transferId); + + if( $payment_info && isset( $payment_info->status ) ){ + + $payment_info = $payment_info->status; + + return esc_html__( self::$transferStates[$payment_info] ); + } + + return esc_html__('Tu pedido ha sido recibido, en un momento recibirás información sobre el estado de la transacción.'); + } + } + + return $text; + } + + /**Recibe el post desde wompi */ + public function check_payment_response(){ + @ob_clean(); + + global $woocommerce; + + $body = file_get_contents('php://input'); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, '_GET => ' . print_r( $_GET, true ) ); + $this->log->add( $this->id, 'body => ' . print_r( $body, true ) ); + } + + $wompi_payments = new Woocommerce_Wompi_Payments(); + $wompi_payments->proccess_wc_api_enpoint(); + + exit; + + } + + + //function to validate the fields before processing the payment + public function validate_fields() { + + if( empty( $_POST['wompi_pse_bank'] ) || intval($_POST['wompi_pse_bank'] == 0 ) ){ + wc_add_notice( 'Por favor selecciona el banco por el cual realizar el pago', 'error' ); + return false; + } + return true; + } + + /**Genera un intento de pago despues de darle click en Finalizar Compra y redirige al cliente a PSE*/ + public function process_payment( $order_id ) { + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, 'order_id => ' . print_r( $order_id, true ) ); + $this->log->add( $this->id, '_POST => ' . print_r( $_POST, true ) ); + } + + $wompi_payments = new Woocommerce_Wompi_Payments(); + + // $wompi_transferId = get_post_meta( $order_id, 'wompi_transferId', true ); + + // if( ! $wompi_transferId ){ + + $args = $wompi_payments->get_wompi_args( $order_id ); + + $args['payment_method']['type'] = 'PSE'; + $args['payment_method']['user_type'] = sanitize_text_field( $_POST['wompi_pse_person_type'] ); + $args['payment_method']['user_legal_id_type'] = sanitize_text_field( get_post_meta($order_id, 'billing_tipo_documento', true) ); + $args['payment_method']['user_legal_id'] = sanitize_text_field( get_post_meta($order_id, 'billing_documento_ident', true) ); + $args['payment_method']['financial_institution_code'] = sanitize_text_field( $_POST['wompi_pse_bank'] ); + $args['payment_method']['payment_description'] = get_bloginfo( 'name' )." Pedido No. {$order_id}"; + + $payment_intent = $wompi_payments->registry_payment_intent( $order_id, $args ); + + if ( $this->debug_mode() ){ + $this->log->add( $this->id, "============= ".__FUNCTION__." ===========" ); + $this->log->add( $this->id, 'payment_intent => ' . print_r( $payment_intent, true ) ); + } + + if( $payment_intent['error'] ){ + + WC()->cart->empty_cart(); + wc_add_notice( $payment_intent['response'], 'error' ); + return parent::process_payment( $order_id ); + } + + $wompi_transferId = $payment_intent['response']['transferId']; + + // } + + for($intent = 1; $intent < 5; $intent ++){ + + $payment_url = $wompi_payments->get_payment_url_for_transferId( $wompi_transferId ); + + if( $payment_url !== false ){ + + $payment_url = add_query_arg('intent', $intent, $payment_url); + + return array( + 'result' => 'success', + 'redirect' => $payment_url + ); + } + + sleep(1); + } + + wc_add_notice( 'Se presentó un error, por favor verifica la información ingresada e inténtalo nuevamente', 'error' ); + WC()->cart->empty_cart(); + + return parent::process_payment( $order_id ); + } + + public function is_valid_currency() { + if ( ! in_array( get_woocommerce_currency(), array( 'COP' ) ) ) return false; + + return true; + } + + public function is_available() { + global $woocommerce; + + if ( $this->enabled=="yes" ) : + + if ( !$this->is_valid_currency()) return false; + if ( $this->testmode != 'yes' && ( ! $this->public_key || ! $this->private_key || ! $this->events_key || ! $this->integrity_key ) ) return false; + return true; + + endif; + + return false; + } + + public function debug_mode(){ + if ( 'yes' == $this->debug ){ + return true; + } + + return false; + } + + public function createUrl() { + + if ( $this->isTest ){ + + $url = "https://sandbox.wompi.co/v1/"; + + }else{ + + $url = "https://production.wompi.co/v1/"; + } + + return $url; + } + + public function get_public_key(){ + return trim($this->public_key); + } + + public function get_private_key(){ + return trim($this->private_key); + } + + public function get_events_key(){ + return trim($this->events_key); + } + + public function get_integrity_key(){ + return trim($this->integrity_key); + } + +} diff --git a/woocommerce-wompi-payments.php b/woocommerce-wompi-payments.php new file mode 100644 index 0000000..5ccfab2 --- /dev/null +++ b/woocommerce-wompi-payments.php @@ -0,0 +1,127 @@ +run_woocommerce_wompi_payments(); + +},0); + +function wompi_payments_plugin_init(){ + + static $plugin; + if (!isset($plugin)){ + require_once('includes/class-woocommerce-wompi-payments-plugin.php'); + $plugin = new Woocommerce_Wompi_Payments_Plugin(__FILE__, WOOCOMMERCE_WOMPI_PAYMENTS_VERSION, WOOCOMMERCE_WOMPI_PAYMENTS_NAME); + } + return $plugin; +} + +function requeriments_woocommerce_wompi_payments(){ + + $openssl_warning = 'Wompi Payments: Requires OpenSSL >= 1.0.1 to be installed on your server'; + + if ( ! defined( 'OPENSSL_VERSION_TEXT' ) ) { + if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { + add_action('admin_notices', function() use($openssl_warning) { + wompi_payments_admin_notices($openssl_warning); + }); + } + return false; + } + + preg_match( '/^(?:Libre|Open)SSL ([\d.]+)/', OPENSSL_VERSION_TEXT, $matches ); + if ( empty( $matches[1] ) ) { + if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { + add_action('admin_notices', function() use($openssl_warning) { + wompi_payments_admin_notices($openssl_warning); + }); + } + return false; + } + + if ( ! version_compare( $matches[1], '1.0.1', '>=' ) ) { + if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { + add_action('admin_notices', function() use($openssl_warning) { + wompi_payments_admin_notices($openssl_warning); + }); + } + return false; + } + + if ( !in_array( + 'woocommerce/woocommerce.php', + apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), + true + ) ) { + if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { + $woo = 'Wompi Payments: El plugin de woocommerce debe de estar activo'; + add_action('admin_notices', function() use($woo) { + wompi_payments_admin_notices($woo); + }); + } + return false; + } + + if (!in_array(get_woocommerce_currency(), array('COP'))){ + if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { + $currency = 'Wompi Payments: Requires COP currencie ' + . sprintf('%s', '' + . 'Click here to configure' . '' ); + add_action('admin_notices', function() use($currency) { + wompi_payments_admin_notices($currency); + }); + } + return false; + } + + $woo_countries = new WC_Countries(); + $default_country = $woo_countries->get_base_country(); + if (!in_array($default_country, array('CO'))){ + if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { + $country = 'Wompi Payments: It requires that the country of the store be in Colombia ' + . sprintf('%s', '' + . 'Click here to configure' . '' ); + add_action('admin_notices', function() use($country) { + wompi_payments_admin_notices($country); + }); + } + return false; + } + + return true; +} + +function wompi_payments_admin_notices( $notice ) { + ?> +
+

+
+