Click here to Skip to main content
13,663,132 members
Click here to Skip to main content
Add your own
alternative version

Stats

16.7K views
1K downloads
26 bookmarked
Posted 17 Jan 2017
Licenced CPOL

PayPal Payment using C# REST Server SDK

, 17 Jan 2017
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Khademul Basher
Founder http://softwarelandmarks.com/
Bangladesh Bangladesh
I am in Software Development for more than 12 years. I am expert on Microsoft Platform for Web Forms, MVC, MVC Core, Web API, Desktop App, PHP etc. I am also expert on jQuery, AngularJS, Bootstrap, Font Awesome, Telerik UI, Kendo UI etc. I know BackboneJS, KnockoutJS also. I am an article writer. I have many articles in CodeProject.

Email: khademulbasher@gmail.com

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionSKD!!!!!!!!!!!!!!! Pin
Member 1296353023-Jan-17 1:26
memberMember 1296353023-Jan-17 1:26 
AnswerRe: SKD!!!!!!!!!!!!!!! Pin
Khademul Basher23-Jan-17 22:19
professionalKhademul Basher23-Jan-17 22:19 
SuggestionCheck your fine print Pin
Member 999971217-Jan-17 6:25
memberMember 999971217-Jan-17 6:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180810.1 | Last Updated 17 Jan 2017
Article Copyright 2017 by Khademul Basher
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid