Integrate PayPal Payment in Website

Oct, 27 2019

Blog By: Ajay

Integrate PayPal Payment in Website

1) Login to Developer account and Get Client Id & Secret
2) Add Payment Button (JavaScript code)
3) Verify Payment
4) Test Payment
5) Go Live

1) Login to Developer account and Get Client Id & Secret

- Login to PayPal Developer Account
- My Apps & Credentials -> Sandbox -> REST API apps -> Create App
- Copy Client Id & Secret

2) Add Payment Button (JavaScript code)

- In src, Repalce Client Id with your Client Id
- Repalce verification URL with URL of your website page
- In Asp.Net, Pgae Load method will hit. If you are using MVC, add action name in URL.
- Some times it is not working in local host so deploy it and then test it.

<!DOCTYPE html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>

<body>
  <script
    src="https://www.paypal.com/sdk/js?client-id=SB_CLIENT_ID">
  </script>
    <form id="form1" runat="server">     
        <div id="paypal-button-container"/> 
    </form>
   <script>
	  paypal.Buttons({
		createOrder: function(data, actions) {
		  return actions.order.create({
			purchase_units: [{
			  amount: {
				value: ’0.01’
			  }
			}]
		  });
		},
		onApprove: function(data, actions) {
		  return actions.order.capture().then(function(details) {
			return fetch(’https://www.you_domain.com/verifypayment.aspx’, {
			  method: ’post’,
			  headers: {
				’content-type’: ’pplication/json’
			  },
			  body: JSON.stringify({
				orderID: data.orderID
			  })
			});
		  });
		}
	  }).render(’#paypal-button-container’);
	</script>
</body>

3) Verify Payment

Install PayPal Checkout SDK from Nuget

static string clientId = "Copy From Developer Account (Step 1)";
        static string secret = "Copy From Developer Account (Step 1)";

        protected async void Page_Load(object sender, EventArgs e)
        {
            MemoryStream memstream = new MemoryStream();
            Request.InputStream.CopyTo(memstream);
            memstream.Position = 0;
            using (StreamReader reader = new StreamReader(memstream))
            {
                if (reader != null)
                {
                    var json = reader.ReadToEnd();

                    if (!string.IsNullOrWhiteSpace(json))
                    {
                        dynamic jsonBody = JObject.Parse(json);
                        string orderID = jsonBody.orderID;

                        if (!string.IsNullOrWhiteSpace(orderID))
                        {
                            await GetOrder(orderID);
                        }
                    }
                }
            }
        }

        public static HttpClient GetClient()
        {
            // Creating a sandbox environment
            PayPalEnvironment environment = new SandboxEnvironment(clientId, secret);

            // Creating a client for the environment
            PayPalHttpClient client = new PayPalHttpClient(environment);
            return client;
        }

        public async Task GetOrder(string orderId, bool debug = false)
        {
            OrdersGetRequest request = new OrdersGetRequest(orderId);

            HttpClient client = GetClient();
            if (client != null)
            {
                var response = await client.Execute(request);

                var result = response.Result();

                if (result != null)
                {
                    string amountReceived = string.Empty;
                    string _orderId = string.Empty;

                    if (result.PurchaseUnits != null && result.PurchaseUnits.Count > 0 && result.PurchaseUnits[0] != null)
                    {
                        AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
                        amountReceived = amount.Value + " " + amount.CurrencyCode;

                        _orderId = result.Id;
                    }

                    if (result.Status == "COMPLETED" && !string.IsNullOrWhiteSpace(_orderId))
                    {
                        //Payment has been received successfully in your account. Provide Service to user or ship item.
                    }
                }
                return response;
            }
            return null;
        }

4) Test Payment

- Go to PayPal Developer Sandbox Accounts
- You will get one Default Merchant Account. Create one Personal (Buyer) Account. PayPal will give you some test amount.
- Click on PayPal buy button from your website. Login and Pay with Buyer account.
- Now login with Merchant account in Sandbox to check whether you have been received amount or not.
- Same again login with Buyer account in Sandbox to check amount have been deducted or not.

5) Go Live

- For live, select Live in first step instead of Sandbox and Create new app.
- Replace Sandbox Client Id and Secrete with Live Client Id and Secrete in JavaScript and in server side code.
- Change SandboxEnvironment with LiveEnvironment in GetClient method at server side.



Comments