Reading list Switch to dark mode

    How to add cc form in custom payment method in magento2

    Updated 26 March 2024

    Here, I am explaining that how to add cc form in custom payment method in magento2. For this you have to read this block Create custom payment method in magento2. In this block explain how to create  custom payment method.

    After creating custom payment method you have to add following file for adding cc form in payment method.

    1 – Update app/code/Test/Module/view/frontend/web/template/payment/testpayment.html In this file call cc form html.

    <div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}">
        <div class="payment-method-title field choice">
            <input type="radio"
                   name="payment[method]"
                   class="radio"
                   data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/>
            <label data-bind="attr: {'for': getCode()}" class="label"><span data-bind="text: getTitle()"></span></label>
        </div>
        <div class="payment-method-content">
            <div class="payment-method-billing-address">
                <!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->
                <!-- ko template: getTemplate() --><!-- /ko -->
                <!--/ko-->
            </div>
            <form class="form" id="pay" action="#" name="pay" method="post" >
                <!-- ko template: 'Test_Module/payment/testpayment-form' --><!-- /ko -->
            </form>
            <div class="actions-toolbar">
                <div class="primary">
                    <button class="action primary checkout"
                            type="submit"
                            data-bind="
                            click: placeOrder,
                            attr: {title: $t('Place Order')},
                            css: {disabled: !isPlaceOrderActionAllowed()},
                            enable: (getCode() == isChecked())
                            "
                            disabled>
                        <span data-bind="i18n: 'Place Order'"></span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    2 – add app/code/Test/Module/view/frontend/web/template/payment/testpayment-form.html . In this file create cc form.

    <fieldset data-bind="attr: {class: 'fieldset payment items ccard ' + getCode(), id: 'payment_form_' + getCode()}">
        <legend class="legend">
            <span><!-- ko i18n: 'Credit Card Information'--><!-- /ko --></span>
        </legend><br />
        <div class="field type">
            <div class="control">
                <ul class="credit-card-types">
                    <!-- ko foreach: {data: getCcAvailableTypesValues(), as: 'item'} -->
                    <li class="item" data-bind="css: {
                                                     _active: $parent.selectedCardType() == item.value,
                                                     _inactive: $parent.selectedCardType() != null && $parent.selectedCardType() != item.value
                                                     } ">
                    </li>
                    <!--/ko-->
                </ul>
                <input type="hidden"
                       name="payment[cc_type]"
                       class="input-text"
                       value=""
                       data-bind="attr: {id: getCode() + '_cc_type', 'data-container': getCode() + '-cc-type'},
                       value: creditCardType
                       ">
            </div>
        </div>
        <div class="field number required">
            <label data-bind="attr: {for: getCode() + '_cc_number'}" class="label">
                <span><!-- ko i18n: 'Credit Card Number'--><!-- /ko --></span>
            </label>
            <div class="control">
                <input type="number" name="payment[cc_number]" class="input-text" value=""
                       data-bind="attr: {
                                        autocomplete: off,
                                        id: getCode() + '_cc_number',
                                        title: $t('Credit Card Number'),
                                        'data-container': getCode() + '-cc-number',
                                        'data-validate': JSON.stringify({'required-number':true, 'validate-card-type':getCcAvailableTypesValues(), 'validate-card-number':'#' + getCode() + '_cc_type', 'validate-cc-type':'#' + getCode() + '_cc_type'})},
                                  enable: isActive($parents),
                                  value: creditCardNumber,
                                  valueUpdate: 'keyup' "/>
            </div>
        </div>
        <div class="field date required" data-bind="attr: {id: getCode() + '_cc_type_exp_div'}">
            <label data-bind="attr: {for: getCode() + '_expiration'}" class="label">
                <span><!-- ko i18n: 'Expiration Date'--><!-- /ko --></span>
            </label>
            <div class="control">
                <div class="fields group group-2">
                    <div class="field no-label month">
                        <div class="control">
                            <select  name="payment[cc_exp_month]"
                                     class="select select-month"
                                     data-bind="attr: {id: getCode() + '_expiration', 'data-container': getCode() + '-cc-month', 'data-validate': JSON.stringify({required:true, 'validate-cc-exp':'#' + getCode() + '_expiration_yr'})},
                                                enable: isActive($parents),
                                                options: getCcMonthsValues(),
                                                optionsValue: 'value',
                                                optionsText: 'month',
                                                optionsCaption: $t('Month'),
                                                value: creditCardExpMonth">
                            </select>
                        </div>
                    </div>
                    <div class="field no-label year">
                        <div class="control">
                            <select name="payment[cc_exp_year]"
                                    class="select select-year"
                                    data-bind="attr: {id: getCode() + '_expiration_yr', 'data-container': getCode() + '-cc-year', 'data-validate': JSON.stringify({required:true})},
                                               enable: isActive($parents),
                                               options: getCcYearsValues(),
                                               optionsValue: 'value',
                                               optionsText: 'year',
                                               optionsCaption: $t('Year'),
                                               value: creditCardExpYear">
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- ko if: (hasVerification())-->
        <div class="field cvv required" data-bind="attr: {id: getCode() + '_cc_type_cvv_div'}">
            <label data-bind="attr: {for: getCode() + '_cc_cid'}" class="label">
                <span><!-- ko i18n: 'Card Verification Number'--><!-- /ko --></span>
            </label>
            <div class="control _with-tooltip">
                <input type="number"
                       autocomplete="off"
                       class="input-text cvv"
                       name="payment[cc_cid]"
                       value=""
                       data-bind="attr: {id: getCode() + '_cc_cid',
                            title: $t('Card Verification Number'),
                            'data-container': getCode() + '-cc-cvv',
                            'data-validate': JSON.stringify({'required-number':true, 'validate-card-cvv':'#' + getCode() + '_cc_type'})},
                            enable: isActive($parents),
                            value: creditCardVerificationNumber" />
                <div class="field-tooltip toggle">
                    <span class="field-tooltip-action action-cvv"
                          tabindex="0"
                          data-toggle="dropdown"
                          data-bind="attr: {title: $t('What is this?')}, mageInit: {'dropdown':{'activeClass': '_active'}}">
                        <span><!-- ko i18n: 'What is this?'--><!-- /ko --></span>
                    </span>
                </div>
            </div>
        </div>
        <!-- /ko -->
    </fieldset>

    3 – Update app/code/Test/Module/view/frontend/web/js/view/payment/method-renderer/testpayment.js add some method related cc form.Which file using to get data from config provider.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    define(
        [
            'underscore',
            'Magento_Checkout/js/view/payment/default',
            'Magento_Payment/js/model/credit-card-validation/credit-card-data',
            'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator',
            'mage/translate'
        ],
        function (_, Component, creditCardData, cardNumberValidator, $t) {
            'use strict';
    
            return Component.extend({
                defaults: {
                    template: 'Test_Module/payment/testpayment',
                    creditCardType: '',
                    creditCardExpYear: '',
                    creditCardExpMonth: '',
                    creditCardNumber: '',
                    creditCardSsStartMonth: '',
                    creditCardSsStartYear: '',
                    creditCardVerificationNumber: '',
                    selectedCardType: null
                },
                initObservable: function () {
                    this._super()
                        .observe([
                            'creditCardType',
                            'creditCardExpYear',
                            'creditCardExpMonth',
                            'creditCardNumber',
                            'creditCardVerificationNumber',
                            'creditCardSsStartMonth',
                            'creditCardSsStartYear',
                            'selectedCardType'
                        ]);
                    return this;
                },
    
                initialize: function() {
                    var self = this;
                    this._super();
    
                    //Set credit card number to credit card data object
                    this.creditCardNumber.subscribe(function(value) {
                        var result;
                        self.selectedCardType(null);
    
                        if (value == '' || value == null) {
                            return false;
                        }
                        result = cardNumberValidator(value);
    
                        if (!result.isPotentiallyValid && !result.isValid) {
                            return false;
                        }
                        if (result.card !== null) {
                            self.selectedCardType(result.card.type);
                            creditCardData.creditCard = result.card;
                        }
    
                        if (result.isValid) {
                            creditCardData.creditCardNumber = value;
                            self.creditCardType(result.card.type);
                        }
                    });
    
                    //Set expiration year to credit card data object
                    this.creditCardExpYear.subscribe(function(value) {
                        creditCardData.expirationYear = value;
                    });
    
                    //Set expiration month to credit card data object
                    this.creditCardExpMonth.subscribe(function(value) {
                        creditCardData.expirationYear = value;
                    });
    
                    //Set cvv code to credit card data object
                    this.creditCardVerificationNumber.subscribe(function(value) {
                        creditCardData.cvvCode = value;
                    });
                },
    
                isActive: function () {
                    return true;
                },
    
                getCcAvailableTypes: function() {
                    return window.checkoutConfig.payment.testpayment.availableTypes['testpayment'];
                },
    
                getCcMonths: function() {
                    return window.checkoutConfig.payment.testpayment.months['testpayment'];
                },
    
                getCcYears: function() {
                    return window.checkoutConfig.payment.testpayment.years['testpayment'];
                },
    
                hasVerification: function() {
                    return window.checkoutConfig.payment.testpayment.hasVerification['testpayment'];
                },
    
                getCcAvailableTypesValues: function() {
                    return _.map(this.getCcAvailableTypes(), function(value, key) {
                        return {
                            'value': key,
                            'type': value
                        }
                    });
                },
                getCcMonthsValues: function() {
                    return _.map(this.getCcMonths(), function(value, key) {
                        return {
                            'value': key,
                            'month': value
                        }
                    });
                },
                getCcYearsValues: function() {
                    return _.map(this.getCcYears(), function(value, key) {
                        return {
                            'value': key,
                            'year': value
                        }
                    });
                }
            });
        }
    );

    4 – Add app/code/Test/Module/etc/frontend/di.xml.Using this map with config provider.

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="Magento\Checkout\Model\CompositeConfigProvider">
            <arguments>
                <argument name="configProviders" xsi:type="array">
                    <item name="test_module_configprovider" xsi:type="object">Test\Module\Model\TestpaymentConfigProvider</item>
                </argument>
            </arguments>
        </type>
    </config>

    5 – Add app/code/Test/Module/Model/TestpaymentConfigProvider.php.Using getConfig method set data for checkout config.

    <?php
    
    namespace Test\Module\Model;
    
    use Magento\Checkout\Model\ConfigProviderInterface;
    use Magento\Framework\View\Asset\Source;
    
    class TestpaymentConfigProvider implements ConfigProviderInterface
    {
        /**
        * @param CcConfig $ccConfig
        * @param Source $assetSource
        */
        public function __construct(
            \Magento\Payment\Model\CcConfig $ccConfig,
            Source $assetSource
        ) {
            $this->ccConfig = $ccConfig;
            $this->assetSource = $assetSource;
        }
    
        /**
        * @var string[]
        */
        protected $_methodCode = 'testpayment';
    
        /**
        * {@inheritdoc}
        */
        public function getConfig()
        {
            return [
                'payment' => [
                    'testpayment' => [
                        'availableTypes' => [$this->_methodCode => $this->ccConfig->getCcAvailableTypes()],
                        'months' => [$this->_methodCode => $this->ccConfig->getCcMonths()],
                        'years' => [$this->_methodCode => $this->ccConfig->getCcYears()],
                        'hasVerification' => $this->ccConfig->hasVerification(),
                    ]
                ]
            ];
        }
    }

    After adding above file.flush cache and check checkout page.

    cc form in custom payment method

    Using above approach we can add cc form in custom payment method.
    I hope this blog will help you.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    3 comments

  • Bhanwar Singh
    • Neelesh Singh (Moderator)
  • Naveed Ramzan
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home