Paystack In Asp.Net MVC
Introduction
Happy new year folks. I hope you all enjoyed your holidays. Let me enlighten you with some new year codes 😊.
Remember my post on how to implement a payment gateway on Paystack with Node js? today, you would see it in action in Asp.Net.
I am not going to build a customer subscription app like I did in the previous one, rather I would provide explicit codes that can be used to implement payment on any mobile apps, web apps, and any platform indeed. It is a simple code and can be easily integrated into your projects.
To know more about Paystack infrastructure, visit the developer's section on their website. They have already written some libraries on vast programming languages like Python, Java, Node js and so on...
If you have problems working with the code or implementing it on your project, drop your comments and you might receive an email from me or if your company is looking forward to incorporating a payment solution, you can contact me.
Diving to the code
Step 1: Building the payment class and model classes
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace MyApp.Classes
{
//Note: Don't change the property names to avoid errors
public class TransactionResult
{
public bool status { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
//Note: Don't change the property names to avoid errors
public class Data
{
[JsonProperty("authorization_url")]
public string authorization_url { get; set; }
[JsonProperty("access_code")]
public string access_code { get; set; }
[JsonProperty("reference")]
public string reference { get; set; }
}
public class Payment
{
private readonly string _payStackSecretKey;
/// <summary>
/// The secret key is needed for authentication and verification purposes.
/// Note: It is best to store the secret key in the web.config file.
/// </summary>
/// <param name="secretKey"></param>
public Payment(string secretKey)
{
_payStackSecretKey= secretKey;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //Don't for get to add this.
}
/// <summary>
/// Initialize a transaction. Check out documentation on https://developers.paystack.co/docs/initialize-a-transaction
/// </summary>
/// <param name="amountInKobo">For eg, 5000000 is 5000 that is "5000*100"</param>
/// <param name="email">The customer email</param>
/// <param name="metadata">Additional data can be included. </param>
/// <param name="resource">The optional api endpoint which is already specified</param>
/// <returns></returns>
public async Task<TransactionResult> InitializeTransaction(int amountInKobo, string email, string metadata = "",
string resource = "https://api.paystack.co/transaction/initialize")
{
var client = new HttpClient {BaseAddress = new Uri(resource)};
client.DefaultRequestHeaders.Add("Authorization", _payStackSecretKey);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var body = new Dictionary<string, string>
{
{"amount", amountInKobo.ToString()},
{"email", email},
{"metadata", metadata}
};
var content = new FormUrlEncodedContent(body);
var response = await client.PostAsync(resource, content);
if (response.IsSuccessStatusCode)
{
TransactionResult responseData = await response.Content.ReadAsAsync<TransactionResult>();
return responseData;
}
return null;
}
/// <summary>
/// Verify a transaction
/// </summary>
/// <param name="reference">The reference code returned from the transaction initialization result </param>
/// <param name="resource">The optional api endpoint which is already specified</param>
/// <returns></returns>
public async Task<string> VerifyTransaction(string reference,string resource = "https://api.paystack.co/transaction/verify")
{
var client = new HttpClient {BaseAddress = new Uri(resource)};
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", _payStackSecretKey);
var response = await client.GetAsync(reference + "/");
if (response.IsSuccessStatusCode)
{
string responseData = await response.Content.ReadAsStringAsync();
return responseData;
}
return null;
}
}
}
Step 2: Using the class in Asp.net MVC
//[Authorize]
public async Task<ActionResult> Pay()
{
var payment = new PaystackPayment("Bearer secret key goes here");
var transaction = await payment.InitializeTransaction(500000, "johndoe@gmail.com");
if (transaction.status)
{
//redirect to authorization url
return RedirectPermanent(transaction.data.authorization_url);
//return Json(transaction, JsonRequestBehavior.AllowGet);
}
return Content("An error occcured");
}
public async Task<ActionResult> Pay()
{
var payment = new PaystackPayment("Bearer secret key goes here");
var transaction = await payment.InitializeTransaction(500000, "johndoe@gmail.com");
if (transaction.status)
{
//redirect to authorization url
return RedirectPermanent(transaction.data.authorization_url);
//return Json(transaction, JsonRequestBehavior.AllowGet);
}
return Content("An error occcured");
}
Conclusion
I hope you have fun coding this. Play with it, tweak it, add it to your project as you like. If you have any issues, let me know right away. Buggy and troublesome codes shouldn't be written in 2017 "I think that should be part of my new year resolution" 😊
Hi
ReplyDeleteCould you please tell me is Paystack compatible with Xamarin?
Thanks
Yes off course, It would work on any device that supports HTTP.
DeleteHi. I am having trouble getting started in a asp.net(vb) web app. I have tried for 1 week to download and install the API from nuggets. For 1 week. Can it be that DotNet is not so supported? I get an error complaining of the DotNet Framework targeted version. No matter what version I can to, the error is the same.
DeleteIt isn't working for me...Please help. Thanks.
ReplyDeleteWhat is the issue?
DeleteHow do I Use this code for ASP.NET 4.0 and 4.5
ReplyDeleteThe code is written in Asp.Net 4.5. You can also check Paystack Api documentation which was listed above.
DeleteNice and Valuable information you explained in this article I loved it more, it is useful for me a lot. Thanks for sharing.
ReplyDeleteRegards,
Best DOT NET Online Training in Hyderabad, India
pls i want to implement with angular js
ReplyDeleteI believe angular should have a way to implement Restful service.
DeleteThis is a great tool for Integration, however how do one trigger the pop up to accept user card details
ReplyDeleteOnce you click on the pay button, you will be redirected to a secured URL provided by paystack to add your card details.
Deletehow to add it on my blog
ReplyDeleteIs it a custom built blog or Google blogger or word press?
DeleteHai Author Good Information that i found here,do not stop sharing and Please keep updating us..... Thanks.
ReplyDeleteHire asp.net developer
.Net development services
Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThanks for sharing the blog. Very informative blog.
ReplyDeleteNet Application development through the team of expert ASP Net developers. Offshore Dot Net Developers India, ASP.net Development Company India, Hire MVC Developer in India.
This is very important and imformative blog,thanks for good info
ReplyDelete.Net Online Course
Your welcome
DeleteThis comment has been removed by a blog administrator.
ReplyDeletecan you help me with a sample code that can work on asp.net mvc
ReplyDeleteIt was written in asp.net mvc but you can send me your email address.
DeletePaystackPayment is not found in the current context. Pls what can i do?
DeleteIt is Payment not PaystackPayment
DeletePls admin I want you to guide me on these am using asp.net 4.0
ReplyDeleteHi, am having error, Wat will be my metaData bcos my is an empty string and the error is INVALID METADATA PASSED
ReplyDeleteError Message : PaystackPayment is not found in the current context . Pls what can i do?
ReplyDeleteIt is Payment not PaystackPayment
Delete