Wednesday, July 8, 2020

Stripe SDK FIle

using NOBOLO.Controllers.Enum;
using NOBOLO.Library.API;
using NOBOLO.Library.Utilities;
using NOBOLO.Models;
using NOBOLO.Repository.GRepository;
using NOBOLO.Repository.UnitOfWork;
using NOBOLO.StripePayment.StripeInputs;
using Stripe;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace NOBOLO.StripePayment
{
    public class StripePayment
    {
        private UnitOfWork _unitOfWork;
        private GenericRepository<tblUser> _UsersRepo;
        public StripePayment()
        {
            _unitOfWork = new UnitOfWork();
            StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["StripeConfigurationApiKey"];
        }
        static StripePayment()
        {
            StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["StripeConfigurationApiKey"];

        }

        public ApiResponse AddCreditCard(ApiInputCreditCard param)
        {
            try
            {

                _UsersRepo = new GenericRepository<tblUser>(_unitOfWork);
                var entityuser = _UsersRepo.Repository.Get(x => x.UsersID == param.UserId);
                if (entityuser == null)
                    return JsonResponse.GetResponse(ResponseCode.Failure, "User not found.");

                //string CustomerId = "";
                //CustomerCreateOptions customerOptions;
                //if (string.IsNullOrEmpty(entityuser.StripeCustomerID))
                //{
                //    if (entityuser.Email != null)
                //    {
                //         customerOptions = new CustomerCreateOptions
                //        {
                //            Email = entityuser.Email
                //        };
                //    }
                //    else
                //    {
                //         customerOptions = new CustomerCreateOptions
                //        {
                //            Email = entityuser.ThiryPartyID
                //        };
                //    }



                //    var customerService = new CustomerService();
                //    Customer customer = customerService.Create(customerOptions);
                //    entityuser.StripeCustomerID = customer.Id;
                //    _UsersRepo.Repository.Update(entityuser);
                //    CustomerId = customer.Id;
                //}
                //else
                //{
                //    CustomerId = entityuser.StripeCustomerID;
                //}

                var cardService = new CardService();
                var cardCreateOptions = new CardCreateOptions
                {
                    Source = param.StripeToken
                };

                var result = cardService.Create(entityuser.StripeCustomerID, cardCreateOptions);

                var CreditCards = GetCreditCards(param.UserId);


                var response = new Dictionary<string, object>();
                response.Add("CreditCards", CreditCards);
                return JsonResponse.GetResponse(ResponseCode.Success, response);
            }
            catch (StripeException e)
            {
                LogHelper.CreateLog(e.StripeError.Message);
                return JsonResponse.GetResponse(ResponseCode.Failure, e.StripeError.Message);
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex);
                return JsonResponse.GetResponse(ResponseCode.Exception, "Something went wrong.");
            }
        }



        public ApiResponse DeleteCreditCards(string CardId, int UserId)
        {
            try
            {
                _UsersRepo = new GenericRepository<tblUser>(_unitOfWork);
                var entityuser = _UsersRepo.Repository.Get(x => x.UsersID == UserId);
                if (entityuser == null)
                    return JsonResponse.GetResponse(ResponseCode.Failure, "User not found.");

                var cardService = new CardService();
                var result = cardService.Delete(entityuser.StripeCustomerID, CardId);

                var CreditCards = GetCreditCards(UserId);
                var response = new Dictionary<string, object>();
                response.Add("CreditCards", CreditCards);

                //Update Default Card Id in User properties Table 
                //GenericRepository<UserProperty> _userPropertuGenericRepository = new GenericRepository<UserProperty>(_unitOfWork);
                //var objList = _userPropertuGenericRepository.Repository.GetAll(x => x.DefaultCardId == CardId);
                //if (objList != null && objList.Count > 0)
                //{
                //    foreach (var item in objList)
                //    {
                //        item.DefaultCardId = "";
                //        item.ModifiedDate = DateTime.UtcNow;
                //        _userPropertuGenericRepository.Repository.Update(item);
                //    }
                //}

                return JsonResponse.GetResponse(ResponseCode.Success, response);

            }
            catch (StripeException e)
            {
                LogHelper.CreateLog(e.StripeError.Message);
                return JsonResponse.GetResponse(ResponseCode.Failure, e.StripeError.Message);
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex);
                return JsonResponse.GetResponse(ResponseCode.Exception, ex.Message);
            }
        }

        public ApiResponse MakeDefaultCreditCards(string CardId, int UserId)
        {
            try
            {
                _UsersRepo = new GenericRepository<tblUser>(_unitOfWork);
                var entityuser = _UsersRepo.Repository.Get(x => x.UsersID == UserId);
                if (entityuser == null)
                    return JsonResponse.GetResponse(ResponseCode.Failure, "User not found.");


                var customerService = new CustomerService();
                Customer customer = customerService.Get(entityuser.StripeCustomerID);

                if (customer != null)
                {
                    if (customer.DefaultSourceId != CardId)
                    {
                        var cardService = new CardService();
                        var result = cardService.Get(entityuser.StripeCustomerID, CardId);
                        if (result != null)
                        {
                            var cusUpdateOptions = new CustomerUpdateOptions
                            {
                                DefaultSource = CardId
                            };

                            customerService.Update(entityuser.StripeCustomerID, cusUpdateOptions);
                        }
                    }
                }

                var CreditCards = GetCreditCards(UserId);
                var response = new Dictionary<string, object>();
                response.Add("CreditCards", CreditCards);

                return JsonResponse.GetResponse(ResponseCode.Success, response);

            }
            catch (StripeException e)
            {
                LogHelper.CreateLog(e.StripeError.Message);
                return JsonResponse.GetResponse(ResponseCode.Failure, e.StripeError.Message);
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex);
                return JsonResponse.GetResponse(ResponseCode.Exception, ex.Message);
            }
        }

        public List<ApiCreditCardView> GetCreditCards(long UserId)
        {
            try
            {

                List<ApiCreditCardView> listview = new List<ApiCreditCardView>();
                _UsersRepo = new GenericRepository<tblUser>(_unitOfWork);
                var entityuser = _UsersRepo.Repository.Get(x => x.UsersID == UserId);
                if (entityuser == null)
                    return listview;

                if (string.IsNullOrEmpty(entityuser.StripeCustomerID))
                    return listview;


                var customerService = new CustomerService();
                var result = customerService.Get(entityuser.StripeCustomerID);
                var Data = result.Sources.Data;

                if (Data == null && Data.Count == 0)
                {
                    return listview;
                }

                foreach (Card item in Data)
                {
                    bool isDefault = false;
                    if (result.DefaultSourceId == item.Id)
                    {
                        isDefault = true;
                    }
                    ApiCreditCardView obj = new ApiCreditCardView()
                    {
                        CardholderName = item.Name ?? "",
                        CustomerId = entityuser.StripeCustomerID,
                        ExpirationDate = item.ExpMonth.ToString() + "/" + item.ExpYear.ToString(),
                        ImageUrl = GetCardImageIcon(item.Brand),
                        IsDefault = isDefault,
                        MaskedNumber = "**********" + item.Last4,
                        CardId = item.Id
                    };

                    listview.Add(obj);

                }


                return listview;
            }
            catch (StripeException e)
            {
                LogHelper.CreateLog(e.StripeError.Message);
                return new List<ApiCreditCardView>();
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex);
                //List<ApiCreditCardView> listview = new List<ApiCreditCardView>();
                //return listview;
                return new List<ApiCreditCardView>();
            }
        }

        public string GetCardImageIcon(string CardType)
        {
            string basePath = ConfigurationManager.AppSettings["WebPath"] + "Content/images/";
            string cardIconPath = "";

            if (CardType.Contains("Visa"))
            {
                cardIconPath = basePath + "visa.png";
            }
            else if (CardType.Contains("MasterCard"))
            {
                cardIconPath = basePath + "MasterCard.png";
            }
            else if (CardType.Contains("American Express"))
            {
                cardIconPath = basePath + "americanexpress.png";
            }
            else if (CardType.Contains("Discover"))
            {
                cardIconPath = basePath + "discover.png";
            }
            else if (CardType.Contains("Diners Club"))
            {
                cardIconPath = basePath + "diners.png";
            }
            else if (CardType.Contains("JCB"))
            {
                cardIconPath = basePath + "jsb.png";
            }
            else if (CardType.Contains("UnionPay"))
            {
                cardIconPath = basePath + "unionpay.png";
            }

            return cardIconPath;
        }

        public static string MakeInvoicePayment(long amount, string Nounce, string PaymentType)
        {
            Charge charge = new Charge();
            amount = amount * 100;
            if (PaymentType == "Card")
            {
                if (!String.IsNullOrEmpty(Nounce))
                {
                    // This transaction is made using Nonce
                    var options = new ChargeCreateOptions
                    {
                        Amount = amount,
                        Currency = "usd",
                        Description = "Invoice Payment",
                        Source = Nounce
                    };
                    var service = new ChargeService();
                    charge = service.Create(options);
                }
            }
            return charge.Id;
        }

        public static string CreateUser(tblUser _user)
        {
            string CustomerId = "";
            CustomerCreateOptions customerOptions;
            if (string.IsNullOrEmpty(_user.StripeCustomerID))
            {
                if (_user.Email != null)
                {
                    customerOptions = new CustomerCreateOptions
                    {
                        Email = _user.Email
                    };
                }
                else
                {
                    customerOptions = new CustomerCreateOptions
                    {
                        Name = _user.Name,
                        Phone = _user.PhoneNumber
                    };
                }
                var customerService = new CustomerService();
                Customer customer = customerService.Create(customerOptions);


                return _user.StripeCustomerID = customer.Id;



            }
            else
            {
                return _user.StripeCustomerID;
            }
        }


        public static string CreateUser1(tblUser _user)
        {
            string CustomerId = "";
            CustomerCreateOptions customerOptions;
            if (!string.IsNullOrEmpty(_user.StripeCustomerID))
            {
                if (_user.Email != null)
                {
                    customerOptions = new CustomerCreateOptions
                    {
                        Email = _user.Email
                    };
                }
                else
                {
                    customerOptions = new CustomerCreateOptions
                    {
                        Name = _user.Name,
                        Phone = _user.PhoneNumber
                    };
                }
                var customerService = new CustomerService();

                try
                {
                    dynamic obj = customerService.Get(_user.StripeCustomerID);
                    return _user.StripeCustomerID;
                }
                catch
                {
                    Customer customer = customerService.Create(customerOptions);
                    return _user.StripeCustomerID = customer.Id;
                }
            }
            else
            {
                return _user.StripeCustomerID;
            }
        }



        public object GetEphemeralKey(string StripeCustomerID, string StripeVersion)
        {

            try
            {
                Stripe.EphemeralKeyCreateOptions _epheOptions = new EphemeralKeyCreateOptions
                {
                    Customer = StripeCustomerID,
                    StripeVersion = StripeVersion
                };

                Stripe.EphemeralKey response = new Stripe.EphemeralKeyService().Create(_epheOptions);
                object ParseResponse = new JavaScriptSerializer().Deserialize<object>(response.RawJson);
                return ParseResponse;
                //return new StripeEphemerayKeyInput
                //{
                //    Id = response.Id,
                //    Object = response.Object,
                //    AssociatedObjects = response.AssociatedObjects,
                //    Created = response.Created,
                //    Expires = response.Expires,
                //    Livemode = response.Livemode,
                //    secret = ConfigurationManager.AppSettings["StripeConfigurationApiKey"]
                //};

            }
            catch (StripeException e)
            {
                LogHelper.CreateLog(e.StripeError.Message);
                //return new StripeEphemerayKeyInput() ;
                return JsonResponse.GetResponse(ResponseCode.Failure, e.StripeError.Message);
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex);
                return JsonResponse.GetResponse(ResponseCode.Exception, ex.Message);
                //return new StripeEphemerayKeyInput();
            }
        }

        public object GetPaymentIntentSecretKey(long Amount, string CustomerID)
        {

            try
            {

                var service = new PaymentIntentService();
                var options = new PaymentIntentCreateOptions
                {
                    Amount = Amount,
                    Currency = "usd",
                    PaymentMethodTypes = new List<string>
                      {
                        "card",
                      },
                    Customer = CustomerID
                };
                object response = service.Create(options);
                return response;

            }
            catch (StripeException e)
            {
                LogHelper.CreateLog(e.StripeError.Message);
                //return new StripeEphemerayKeyInput() ;
                return e.StripeError.Message;
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex);
                return JsonResponse.GetResponse(ResponseCode.Exception, ex.Message);
                //return new StripeEphemerayKeyInput();
            }
        }


    }
}

No comments:

Post a Comment

Two Factor Authentication using .Net Core

Install Package dotnet add package GoogleAuthenticator --version 3.1.1 Model Changes public bool IsAuthenticatorReset { get; set; } public s...