Wednesday, July 8, 2020

PayPal SDK 3 file in one

*********** Paypal Lib ***********************





**************  Paypal Lib END *******************

using PayPal.Api;
using NOBOLO.Library.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace NOBOLO.Library.PaymentLib
{
    public class PaypalLib
    {
        public enum PayPalStatus
        {
            PENDING,
            PROCESSING,
            SUCCESS,
            ERROR,
            UNCLAIMED
        }

        #region "Paypal Payouts"

        public PaymentResponse PaypalPayoutPayments(decimal _PayAmount, string _Payto, string _PayamentNote, string _ItemRefNo)
        {
            PaymentResponse _PaymentResponse = new PaymentResponse();
            _PaymentResponse.PaymentKey = "";
            _PaymentResponse.ErrorDescription = "";

            try
            {
                APIContext apiContext = PaypalConfiguration.GetAPIContext();

                // ### Initialize `Payout` Object
                // Initialize a new `Payout` object with details of the batch payout to be created.
                var payout = new Payout
                {
                    // #### sender_batch_header
                    // Describes how the payments defined in the `items` array are to be handled.
                    sender_batch_header = new PayoutSenderBatchHeader
                    {
                        sender_batch_id = "Sngle_" + System.Guid.NewGuid().ToString().Substring(0, 8),
                        email_subject = _PayamentNote,

                    },

                    // #### items
                    // The `items` array contains the list of payout items to be included in this payout.
                    // If `syncMode` is set to `true` when calling `Payout.Create()`, then the `items` array must only
                    // contain **one** item.  If `syncMode` is set to `false` when calling `Payout.Create()`, then the `items`
                    // array can contain more than one item.
                    items = new List<PayoutItem>
                     {
                        new PayoutItem
                        {
                            recipient_type = PayoutRecipientType.EMAIL,
                            amount = new Currency
                            {
                                value = string.Format("{0:F2}", _PayAmount),
                                currency = "USD"
                            },
                            receiver = _Payto,
                            //receiver = "salman@sandbox.com",
                            //receiver = "test@gamil.com",
                            note = _PayamentNote,
                            sender_item_id = _ItemRefNo,

                        }
                    }
                };

                // ### Payout.Create()
                // Creates the batch payout resource.
                // `syncMode = false` indicates that this call will be performed **asynchronously**,
                // and will return a `payout_batch_id` that can be used to check the status of the payouts in the batch.
                // `syncMode = true` indicates that this call will be performed **synchronously** and will return once the payout has been processed.
                // > **NOTE**: The `items` array can only have **one** item if `syncMode` is set to `true`.
                //LogHelper.CreateLog("Before payout.Create(apiContext, true)", ErrorType.PaymentGateway);
                //LogHelper.CreateLog("_Payto=" + _Payto + " _PayAmount = " + _PayAmount.ToString() + " _PayamentNote = " + _PayamentNote + " _ItemRefNo= " + _ItemRefNo, ErrorType.PaymentGateway);


                var createdPayout = payout.Create(apiContext, false);

                //LogHelper.CreateLog("After payout.Create(apiContext, true)", ErrorType.PaymentGateway);

                //PayPal.Api.PayoutTransactionStatus.

                //_PaymentResponse.PaymentStatus = createdPayout.items[0].transaction_status.ToString();
                _PaymentResponse.PaymentStatus = createdPayout.batch_header.batch_status.ToString();
                _PaymentResponse.PaymentKey = createdPayout.batch_header.payout_batch_id;

                //if (createdPayout.items[0].error != null)
                //{
                //    _PaymentResponse.ErrorDescription = createdPayout.items[0].error.message;
                //}

                return _PaymentResponse;

                //SUCCESS = 0,
                //
                // Summary:
                //     The item has been denied payment.
                // DENIED = 1,
                //
                // Summary:
                //     The item is awaiting payment.
                // PENDING = 2,
                //
                // Summary:
                //     The item is being processed.
                // PROCESSING = 3,
                //
                // Summary:
                //     Processing failed for the item.
                //FAILED = 4,
                //
                // Summary:
                //     The item is unclaimed. If the item is not claimed within 30 days, the funds will
                //     be returned to the sender.
                //UNCLAIMED = 5,
                //
                // Summary:
                //     The item is returned. The funds are returned if the recipient hasn't claimed
                //     them in 30 days.
                //RETURNED = 6,
                //
                // Summary:
                //     The item is on hold.
                //ONHOLD = 7,
                //
                // Summary:
                //     The item is blocked.
                //BLOCKED = 8,
                //
                // Summary:
                //     It is not possible for the CANCELLED state to occur if the sender is solely using
                //     the API to send Payouts. This status is an edge-case if a sender uses both the
                //     MassPay web upload and the Payouts API, cancels the web upload, and then uses
                //     the API to find the batch/items. In this case, CANCELLED status is possible.
                //CANCELLED = 9

            }
            //catch (PayPal.IdentityException ex)
            //{
            //    // ex.Details provides quick access to the API error information.
            //    LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
            //    _PaymentResponse.ErrorDescription = ex.Message;
            //    return _PaymentResponse;
            //}
            catch (PayPal.HttpException ex)
            {
                // Some other error occurred when attempting to send the request to PayPal.
                // ex.Response contains the full response from the API which should highlight the error encountered.
                JObject joResponse = JObject.Parse(ex.Response);


                LogHelper.CreateLog(ex.Response, ErrorType.PaymentGateway);
                _PaymentResponse.ErrorDescription = (string)joResponse["message"];
                return _PaymentResponse;
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
                _PaymentResponse.ErrorDescription = ex.Message;
                return _PaymentResponse;
            }
            //catch (PayPal.PayPalException ex)
            //{
            //    // A general exception was thrown from the SDK.
            //    LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
            //    _PaymentResponse.ErrorDescription = ex.Message;
            //    return _PaymentResponse;
            //}
            //catch (System.Exception ex)
            //{
            //    // Some other general exception occurred.
            //    LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
            //    _PaymentResponse.ErrorDescription = ex.Message;
            //    return _PaymentResponse;
            //}
            //catch (PayPal.PaymentsException ex)
            //{

            //    if (ex.Details != null)
            //    {
            //        foreach (PayPal.Api.ErrorDetails _error in ex.Details.details)
            //        {
            //            LogHelper.CreateLog(_error.issue, ErrorType.PaymentGateway);
            //            _PaymentResponse.ErrorDescription = ex.Message;
            //        }

            //        LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
            //        _PaymentResponse.ErrorDescription = ex.Message;
            //        return _PaymentResponse;
            //    }

            //    LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
            //    _PaymentResponse.ErrorDescription = ex.Message;
            //    return _PaymentResponse;
            //}
        }


        public PaymentResponse PaypalPayoutPaymentsBatch(
                               decimal _LotOwnerPayAmount, string _LotOwnerPayto,
                               decimal _SpotLeaserPayAmount, string _SpotLeaserPayto,
                               string _PayamentNote, string _ItemRefNo)
        {
            PaymentResponse _PaymentResponse = new PaymentResponse();
            _PaymentResponse.PaymentKey = "";

            try
            {
                APIContext apiContext = PaypalConfiguration.GetAPIContext();

                // ### Initialize `Payout` Object
                // Initialize a new `Payout` object with details of the batch payout to be created.
                var payout = new Payout
                {
                    // #### sender_batch_header
                    // Describes how the payments defined in the `items` array are to be handled.
                    sender_batch_header = new PayoutSenderBatchHeader
                    {
                        sender_batch_id = "batch_" + System.Guid.NewGuid().ToString().Substring(0, 8),
                        email_subject = _PayamentNote,

                    },
                    // #### items
                    // The `items` array contains the list of payout items to be included in this payout.
                    // If `syncMode` is set to `true` when calling `Payout.Create()`, then the `items` array must only
                    // contain **one** item.  If `syncMode` is set to `false` when calling `Payout.Create()`, then the `items`
                    // array can contain more than one item.
                    items = new List<PayoutItem>
                     {
                        new PayoutItem
                        {
                            recipient_type = PayoutRecipientType.EMAIL,
                            amount = new Currency
                            {
                                value = _LotOwnerPayAmount.ToString(),
                                currency = "USD"
                            },
                            receiver = _LotOwnerPayto,
                            //receiver = "salman@sandbox.com",
                            //receiver = "test@gamil.com",
                            note = _PayamentNote,
                            sender_item_id = _ItemRefNo +" Lotowner"
                        },
                         new PayoutItem
                        {
                            recipient_type = PayoutRecipientType.EMAIL,
                            amount = new Currency
                            {
                                value = _SpotLeaserPayAmount.ToString(),
                                currency = "USD"
                            },
                            receiver = _SpotLeaserPayto,
                            //receiver = "salman@sandbox.com",
                            //receiver = "test@gamil.com",
                            note = _PayamentNote,
                            sender_item_id = _ItemRefNo+" SpotOwner"
                        }
                    }
                };

                // ### Payout.Create()
                // Creates the batch payout resource.
                // `syncMode = false` indicates that this call will be performed **asynchronously**,
                // and will return a `payout_batch_id` that can be used to check the status of the payouts in the batch.
                // `syncMode = true` indicates that this call will be performed **synchronously** and will return once the payout has been processed.
                // > **NOTE**: The `items` array can only have **one** item if `syncMode` is set to `true`.
                var createdPayout = payout.Create(apiContext, false);

                //PayPal.Api.PayoutTransactionStatus.

                _PaymentResponse.PaymentStatus = createdPayout.batch_header.batch_status.ToString();
                _PaymentResponse.PaymentKey = createdPayout.batch_header.payout_batch_id;

                if (createdPayout.batch_header.errors != null)
                {
                    _PaymentResponse.ErrorDescription = createdPayout.batch_header.errors[0].message;
                }

                return _PaymentResponse;

                //SUCCESS = 0,
                //
                // Summary:
                //     The item has been denied payment.
                // DENIED = 1,
                //
                // Summary:
                //     The item is awaiting payment.
                // PENDING = 2,
                //
                // Summary:
                //     The item is being processed.
                // PROCESSING = 3,
                //
                // Summary:
                //     Processing failed for the item.
                //FAILED = 4,
                //
                // Summary:
                //     The item is unclaimed. If the item is not claimed within 30 days, the funds will
                //     be returned to the sender.
                //UNCLAIMED = 5,
                //
                // Summary:
                //     The item is returned. The funds are returned if the recipient hasn't claimed
                //     them in 30 days.
                //RETURNED = 6,
                //
                // Summary:
                //     The item is on hold.
                //ONHOLD = 7,
                //
                // Summary:
                //     The item is blocked.
                //BLOCKED = 8,
                //
                // Summary:
                //     It is not possible for the CANCELLED state to occur if the sender is solely using
                //     the API to send Payouts. This status is an edge-case if a sender uses both the
                //     MassPay web upload and the Payouts API, cancels the web upload, and then uses
                //     the API to find the batch/items. In this case, CANCELLED status is possible.
                //CANCELLED = 9

            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
                _PaymentResponse.ErrorDescription = ex.Message;
                return _PaymentResponse;
            }
        }



        public PaymentResponse GetPaypalPatoutPaymentStatus(string _payout_batch_id)
        {
            PaymentResponse _PaymentResponse = new PaymentResponse();
            _PaymentResponse.PaymentKey = "";
            _PaymentResponse.PaymentStatus = "";
            _PaymentResponse.ErrorDescription = "";

            try
            {
                APIContext apiContext = PaypalConfiguration.GetAPIContext();
                var retrievedPayout = Payout.Get(apiContext, _payout_batch_id);

                if (retrievedPayout.batch_header.batch_status == PayPalStatus.SUCCESS + "")
                {
                    _PaymentResponse.PaymentStatus = retrievedPayout.batch_header.batch_status;
                    _PaymentResponse.PaymentKey = retrievedPayout.batch_header.payout_batch_id;

                    //in case of batch processing
                    if (retrievedPayout.items != null)
                    {
                        foreach (var _error in retrievedPayout.items)
                        {
                            if (_error.error != null)
                            {
                                _PaymentResponse.ErrorDescription = _PaymentResponse.ErrorDescription + _error.payout_item.receiver + " : " + _error.error.message + " /n ";
                            }
                        }

                        foreach (var _error in retrievedPayout.items)
                        {
                            _PaymentResponse.ErrorDescription = _PaymentResponse.ErrorDescription + _error.payout_item.receiver + " : " + _error.transaction_status + " /n ";
                        }
                    }


                    return _PaymentResponse;
                }
                else if (retrievedPayout.batch_header.batch_status != PayPalStatus.PENDING.ToString() || retrievedPayout.batch_header.batch_status != PayPalStatus.PROCESSING.ToString())
                {
                    _PaymentResponse.PaymentStatus = retrievedPayout.batch_header.batch_status;
                    _PaymentResponse.PaymentKey = retrievedPayout.batch_header.payout_batch_id;

                    //in case of batch processing
                    if (retrievedPayout.items != null)
                    {
                        foreach (var _error in retrievedPayout.items)
                        {
                            if (_error.error != null)
                            {
                                _PaymentResponse.ErrorDescription = _PaymentResponse.ErrorDescription + _error.payout_item.receiver + " : " + _error.error.message + " /n ";
                            }
                        }

                        foreach (var _error in retrievedPayout.items)
                        {
                            _PaymentResponse.ErrorDescription = _PaymentResponse.ErrorDescription + _error.payout_item.receiver + " : " + _error.transaction_status + " /n ";
                        }
                    }

                    return _PaymentResponse;
                }

                _PaymentResponse.ErrorDescription = "Error";
                return _PaymentResponse;
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
                _PaymentResponse.ErrorDescription = ex.Message;
                return _PaymentResponse;
            }


        }

        #endregion
    }
}

