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

PayPal Payment using C# REST Server SDK

0.00/5 (No votes)
17 Jan 2017 1  
This article describes PayPal payment options and gives an example of how to use PayPal REST server API for payment with sample code.

Introduction

PayPal allow merchants to add payment functionality in their site and allow user to purchase their product in a secured environment. Merchant can integrate PayPal in their site to take the user directly in PayPal site and pay using PayPal login or can customize their site for payment checkout and use PayPal REST API call in the backend.

PayPal provide different products and solutions for payment.

  1. Braintree v.zero SDK
  2. Payment Buttons
  3. Payment REST API
  4. PayPal Here
  5. Express Checkout
  6. Shopping Carts
  7. PayPal Pro / Payflow
  8. Website Payment Pro
  9. Mobile SDK

Categorization

According to implementation in a site, PayPal services may be categorize following ways.

  1. Express Checkout
    • Payment Buttons
  2. Direct Payment
    • REST API Call from client
    • REST API Server SDK
    • SOAP APIs
    • v.zero SDK
    • Mobile SDK etc.

REST API Server SDK

PayPal provide a SDK for .NET developer. Using SDK, developer can easily complete a payment by calling a function with appropriate parameters. PayPal allow the following type of operations using SDK.

Using REST Server SDK we can perform the following Payment related operations.

  1. Billing Agreement
  2. Billing Plans
  3. Identity
  4. Invoicing
  5. Payment Experience
  6. Payments
  7. Payouts
  8. Vault
  9. Webhooks

Credential

PayPal supply keys to use as credential. We can get these two keys by creating an App in the PayPal Development account. Save these two keys in the Web.config or somewhere else to use for the API request call. These two keys are named as,

  1. Client ID
  2. Secret Key

PayPal Environments

PayPal provide two types of environment

  1. Sandbox or Development
  2. Live or Production

How to Setup the Development environment?

The steps to setup the development environment is as follows:

  1. Sign Up on paypal.com for a Business Account.
  2. Next login into PayPal developer site https://developer.paypal.com using the PayPal credential.
  3. Create a new App in development environment. It will give the keys as Client ID and a Secret key for credential.
  4. If you click on Sandbox Accounts link it will display the test account created for Development. One for merchant and one for buyer. Use these account for test payment.
  5. If you open the buyer details information, it will show you the test credit card information which will be used for test transaction during development.

Sample Project

The sample project is divided into two parts Client and Server. The client is developed using form.io form builder framework, AngularJS and JQuery. The client project has a built in form to take credit card information and a submit button to submit a request to the server project.

On the other hand Server receives the request from client and execute a payment API call to the PayPal server with appropriate card information and shipping address. If payment is completed successfully PayPal return an object back to the server and server send it back to client.

The sample form UI is shown below

The keys stored in web.config file is shown below

<appSettings>
    <add key="mode" value="sandbox" />
    <add key="connectionTimeout" value="360000" />
    <add key="requestRetries" value="1" />
    <add key="clientId" value="AcfYDG1vKiEYRfwUforCnWEub0w3QkRoErFkSOL3VRl4iEd_N-qrj76ydpnxdlxE3Ujxy0lbSpzLELSv" />
    <add key="clientSecret" value="EBF7_ov-w-HFyatwGPAsL9vbNDECp3wG5sA_e1Rx-_rgSEmWwSOIW_jPj8dF_GNJx59JXFFHQUQXrrtE" />
  </appSettings>

Server side code to use these two keys are

public static class PayPalConfig
    {
        public readonly static string ClientId;
        public readonly static string ClientSecret;

        static PayPalConfig()
        {
            ClientId = ConfigurationManager.AppSettings["clientId"];
            ClientSecret = ConfigurationManager.AppSettings["clientSecret"];
        }
        /*More Code*/
    }

PayPal SDK supply an abstract class named BaseSamplePage. We need to inherit this class in our own custom class.

The abstract class sample code

public abstract class BaseSamplePage
    {
        protected RequestFlow flow;

        public RequestFlow GetFlow()
        {
            this.RegisterSampleRequestFlow();
            try
            {
                this.RunSample();
            }
            catch (Exception ex)
            {
                this.flow.RecordException(ex);
                throw ex;
            }
            return flow;
        }
        protected abstract void RunSample();

        protected void RegisterSampleRequestFlow()
        {
            if(this.flow == null)
            {
                this.flow = new RequestFlow();
            }
            HttpContext.Current.Items["Flow"] = this.flow;
        }
    }

The custom class summary code

public class PayPalRequest : BaseSamplePage
    {
        private CardInput cardInput;
        public PayPalRequest(CardInput inputPar)
        {
            cardInput = inputPar;
        }
        protected override void RunSample()
        {
            //Payment realated code
        }
    }

Code for ApiController

public class PayPalController : ApiController
    {
        public HttpResponseMessage Get(string cardData)
        {
            CardInput cartInput = JsonConvert.DeserializeObject<CardInput>(cardData);
            PayPalRequest payPalRequest = new PayPalRequest(cartInput);

            try
            {
                RequestFlow flow = payPalRequest.GetFlow();
                return Request.CreateResponse(HttpStatusCode.OK, flow);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.OK, "Fail");
            }
        }
    }

The client Ajax call request code

$scope.$on('formSubmission', function (err, submission) {

            var cardInput = JSON.stringify(submission.data, null, "  ");
            $.ajax({
                type: "GET",
                url: "http://(server:port)/api/PayPal?cardData=" + cardInput,
                dataType: 'jsonp',
                jsonpCallback: 'apiStatus',
                success: function (msg) {
                    alert("Payment Id: " + JSON.parse(msg.items[0].response).id);
                    console.log( JSON.parse(msg.items[0].response));
                },
                error: function (request, status, error) {
                    alert("error");
                }
            });
            
        });

The returned Payment Id of a transaction is shown below

Sandbox

After each transaction is completed, you can see the deposited amount and the log of transaction in your Sandbox account. Use the merchant username and password for login into the url https://www.sandbox.paypal.com.

The following image shows a sample Sandbox account

Conclusion

PayPal provide different ways and different functionalities to implement the payment on your site. Here I have shown the functionality for how to do Payment. Same way you can do the Payout, Invoicing, Billing and other functionality.

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