How to verify a credit card with Free API

Understanding credit card verification

The payment technology has come a long way since the advent of the credit and debit card. Due to the rising trend of online shopping, the growth of using credit cards as mobile payment is on the uptick in recent years. To keep up, companies continuously expand their payment options for customers, so do card verification. How do you tell if a credit card number is real? In the coming article, we would provide you an in-depth sight on card number validation on credit or debit card, in order to keep you and your business away from fraud and chargebacks. 

What exactly is Card Verification?

Card verification is a crucial step in the payment process which allows debit or credit cards. Due to the rising trend of online shopping, the growth of using credit cards as mobile payment is on the uptick in recent years. To keep up, companies continuously expand their payment options for customers, so do credit or debit card verification methods, in order to avoid fraud and chargebacks.

What will be checked during a card verification?

A credit card contains cardholder’s name, expiry date, card number and the card verification value(CVV). Have you ever wondered what a lengthy credit number means? Credit card numbers might look random to you. Yet, there are in fact some hidden meanings behind each group of numbers. In most credit card verification APIs, there are four components that will be verified during the verification.

There are four parts in the number:

  1. Major Industry Identifier (MII) — identifies the industry of the card. 
  2. Issuer Identification Number (IIN) — identifies the issuer of the card. American Express starts with 34 or 37, Mastercard starts with 2221–2720 or 51–55, Visa starts with 4. This is especially useful for future updates if card issuers ever decide to expand their IIN ranges.
  3. Account Number — identifies the customer’s account
  4. Checksum — makes sure that the account number is valid

Most of the credit cards including test credit card available in general comprise of the above components.

What exactly does an API do?

We all know that there are somethings we just don’t want do it manually. That’s where APIs come in. An API, or application programming interface, is a set of rules and specifications that allow two software programs to communicate with each other. Developers can build applications that work seamlessly together and make it possible for end-users to complete complex tasks with just a few clicks. By using an API, you can save yourself time and effort of having to write your own code from scratch. Let’s take a closer look at what an API is and how you can use it in your own development projects. If you want to know more about what an API is, check this link out.

For example, imagine being able to book a flight, hotel, and rental car all in one place by using just a few taps on your smartphone. This would not be possible without APIs! As the world becomes increasingly interconnected, the importance of well-designed APIs will only continue to grow.

What is a Credit card Validator? How does it work?

How does credit card validation work? Does it just compare the digits in your card number to a MasterCard or Visa database? Turns out, it’s a bit more complicated than that. To check with the card numbers, as well as other cardholder information, we can create a credit card validator API to check all credit card components at a time.

A Credit Card Validator API initiates requests that verifies whether a payment token is valid. Before attempting to convert a temporary, single-use token into a permanent-use token, it gives a POST request to the verifications endpoint with a card object containing the card details you wish to check.

Number Check

{
  card: {
    niceType: 'American Express',
    type: 'american-express',
    gaps: [4, 10],
    lengths: [15],
    code: {name: 'CID', size: 4}
  },
   
  isPotentiallyValid: true, // if false, indicates there is no way the card could bevalid,
 
  isValid: true // if true, number is valid forsubmission
}

If a valid card type cannot be determined, the card field in the response will be null. 

Holder Name Check

{
    isPotentiallyValid: true,
    isValid: true
}

If a cardholder name is comprised of only numbers, hyphens and spaces, the validator considers it to be too card-like to be valid, but may still be potentially valid if a non-numeric character is added. This is to prevent card number values from being sent along as the cardholder name but not make too many assumptions about a person’s cardholder name. If a cardholder name is longer than 255 characters, it is assumed to be invalid.

Expire Date Check

{
  isPotentiallyValid: true, // if false, indicates there is no way this could be valid in the future
   
  isValid: true,
   
  month: '10', // a string with the parsed month if valid, null if either month or year are invalid
   
  year: '2016' // a string with the parsed year if valid, null if either month or year are invalid
}

expirationDate will parse strings in a variety of formats:

InputOutput
'2019-10'{month: '10', year: '2019'}
'10/2019'
'10 / 2019'
'102019'
'10 2019'
'10 19'
{month: '10', year: '2019'}
'10/19'
'10 / 19'
'1019'
'10 19'
{month: '10', year: '19'}

CVV Check

The cvv validation by default tests for a numeric string of 3 characters in length. The maxLength can be overridden by passing in an integer as a second argument. You would typically switch this length from 3 to 4 in the case of an American Express card which expects a 4 digit CID.

