Integrate Paypal version 2 payment gateway in dotnet core.

This article will explain how to integrate PayPal v2 into dot net core

Step 1: Register yourself with PayPal and get Clientid and Secret

Step 2: Create View (In my case, it is Invoicedetail.cshtml) and add one button as shown below:


Pay with


Step 3: Create a Class(In my case, it is PaypalJson) which deserializes Paypal JSON Values to the C# class (Given Below)

public class PaypalJson
{
public string scope { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public string app_id { get; set; }
public int expires_in { get; set; }
public string nonce { get; set; }
}

Step 4: Since the official Paypal SDK for .NET is deprecated, we will create our own HTTP client to access the Paypal REST API. In our case, we named the class as CapturePaymentReturn.cs.
Below is the code:

public class CapturePaymentReturn
{
// Root myDeserializedClass = JsonConvert.DeserializeObject(myJsonResponse);
public class Address
{
public string country_code { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string admin_area_2 { get; set; }
public string admin_area_1 { get; set; }
public string postal_code { get; set; }
}

public class Amount
{
public string currency_code { get; set; }
public string value { get; set; }
}

public class Capture
{
public string id { get; set; }
public string status { get; set; }
public Amount amount { get; set; }
public bool final_capture { get; set; }
public SellerProtection seller_protection { get; set; }
public SellerReceivableBreakdown seller_receivable_breakdown { get; set; }
public string invoice_id { get; set; }
public List links { get; set; }
public DateTime create_time { get; set; }
public DateTime update_time { get; set; }
}

public class GrossAmount
{
public string currency_code { get; set; }
public string value { get; set; }
}

public class Link
{
public string href { get; set; }
public string rel { get; set; }
public string method { get; set; }
}

public class Name
{
public string given_name { get; set; }
public string surname { get; set; }
public string full_name { get; set; }
}

public class NetAmount
{
public string currency_code { get; set; }
public string value { get; set; }
}

public class Payer
{
public Name name { get; set; }
public string email_address { get; set; }
public string payer_id { get; set; }
public Address address { get; set; }
}

public class Payments
{
public List captures { get; set; }
}

public class PaymentSource
{
public Paypal paypal { get; set; }
}

public class Paypal
{
public string email_address { get; set; }
public string account_id { get; set; }
public Name name { get; set; }
public Address address { get; set; }
}

public class PaypalFee
{
public string currency_code { get; set; }
public string value { get; set; }
}

public class PurchaseUnit
{
public string reference_id { get; set; }
public Shipping shipping { get; set; }
public Payments payments { get; set; }
}

public class Root
{
public string id { get; set; }
public string status { get; set; }
public PaymentSource payment_source { get; set; }
public List purchase_units { get; set; }
public Payer payer { get; set; }
public List links { get; set; }
}

public class SellerProtection
{
public string status { get; set; }
public List dispute_categories { get; set; }
}

public class SellerReceivableBreakdown
{
public GrossAmount gross_amount { get; set; }
public PaypalFee paypal_fee { get; set; }
public NetAmount net_amount { get; set; }
}

public class Shipping
{
public Name name { get; set; }
public Address address { get; set; }
}

}

 

Step 5: Once you get Clientid and Secret details, Create a method (Shown Below) which generates a Bearer Token

string ClientId = “Abp1aP9xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”;
string Secret = “EMWssssssssssssssssssssssssssssssssssssssssssssss”;
string SuccessUrl = “https://YourUrl/CapturePayment”;
string CancelUrl = “https://Your cancel Url”;

public string GetBearerToken()
{
string encoded = Convert.ToBase64String(Encoding.GetEncoding(“ISO-8859-1″).GetBytes($”{ClientId}:{Secret}”));
var client = new WebClient();
client.Headers.Add(“authorization”, “Basic ” + encoded);
client.Headers.Add(“content-type”, “application/x-www-form-urlencoded”);
client.Headers.Add(“accept-language”, “en_US”);
client.Headers.Add(“accept”, “application/json”);
var body = “grant_type=client_credentials”;
var response = client.UploadString(“https://api.paypal.com/v1/oauth2/token”, “POST”, body);
var optionss = new JsonSerializerOptions
{
IncludeFields = true,
};
PaypalJson auth = JsonConvert.DeserializeObject(response);
string BearerToken = auth.access_token;
return BearerToken;
}

Step 6: Create Get Action (in our case, it is PayPal and capturepayment)

[HttpGet]
public async Task paypal(string InvoiceNo)
{

var invoicedetail = await _context.TblInvoices.FirstOrDefaultAsync(e => e.InvoiceNumber == InvoiceNo);
var ItemsDetails = await _context.TblItemsDetails.FirstOrDefaultAsync(e => e.InvoiceNumber == InvoiceNo);

string guid = Guid.NewGuid().ToString();
string BearerToken = GetBearerToken();
var client = new WebClient();
client.Headers.Add(“authorization”, “Bearer ” + BearerToken);
client.Headers.Add(“accept-language”, “en_US”);
client.Headers.Add(“content-type”, “application/json”);
client.Headers.Add(“accept”, “application/json”);
var content = “{\n \”intent\”: \”CAPTURE\”,\n \”purchase_units\”: [\n {\n \”items\”: [\n {\n \”name\”: \””+ItemsDetails.Item+”\”,\n \”description\”: \””+ItemsDetails.Item+”\”,\n \”quantity\”: \”1\”,\n \”unit_amount\”: {\n \”currency_code\”: \””+invoicedetail.Currency+”\”,\n \”value\”: \””+invoicedetail.GrandTotal+”\”\n }\n }\n ],\n \”amount\”: {\n \”currency_code\”: \””+invoicedetail.Currency+”\”,\n \”value\”: \””+invoicedetail.GrandTotal+”\”,\n \”breakdown\”: {\n \”item_total\”: {\n \”currency_code\”: \””+invoicedetail.Currency+”\”,\n \”value\”: \””+invoicedetail.GrandTotal+”\”\n }\n }\n },\n \”invoice_id\”:\”” + InvoiceNo + “\”\n }\n ],\n \”application_context\”: {\n \”return_url\”: \”” + SuccessUrl + “\”,\n \”cancel_url\”: \”” + CancelUrl + “\”\n }\n}”;
var response = client.UploadString(“https://api.paypal.com/v2/checkout/orders”, “POST”, content);

PaypalCreateorderResponse.Root root = JsonConvert.DeserializeObject(response);
string referenceid = root.id;

string CheckoutLink = root.links[1].href.ToString();

HttpContext.Session.SetString(“referenceid”, referenceid.ToString());
return Redirect(CheckoutLink);

}

public async Task CapturePayment(string token, string PayerID)
{

string referenceid = HttpContext.Session.GetString(“referenceid”);
string BearerToken = GetBearerToken();
var client = new WebClient();
client.Headers.Add(“authorization”, “Bearer ” + BearerToken);
client.Headers.Add(“content-type”, “application/json”);
var response = client.UploadString(“https://api.paypal.com/v2/checkout/orders/” + token + “/capture”, “POST”, string.Empty);
CapturePaymentReturn.Root root = JsonConvert.DeserializeObject(response);
string Orderid = root.purchase_units.FirstOrDefault().payments.captures.FirstOrDefault().invoice_id;
string Status = root.status;
if (Status == “COMPLETED”)
{
var status = await _context.TblInvoices.FirstOrDefaultAsync(e => e.InvoiceNumber == Orderid);
if (status != null)
{
status.Status = “Completed”;
}
await _context.SaveChangesAsync();
return View(“PaymentSuccess”);
}
else
{
return View(“PaymentFailed”);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *