WooCommerce 2.1 includes a standardised credit card form which payment gateway plugins can now utilise for a consistent UI.
This functionality is aimed at direct gateways where the credit card form is shown on the checkout – it shouldn’t be needed for any others. Here’s how to support it.
1. Declare support
In your main gateway class, you’ll first need to add the
supports variable and ensure that contains
default_credit_card_form. By default,
supports is an array containing only ‘products’, so you can append it:
$this->supports = 'default_credit_card_form';
2. Modify your payment_fields method
If you don’t have a ‘payment_fields’ method you can ignore this step, but if you had a credit card form previously you most likely will.
Remove the method to let core handle the output of the form, or if you really need the method, output the form manually using:
That will output the new-style form in the payment area on the checkout.
3. Modify your form handler
Next you’ll need to ensure your gateway is looking for the correct post data, as the field names may have changed. By default, the credit card form will post the following fields:
You’ll want to format these values as necessary, for example you may want to remove spaces and dashes from the credit card number, or reformat the expiry from the default ‘MM/YY’ format to something your gateway requires.
Need something custom?
If you need a more custom form, but still want to use our scripts and styles, you have two options:
1. Use the credit_card_form() method
credit_card_form() takes two arguments – $args and $fields.
$args only consists of
fields_have_names in 2.1, so if you passed in:
$args = array( 'fields_have_names' => false )
This would result in the credit card form fields having no ‘names’ thus preventing them from being posted. This is useful for gateways like Stripe where the values are not posted, and are instead tokenised via another script.
$fields lets you pass in your own fields to change the default ones. You should look at the inline documentation for notes on the usage of this.
2. Use the filters and actions
woocommerce_credit_card_form_args– filters the args array letting you change
woocommerce_credit_card_form_fields– filters the default fields should you need to change them globally
woocommerce_credit_card_form_start– action fired before the fields are output to the credit card form
woocommerce_credit_card_form_end– action fired after the fields are output to the credit card form
That wasn’t too hard now was it🙂 Using the default credit card form should be a great time saver for gateway developers, and should ultimately improve the experience for end-users too. Win win.