How to Accept Payments Through PayPal on Your Website

On
PayPal logo within a laptop screenNowadays, there are countless services and options to facilitate simple payment processing on a website. And, PayPal is one of such popular options. This guide will help you implement a PayPal button with support for credit card transactions. This tutorial is aimed to implement a simple payment system for processing—a one-time consolidated amount. The payment solution presented below is not a full-fledged eCommerce system. With basic web design knowledge, one can substantially customize the entire flow of events, before and after the payment is processed. If you offering a service that doesn't involve any kind of memberships or a recurring subscription model, you can use the solution given below to easily process payments from your customers. You can implement this payment processing system on any web page running on a secure HTTPS URL provided you have access to its source code. Let's get started and learn to integrate a custom yet simple payment processing system powered by the popular PayPal platform.

PayPal logo within a laptop screen You'll need a PayPal Business Account to get started with the process. A general PayPal account can be upgraded to a business account. There's no upgrade or monthly fee just for having a business account.

Read Also:
Best and Free Shopping Cart (eCommerce) Applications for Small Businesses

Once you have a verified and active PayPal business account, you can get started with the payment button integration process—immediately. So, here we go!

Prepare the Essentials Before Integrating the Code

Now that you have the PayPal business account ready, log in to the PayPal developer dashboard to complete two important and essential steps.

First of all, you need to create two sandbox accounts. The first one is the merchant sandbox account and the second one is the buyer sandbox account. The latter one can be omitted if you're just testing card processing transactions that don't require a PayPal account.

A PayPal sandbox account provides you with a simulated environment to test your integrated payment solution through dummy transactions.

Within your developer dashboard, go to the SANDBOX → Accounts → Create Account option to create both the sandbox accounts. Simply, fill in the required fields and options to create an account.

Like a regular PayPal account, you can also log in to your sandbox PayPal account to view and manage its settings and transactions.

The second important step that needs to be completed is the creation of an app to receive the credentials to be used for both the sandbox and live transactions. To do so, go to the My Apps & Credentials → Create App option.

Give the app an appropriate name of your choice and select the merchant sandbox account you want the app to be associated with. Click the button to finish the app creation process.

PayPal REST API credentials Once the app is created, you're provided with the API credentials for both the sandbox and live environments. The Client ID is what you'll use in the payment processing code integrated on the website. During the testing phase, use the sandbox API credentials.

Once both these important steps are completed within the developer dashboard, you can move on to the next phase of integrating the custom payment button code that meets your requirements.

Develop and Integrate Custom Payment Button Code

Now the code customization depends on your exact needs and requirements. For example, you may be looking to redirect a customer to a different web page after successful completion of the payment.

Or, you may want to keep the customer on the same web page throughout the entire payment process. This second approach is what we're going to implement in this tutorial. Keeping the customer on the same web page gives a better user experience to the visitor for simple payment routines.

Following are the prominent payment processing features you can follow and implement on your website.
  • Create a custom landing page for the service or product you're going to accept the payment for.
  • Keep the customer on the same web page throughout the entire transaction.
  • Authorize the customer and payment details and ask for the payment confirmation with the relevant details.
  • Once the payment is successful, clearly notify the customer about the same followed with all the post-payment details.
  • Implement an error handling routine to notify customer why the transaction was not successful.
  • Test, test, and test before making your payment button code—live!

Here's a real world live example of a PayPal payment button integration on a custom landing page.

Let's get started with the actual code from here onwards.

The 3 important parts directly related to the PayPal button are as follows.
  • The <div> container that renders the payment buttons at the desired location on the web page.
  • The checkout.js script that configures and runs the entire payment process. Ideally, include this important script in the <head> tag of the web page.
  • Our custom button configuration and rendering script to match with our exact requirements.
Here's how all the 3 parts are included in the web page.

<!--The div container where the payment buttons will appear-->
<div id="paypal-button"></div>

<!--The essential checkout.js script powering the entire payment system-->
<script src="https://www.paypalobjects.com/api/checkout.js"></script>

