Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

PayPal REST API Recurring Payment via Stored Credit Card

0.00/5 (No votes)
13 Mar 2015 1  
The tip explains how to make recurring payments using the Stored Credit Cards in the Paypal Vault.

Introduction

This is my 2nd post and it is a successor of my 1st article here. I am trying to explain the Recurring Payments using Paypal here via Credit Cards.

Background

A little knowledge is required about the Paypal REST API and the pre-requisites from the 1st article. If you have not read my previous article and you are new to PAYPAL REST API, I highly recommend you to read the 1st article here.

Using the Code

You can setup the code environment as well from the 1st article. This code is just an extension to the previous project only. We just need to add some more functions to the code which will save the Credit Card details of the user in the Paypal Vault and return the token to you.

We need to save this token returned by the Paypal Server at our end. This token will be used to make the recurring payment automatically by your system or website.

PaypalCCModel class is for storing the Credit Card data in an Object. You need to instantiate this Object and fill details in it and then call the function StoreCreditCardInPaypal.

    public class PaypalCCModel
    {
        public string nostore { get; set; }
        public string Number { get; set; }
        public string cvv2 { get; set; }
        public string Type { get; set; }
        public string ExpireMonth { get; set; }
        public string ExpireYear { get; set; }
    }

Storing the CreditCard information in the PayPal Server

    private bool StoreCreditCardInPaypal(PaypalCCModel ccmodel)
    {
            //Creating the CreditCard Object and assigning values
            CreditCard credtCard = new CreditCard();
            credtCard.expire_month = int.Parse(ccmodel.ExpireMonth);
            credtCard.expire_year = int.Parse(ccmodel.ExpireYear);
            credtCard.number = ccmodel.Number;
            credtCard.type = ccmodel.Type.ToLower();
            credtCard.cvv2 = ccmodel.cvv2;

            try
            {
                //Getting the API Context to authenticate the call to Paypal Server
                APIContext apiContext = Configuration.GetAPIContext();
                // Storing the Credit Card Info in the PayPal Vault Server
                CreditCard createdCreditCard = credtCard.Create(apiContext);

                //Saving the User's Credit Card ID returned by the PayPal
                //You can use this ID for future payments via User's Credit Card
                SaveCardID(User.Identity.Name,createdCreditCard.id);
                
            }
            catch (PayPal.PayPalException ex)
            {
                Logger.LogError("Error: "+ex.Message);
                return false;
            }
            catch (Exception ex)
            {
                Logger.LogError("Error: "+ex.Message);
            }

            return true;
    }

In SaveCardID function, I am just storing the CreditCard ID returned by PayPal in the database. You can write your own function for saving it.

Now, below is the function that makes the payment using the stored credit cards. It uses the ID which was returned in the function StoreCreditCardInPaypal.

public bool PaymentViaStoredCard()
{
            // Preparing Item
            Item item = new Item();
            item.name = "Item Name";
            item.currency = "USD";
            item.price = "1";
            item.quantity = "1";
            item.sku = "sku-1123324";

            List<item> itms = new List<item>();
            itms.Add(item);
            ItemList itemList = new ItemList();
            itemList.items = itms;

            //Here is the Credit Card detail which we need to use from our database
            CreditCardToken credCardToken = new CreditCardToken();
            //Here, we are assigning the User's Credit Card ID which we saved in Database
            credCardToken.credit_card_id = "CARD-5MY32504F4899612AKIHAQHY";

            //Specify Payment Details
            Details details = new Details();
            details.shipping = "1";
            details.subtotal = "1";
            details.tax = "1";

            //Specify the Total Amount
            Amount amnt = new Amount();
            amnt.currency = "USD";
            // Total must be equal to the sum of shipping, tax and subtotal.
            amnt.total = "3";
            amnt.details = details;

            //Create Transaction Object
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "This is the recurring payment transaction";
            tran.item_list = itemList;

            //Adding the transaction above to the list
            List<transaction> transactions = new List<transaction>();
            transactions.Add(tran);

            //Specifying the funding Instrument here.
            //Notice that we are not using any credit card details here
            //But we are using the Credit Card Object which has the Card ID
            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card_token = credCardToken;

            //Adding the Funding Instrument to the list
            List<fundinginstrument> fundingInstrumentList = new List<fundinginstrument>();
            fundingInstrumentList.Add(fundInstrument);

            //Specify the fundind Instrument List and Payment Method as Credit Card
            //Because we are making the payment using the store Credit Card
            Payer payr = new Payer();
            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method = "credit_card";

            //Finally Making payment Object and filling it with values
            Payment pymnt = new Payment();
            pymnt.intent = "sale";
            pymnt.payer = payr;
            pymnt.transactions = transactions;

            try
            {
                //Getting the API Context to authenticate the Call to Paypal Server
                APIContext apiContext = Configuration.GetAPIContext();

                // Making the payment using a valid APIContext
                Payment createdPayment = pymnt.Create(apiContext);
            }
            catch (PayPal.PayPalException ex)
            {
                Logger.LogError("Error: "+ex.Message);
            }
}

Now, you can check the payment state in the object createdPayment as earlier in the 1st article.

For making the recurring payments, you can implement your own logic code and use the above function to make the payment from your clients automatically.

For Showing Credit Card Details to user

If you need to see the credit card or you might need to show it to the users on demand.

For example, if a user wants to see from which credit card of his, recurring payments are being done. Then, you can show his card details with the code snippet below. We will use the Credit Card ID which we have stored at our end for fetching the details.

public void GetCreditCardDetailsFromVault()
{
            try
            {
                //Getting the API Context to authenticate the call
                APIContext apiContext = Configuration.GetAPIContext();

                //Getting the Credit Card Details from paypal
                //By sending the Card ID saved at our end
                CreditCard card = CreditCard.Get(apiContext, "CARD-00N04036H5458422MKRIAWHY");
            }
            catch (PayPal.PayPalException ex)
            {
                Logger.LogError("Error: "+ex.Message);
            }
}

You will get the Card Details in the card object above.

Deleting a Card from the Vault

There might be a case where user wants to change his card details and add another card for the recurring Payments. Then, you will need to delete the old card details and store new card details in the vault. When we do this, the ID returned by the Paypal is changed for the new card. Because the Previous card details will be deleted completely from the paypal and we will need to create a new entry in the vault because there is no way to replace the details. We have add new.

public void DeleteCreditCardFromVault()
{
            try
            {
                // Getting the API Context for authentication the call to paypal server
                APIContext apiContext = Configuration.GetAPIContext();

                //get the credit card from the vault to delete
                CreditCard card = CreditCard.Get(apiContext, "CARD-00N04036H5458422MKRIAWHY");

                 // Delete the credit card
                card.Delete(apiContext);

            }
            catch (PayPal.PayPalException ex)
            {
                Logger.LogError("Error: "+ex.Message);
            }
}

That's it!! If you have any queries, you can ask me.

Thanks for reading!!

Points of Interest

Recurring Payments is very interesting and widely used by the Services Website for regular payments from their clients in Automated Fashion. It is really an interesting concept of PayPal.

History

  • 13th March 2015: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here