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");
        }

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" 😊

Comments

  1. Hi
    Could you please tell me is Paystack compatible with Xamarin?
    Thanks

    ReplyDelete
    Replies
    1. Yes off course, It would work on any device that supports HTTP.

      Delete
    2. Hi. 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.

      Delete
  2. It isn't working for me...Please help. Thanks.

    ReplyDelete
  3. How do I Use this code for ASP.NET 4.0 and 4.5

    ReplyDelete
    Replies
    1. The code is written in Asp.Net 4.5. You can also check Paystack Api documentation which was listed above.

      Delete
  4. Nice and Valuable information you explained in this article I loved it more, it is useful for me a lot. Thanks for sharing.
    Regards,
    Best DOT NET Online Training in Hyderabad, India

    ReplyDelete
  5. pls i want to implement with angular js

    ReplyDelete
    Replies
    1. I believe angular should have a way to implement Restful service.

      Delete
  6. This is a great tool for Integration, however how do one trigger the pop up to accept user card details

    ReplyDelete
    Replies
    1. Once you click on the pay button, you will be redirected to a secured URL provided by paystack to add your card details.

      Delete
  7. Replies
    1. Is it a custom built blog or Google blogger or word press?

      Delete
  8. Hai Author Good Information that i found here,do not stop sharing and Please keep updating us..... Thanks.
    Hire asp.net developer
    .Net development services

    ReplyDelete
  9. 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.

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Thanks for sharing the blog. Very informative blog.
    Net 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.

    ReplyDelete
  12. This is very important and imformative blog,thanks for good info
    .Net Online Course

    ReplyDelete
  13. This comment has been removed by a blog administrator.

    ReplyDelete
  14. can you help me with a sample code that can work on asp.net mvc

    ReplyDelete
    Replies
    1. It was written in asp.net mvc but you can send me your email address.

      Delete
    2. PaystackPayment is not found in the current context. Pls what can i do?

      Delete
    3. It is Payment not PaystackPayment

      Delete
  15. Pls admin I want you to guide me on these am using asp.net 4.0

    ReplyDelete
  16. Hi, am having error, Wat will be my metaData bcos my is an empty string and the error is INVALID METADATA PASSED

    ReplyDelete
  17. Error Message : PaystackPayment is not found in the current context . Pls what can i do?

    ReplyDelete

Post a Comment

Popular posts from this blog

Sending Notification Message with Firebase with JavaScript and .Net client

Solved: Jwt Authentication in Asp.Net Web Api And Mvc