{
  isPotentiallyValid: true,
  isValid: true
}

You can optionally pass minLength as a property of an object as a second argument. This will override the default min length of 3.

valid.postalCode('123', {minLength: 5});
 
{
  isPotentiallyValid: true,
  isValid: false
}

Create your own Credit Card Validator API

To do that, you’ll need a suitable Credit card API provider. Using OpenAPIHub’s API, here’s how you can proceed:

Why should you choose this Validator API server?

The Credit card verification API is supported by OpenAPIHub, an All-in-one API Platform that supports API Needs and it is certified as “AWS Qualified Software” since 2022. You can register for an API portal for free, share and monetise APIs easily on the trustable platform certified by ISO27001.

Prerequisites

You will need a suitable API provider. Using FiberConnect’s API supported by OpenAPIHub, you can proceed easily as follows :

1. OpenAPIHub Developer Account

You need to sign up for an OpenAPIHub developer account in order to subscribe and access this API. For more information, please refer to “Register as a Developer“.

2. Active API Subscription

You need to subscribe to this API before consuming it. Many APIs come with a free trial plan so that you can experience the API functions provided free of charge. For more information, please refer to “Subscribe to APIs“.

3. API Credential

An API Key is required to access the API. It can be obtained in the Developer Admin Portal once you have completed the signup to OpenAPIHub. For more information, please refer to “Create API Key“.

You may check out the full API documentation here in the OpenAPIHub.

Make a Credit Card Validator API request with Vue.js

Below is the full script of the Vue.js. You may add this to the IDE.

const endpoint = 'https://trial-api-credit-card-validator-4sfb.gw.openapihub.com/credit-card';
 
new Vue({
  el: '#app',
  data() {
    return {
      number: '',
      name: '',
      expiry_date: '',
      cvv: '',
      apikey: '',
      result: '',
      error: ''
    }
  },
  methods: {
    validate: async function() {
      const axiosConfig = {
        headers: {
          'content-type': 'application/json',
          'x-openapihub-key': this.apikey
        }
      }
 
      const requestBodyCheckNumber = {
        'number': this.number,
        'luhnValidateUnionPay': true,
        'maxLength': 16
      }
      await axios.post(`${endpoint}/number-check`, requestBodyCheckNumber, axiosConfig)
        .then(async res => {
          this.error = ''
          if (res.data.isValid && res.data.isPotentiallyValid) {
            const requestBodyCheckName = {
              'name': this.name
            }
            await axios.post(`${endpoint}/holder-name-check`, requestBodyCheckName, axiosConfig)
              .then(async res => {
                this.error = ''
                if (res.data.isValid && res.data.isPotentiallyValid) {
                  const requestBodyCheckExpiryDate = {
                    'date': `${this.expiry_date.substr(5)}/${this.expiry_date.substr(2, 2)}`,
                    'maxElapsedYear': `${new Date().getYear() + 10}`
                  }
                  await axios.post(`${endpoint}/expire-date-check`, requestBodyCheckExpiryDate, axiosConfig)
                    .then(async res => {
                      this.error = ''
                      if (res.data.isValid && res.data.isPotentiallyValid) {
                        const requestBodyCheckCvv = {
                          'cvv': this.cvv,
                          'maxLength': 3
                        }
                        await axios.post(`${endpoint}/cvv-check`, requestBodyCheckCvv, axiosConfig)
                          .then(res => {
                            this.error = ''
                            if (res.data.isValid && res.data.isPotentiallyValid) {
                              this.result = `Result -<br>Valid`
                            } else {
                              this.result = `Result -<br>Invalid CVV`
                            }
                          }).catch(err => {
                            this.error = `Error occurred -<br>${err.response.data.message}`
                            console.log('Error', err.response.data.message)
                          })
                      } else {
                        this.result = `Result -<br>Invalid Expiry Date`
                      }
                    }).catch(err => {
                      this.error = `Error occurred -<br>${err.response.data.message}`
                      console.log('Error', err.response.data.message)
                    })
                } else {
                  this.result = `Result -<br>Invalid Holder's Name`
                }
              }).catch(err => {
                this.error = `Error occurred -<br>${err.response.data.message}`
                console.log('Error', err.response.data.message)
              })
          } else {
            this.result = `Result -<br>Invalid Card Number`
          }
        }).catch(err => {
          this.error = `Error occurred -<br>${err.response.data.message}`
          console.log('Error', err.response.data.message)
        })
 
 
    }
  }
})

Make an User Interface for the API

It’s quire hard to attract more users if your API do not have an easy-to-use user interface. Follow the below HTML to create a backbone of your UI. 

<div id="app">
  <div class="demo-description">
    <h2>Credit Card Validator</h2>
    <span>To protect your credentials.</span>
    <br>
    <span>DO NOT save this API Key in the code sandbox!!</span>
  </div>
  <div class="test-area">
    <div class="input-area">
      <span>API Key</span>
      <input
        type="text"
        placeholder="Input your key here"
        v-model="apikey"
      >
      <br>
       
      <span>Card Number</span>
      <input
        type="tel"
        placeholder="Card Number"
        v-model="number"
      >
      <br>
       
      <span>Holder's Name</span>
      <input
        type="text"
        placeholder="Holder's Name"
        v-model="name"
      >
      <br>
       
      <span>Expiry Date</span>
      <input
        type="month"
        v-model="expiry_date"
      >
      <br>
       
      <span>CVV</span>
      <input
        type="tel"
        placeholder="CVV"
        v-model="cvv"
      >
      <br>
      <button v-on:click="validate">Validate</button>
    </div>
 
    <div class="output-area">
      <template v-if="error">
        <span v-html="error" />
      </template>
      <template v-else-if="!result">
        Fill in API Key, Card Number, Holder's Name, Expiry Date and CVV, then press "Validate".
      </template>
      <template v-else>
        <div v-html="result" />
      </template>
    </div>
  </div>
</div>

Then, add some dressings for your dish. Put the CSS script to decorate your UI. 

@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap');
body {
  background: #20262E;
  padding: 20px;
  font-family: 'Open Sans', sans-serif;
}
  
#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  /* height: 400px; */
}
  
.demo-description {
  text-align: center;
  margin-bottom: 20px;
}
  
.demo-description h2 {
  font-weight: semibold;
  margin-bottom: 5px;
}
  
.demo-description span {
  color: #999999;
}
  
.test-area {
  display: flex;
}
  
.input-area {
  text-align: right;
}
  
.input-area span {
  display: inline-block;
  line-height: 48px;
  margin-right: 8px;
  text-align: right;
  width: 150px;
}
  
.input-area input, select {
  border: 1px solid #999999;
  border-radius: 3px;
  height: 30px;
  width: 150px;
  padding: 0 7px;
}
 
.input-area select {
  height: 32px;
  width: 166px;
}
  
.input-area input::placeholder {
  color: #d0d0d0;
}
  
.input-area button {
  background-color: #57abf0;
  border: 0;
  border-radius: 4px;
  color: #ffffff;
  font-weight: 600;
  margin-top: 15px;
  width: 166px;
  padding: 15px 10px;
}
  
.output-area {
  color: #505050;
  font-size: 14px;
  margin: 20px;
  margin-right: 0px;
  width: calc(100% - 350px);
}
  
@media screen and (max-width: 616px) {
  .input-area {
    text-align: center;
  }
 
  .input-area span {
    text-align: left;
  }
    
  .output-area {
    width: calc(100% - 150px);
  }
    
  .input-area button {
    width: 140px;
    padding: 10px 7px;
  }
}
  
.output-area svg {
  transform: scale(0.7) translateX(-30px) translateY(-95px);
}

Verify your credit card now

Now that we have all the materials prepared. Let’s have a try on our work now!

Simply fill in the form with API key, Card number, Holder’s name, Expiry Date and the CVV. Press “Validate”. Swiftly, you can get your result for verification.

And the output is as follows:

Conclusion

As the trend of credit card payment is still lifting up, credit card validation would be getting more and more essential and common for online merchants and customers. By understanding how they work and how to create a Credit Card validator API, you can create custom validation with easy-to-use method generator for your developing softwares or applications. What are waiting for? Hands on more free APIs on OpenAPIHub now!

Next Steps?

Try out our free Validator API Now in OpenAPIHub and see how easy it is to facilitate your business, projects or work now! 

OpenAPIHub is an API Platform that help you define API subscription and enable API Monetization with ease. Check the following 2-min What is OpenAPIHub video for more and try OpenAPIHub for Free!

Ready to Start Your API Journey?

Join OpenAPIHub and connect to the fast growing API Hub Community to grow your API Business today!

Start for Free