<!--Our custom script to configure the buttons and payment flow as per our needs-->
<script>
  paypal.Button.render({

    // Configure the environment and the payment system—here!
    
  }, '#paypal-button');
</script>
You can note that the ID paypal-button applied to the button rendering <div> tag is included in the environment configuration custom script too. The ID tag need not be exactly the same. You can give it some other meaningful name too.

Now, let's focus on the custom script and see how to configure the environment and the payment processing flow as per our needs. Though the latter part can be customized in different possible ways, I'll go ahead with the one I find the most user-friendly and suitable for both the customer and the merchant.

Environment and client configuration - The PayPal button code runs in two modes, viz., sandbox or production. Quite obviously, whenever you'll start building your custom payment button code, you'll start with the sandbox environment to facilitate thorough testing through dummy transactions.

Here's how to start with this configuration.

<script>
  paypal.Button.render({

    // Environment (sandbox/production) in which the entire payment system should run.
    env: 'sandbox',

    // The client ID (sandbox/production) API credentials) goes here.
    client: {
    sandbox: 'xxxxxxxxxxxxxxxxxx',
    production: 'xxxxxxxxxxxxxxxxxx'
    }

  }, '#paypal-button');
</script>
The code shown above is—quite simple! Through env:, we set the current environment. You can either use sandbox or production values for this option. Naturally, unless one is a PayPal code integration ninja, the process almost always start with a sandbox environment.

The second option client: integrates the payment button code with a specific PayPal developer account. In the first section of this tutorial, we've already learned about creating PayPal API credentials which are also known as client IDs.

That's what need to be copy-pasted here replacing the dummy xxxxxx.... string. Depending on the value provided for the env: option, the appropriate client ID will be automatically used from the client: section.

Button style, funding, and experience configuration - Next, we'll concentrate on customizing the look and feel of the payment buttons, the configuration of allowed and disallowed funding sources, and the configuration of the checkout experience. Here's how to do it.

<script>
  paypal.Button.render({


    // PayPal payment buttons customization options.
    style: {
      layout: 'vertical', 
      size:   'responsive', 
      shape:  'rect',  
      color:  'gold' 
    },

    // Configuration of available funding sources for the customers.
    funding: {
      allowed: [ paypal.FUNDING.CARD ],
      disallowed: [ paypal.FUNDING.CREDIT ]
    },

   // Various checkout experience options.
   experience: {
      input_fields: {
          no_shipping: 1
      } 
   },

   // Configuration of 'Pay Now' checkout flow.
   commit: true

  }, '#paypal-button');
</script>
The first button styling option style: is fairly simple. You can customize the appearance and layout of the buttons through the available customization options.

PayPal payment buttons Feel free to play with the styling options to get your preferred layout and appearance. The next option funding: configures the available ways through which a customer can make a payment.

For example, the value paypal.FUNDING.CARD for the option allowed: ensures that the credit card payment buttons are available for the customers.

Similarly, the value paypal.FUNDING.CREDIT for the option disallowed: denotes that the option to make a payment through PayPal Credit is not available for the customers. You can configure the preferred funding method as per your needs.

The next two options deal with the checkout experience. The no_shipping parameter with a value of 1 for the experience: option ensure that the shipping address is not displayed on the pages generated by PayPal.

If you're not delivering physical goods to the payer, you may use this option else you can skip it altogether. And, to initiate the payer-friendly 'Pay Now' checkout flow, use the value true for the commit: option. I'll strongly recommend activating this feature.

Payment configuration - The next important step involves configuration of the payment you're going to receive from the potential customers. As mentioned earlier, we're using this entire setup to receive a simple one-time payment for a simple service or a donation. Let's see how to do it.

<script>
  paypal.Button.render({


    // Payment configuration options.
    payment: function (data, actions) {
    return actions.payment.create({
      payment: {
        transactions: [
          {
            amount: {
              total: '99.00',
              currency: 'USD'
            },
            description: 'Write service/product description here'
          }
        ]
      }
    });
  }

  }, '#paypal-button');
</script>
Whenever a potential customer shows interest in your service or product and clicks the PayPal button, the payment: method is triggered through which you can configure and customize the payment information and data.

You can see in the sample code above how total: and currency: parameters are used to specify the amount of the purchase as well as its exact currency code.

Through the description: parameter, you can provide the information about the service or product you're selling. It appears both in the invoice as well as within the checkout process interface.

This is a barebones configuration of a simple payment. Advanced users can configure a more detailed payment structure for the prospects.

Payment authorization and execution configuration - The last yet the most important 2-step configuration process involve creating a custom checkout experience for the customer during the payment authorization and completion phase. Let's once again start with the minimal sample code.

<script>
  paypal.Button.render({


    // Payment authorization and completion configuration options.
    onAuthorize: function (data, actions) {
    
    return actions.payment.get().then(function (paymentDetails) {

                var fullname = paymentDetails.payer.payer_info.first_name + " " + paymentDetails.payer.payer_info.last_name;
                var shipping = paymentDetails.payer.payer_info.shipping_address;

                // Add your custom post-payment authorization dialogue for the customer.


        document.querySelector('#confirm-button').addEventListener('click', function () {

            // At this point, the customer has clicked the payment completion button.

            return actions.payment.execute().then(function () {
             
                // Add your custom post-payment completion dialogue for the customer.

              });
          });
      });
  }

  }, '#paypal-button');
</script>
Before moving ahead, let's try to understand the entire process through a graphic shown below. It's a 3-step process which completes on the same web page with any page redirections.

A working knowledge of JavaScript is essential to configure and customize this part of the checkout flow. You can either use vanilla JavaScript or a library like jQuery to configure this step.

PayPal checkout process Though a 3-step process can be reduced to a 2-step process, it's always a good practice to show a confirmation dialogue to the customer asking for his permission before actually charging for your product or service.

The onAuthorize: method is triggered as soon as the customer has filled in the payment and personal details and has clicked the Pay Now button.

The details entered by the customer may or may not get validated at this point. If it's the latter case, you must handle it and reset the entire payment process. To keep things simple, we'll skip this part.

If the submitted are validated successfully by PayPal, you can grab the available customer submitted details through the actions.payment.get() method.

You can see in the sample code above that I have grabbed the full name and the address of the customer and have stored this information in two JavaScript variables. You can use this information to populate the already hidden dialogue container with a confirmation button.

Thereafter, you must hide the PayPal buttons container and display the dialogue container you've already populated with the available customer details.

Naturally, at this juncture, we need to track the click on the confirmation button which we are doing through the addEventListener() function in our sample code. A production-grade implementation may have a cancellation button as well to nullify the process followed by a reset of the payment buttons.

As soon as the button is clicked, the payment is charged from the customer and the transaction is completed. At this point, the control passes to the actions.payment.execute() method.

Now you can hide the dialogue container of step 2 and must populate the final dialogue box with a thank you note and all the information you want to display to the customer after successful completion of the transaction. Thereafter, do not forget to make it visible on the screen.

Here's a live demo page to help you see the entire checkout flow through a dummy purchase.

And, last but not least, you must add a section to show error message occurring due to any reason. Here's how to do it.

<script>
  paypal.Button.render({


    // Handle errors during the checkout flow.
    onError: function (err) {

    // Show an error message to the customer.

  }

  }, '#paypal-button');
</script>
If the control reaches this error section, a simple reset of the payment buttons is not possible. You can show an error message and can refresh the entire page to let customer start the process again.

Make sure you've thoroughly tested your custom implementation before making it live on your website. For your convenience, I've bundled the entire sample code skeleton in a single file.

Download the complete PayPal button code template (Starter Kit)

If you're struggling to integrate this PayPal button system on your website and are looking to hire a professional to do it correctly, feel free to tweet or send a DM at my Twitter handle.