*********** Payment Response ***********************

namespace NOBOLO.Library.PaymentLib
{
    public class PaymentResponse
    {
        public string PaymentKey { get; set; }

        public string ErrorDescription { get; set; }

        public string PaymentStatus { get; set; }
    }
}



**************  Payment Response END *******************


*********** Paypal configuration***********************



using NOBOLO.Library.Utilities;
using PayPal.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;

namespace NOBOLO.Library.PaymentLib
{
    //Paypal Configuration
    public static class PaypalConfiguration
    {
        //these variables will store the clientID and clientSecret
        //by reading them from the web.config
        public readonly static string ClientId;
        public readonly static string ClientSecret;
        public static Dictionary<string, string> sdkConfig;

        public static object PayPal { get; private set; }

        static PaypalConfiguration()
        {

            var config = GetConfig();
            ClientId = WebConfigurationManager.AppSettings["PaypalApiClientId"].ToString();
            ClientSecret = WebConfigurationManager.AppSettings["PaypalApplClientSecret"].ToString();

        }

        // getting properties from the web.config
        public static Dictionary<string, string> GetConfig()
        {

            sdkConfig = new Dictionary<string, string>();
            sdkConfig.Add("mode", WebConfigurationManager.AppSettings["PayPalMode"].ToString());
            sdkConfig.Add("connectionTimeout", "30000");
            sdkConfig.Add("requestRetries", "5");
            sdkConfig.Add("clientId", ClientId);
            sdkConfig.Add("clientSecret", ClientSecret);

            //sdkConfig.Add("IPAddress", "127.0.0.1");
            //sdkConfig.Add("account1.apiUsername", "***.gmail.com");
            //sdkConfig.Add("account1.apiPassword", "*******");
            //sdkConfig.Add("account1.apiSignature", "api signature here");
            //sdkConfig.Add("account1.applicationId", "app id here");
            //sdkConfig.Add("account1.signatureSubject", "");
            //sdkConfig.Add("account1.certificateSubject", "");
            return sdkConfig;
        }

        private static string GetAccessToken()
        {
            try
            {
                // getting accesstocken from paypal                
                string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();
                //LogHelper.CreateLog("Accesstoken=" + accessToken, ErrorType.PaymentGateway);

                return accessToken;
            }
            catch (PayPal.HttpException ex)
            {
                // Some other error occurred when attempting to send the request to PayPal.
                // ex.Response contains the full response from the API which should highlight the error encountered.
                LogHelper.CreateLog(ex, ErrorType.PaymentGateway);
                return "";
            }
        }

        public static APIContext GetAPIContext()
        {
            // return apicontext object by invoking it with the accesstoken
            APIContext apiContext = new APIContext(GetAccessToken());
            apiContext.Config = GetConfig();
            return apiContext;
        }
    }
}


**************  Paypal Configuration END *******************




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