Ejemplo n.º 1
0
        public string GetAuthorizationToken(String SessionKey,
                                            String additionalParameters, MobileTokenRequest tokenrequest)
        {
            string responseString = "";

            try
            {
                if (SessionKey != Hash512("GENTOKEN" + tokenrequest.oneTimePin + tokenrequest.subscriberId))
                {
                    return("67|Security Validation Failed");
                }
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

                ServicePointManager.SecurityProtocol =
                    (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls) | (SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12);

                String httpMethod  = "POST";
                String resourceUrl = ConfigurationManager.AppSettings["AresourceUrl"];
                resourceUrl = resourceUrl.Replace("{0}", tokenrequest.subscriberId);//Set the account number in the end point
                String clientId        = ConfigurationManager.AppSettings["AclientId"];
                String clientSecretKey = ConfigurationManager.AppSettings["AclientSecretKey"];

                String signatureMethod = "SHA1";//"SHA-1"

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(resourceUrl);
                httpWebRequest.Method = httpMethod;
                String clientIdBase64 = GetAsBase64(clientId);
                String authorization  = AUTHORIZATION_REALM + " " + clientIdBase64;


                long   timestamp = GetCurrentUnixTimestampMillis() / 1000;
                Guid   uuid      = Guid.NewGuid();
                String nonce     = uuid.ToString().Replace("-", "").Replace("+", "");

                String encodedResourceUrl = UpperCaseUrlEncode(resourceUrl);
                String signatureCipher    = httpMethod + "&" + encodedResourceUrl + "&"
                                            + timestamp + "&" + nonce + "&" + clientId + "&"
                                            + clientSecretKey;



                if (!String.IsNullOrWhiteSpace(additionalParameters))
                {
                    signatureCipher = signatureCipher + "&" + additionalParameters;
                }


                MessageDigest messageDigest = MessageDigest
                                              .GetInstance(signatureMethod);
                byte[] signatureBytes = messageDigest
                                        .Digest(Encoding.UTF8.GetBytes(signatureCipher)); //    // encode signature as base 64
                String signature = Convert.ToBase64String(signatureBytes);                //.Replace("+","%2B");

                httpWebRequest.Timeout          = 60000;
                httpWebRequest.ReadWriteTimeout = 60000;
                httpWebRequest.ContentType      = "application/json";
                httpWebRequest.KeepAlive        = false;
                //httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);


                // httpWebRequest.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                String token = "";
                token = GetPassport();

                httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "InterswitchAuth " + clientIdBase64);

                httpWebRequest.Headers.Add(TIMESTAMP, timestamp.ToString());
                httpWebRequest.Headers.Add(NONCE, nonce);
                httpWebRequest.Headers.Add(SIGNATURE_METHOD, signatureMethod);
                httpWebRequest.Headers.Add(SIGNATURE, signature);
                httpWebRequest.Headers.Add(ACCESS_TOKEN, token);

                httpWebRequest.Headers.Add("frontEndPartnerId", tokenrequest.frontEndPartnerId);
                //Authorization: Bearer (Access Token)
                //httpWebRequest.Headers.Add("Authorization", "eyJhbGciOiJSUzI1NiJ9.eyJzY29wZSI6WyJwcm9maWxlIl0sImV4cCI6MTQ3MTYwODQxNCwianRpIjoiNGM5YzEyODAtZTVjMC00OWQwLTkxOGQtZGJiYTI0NDczYjdlIiwiY2xpZW50X2lkIjoiSUtJQURGQjZGNTNGRUUzQ0U0QjY5MUIzNDNDNTVEMjk1NkJFMUNGNEE5QkMifQ.GY7U2UMVvUHSTqz_ybapCxEIA0jHUQdxXL_iuPOE_rcXecz7n0AzsFbM_Nt9bdOGRszQJ8amB3PUf638BR9lVCRWZU73OXN6G5G6o8t-ZjP2GThc4J-34sLl-yZWGZpP4Fu4uMKgz07276QSvMEPWPIBhvUYS2x1PAgXQXUV4ayGT3ps9ROv2uTkMhKgQsWyMUNsvnWSGDSQbVK7AUPFruYAMk-jxo8loY8T3edqRP-rk7ZO48SiLoNhq-YLTU_RLUK76g8c8RtKphOR2HGXOPW0IInxPKvpM5dItg6VxTdeHiJPnEPMlhVcMbvQjbe");

                Logheaders(httpWebRequest.Headers);

                String postData = JsonConvert.SerializeObject(tokenrequest);
                nLogger.Info(" body", postData);
                StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                requestWriter.Write(postData);
                requestWriter.Close();


                nLogger.Info("About to Get Response ");
                var response = (HttpWebResponse)httpWebRequest.GetResponse();

                //nLogger.Info("RESPONSE: " + response.StatusCode);
                if (HttpStatusCode.OK == response.StatusCode || HttpStatusCode.Created == response.StatusCode)//Successful
                {
                    // Get the stream containing content returned by the server.
                    Stream dataStream = response.GetResponseStream();
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    responseString = reader.ReadToEnd();
                }
                nLogger.Info("responseString " + responseString);
            }
            catch (WebException ex)
            {
                try
                {
                    nLogger.Error(ex);
                    nLogger.Info(ex.StackTrace);
                    nLogger.Info(ex.Message);

                    using (WebResponse response = ex.Response)
                    {
                        HttpWebResponse httpResponse = (HttpWebResponse)response;
                        nLogger.Info("Error code: {0}", httpResponse.StatusCode);
                        nLogger.Info("Status Description: {0}", httpResponse.StatusDescription);
                        string text = "";
                        using (Stream data = response.GetResponseStream())
                        {
                            text = new StreamReader(data).ReadToEnd();
                            nLogger.Info(text);
                        }
                    }
                }
                catch
                {
                }
            }
            catch (Exception ex)
            {
                //nLogger.Info(ex);
                nLogger.Info(ex.ToString());
            }

            return(responseString);
        }
Ejemplo n.º 2
0
        public CardlessWithdrawalTransaction GeneratePayCode(String SessionKey, String SourceChannel, String AccountNumber, String subscriberID, String oneTimePin, String CIF, decimal Amount)
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            ServicePointManager.SecurityProtocol =
                (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls) | (SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12);



            int tokenLifeTimeInMinute = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["tokenLifeExpiryInMinutes"]);

            String accountType = "00";//00- All 10-Savings 20-Current
            CardlessWithdrawalTransaction transaction = new CardlessWithdrawalTransaction();

            try
            {
                String additionalParameters = "";

                MobileTokenRequest tokenrequest = new MobileTokenRequest();

                tokenrequest.subscriberId = subscriberID;//Mandatory - AccountNumber


                String transactionreference = DateTime.Now.ToString("yyMMddHHmmssfff");
                String otp = DateTime.Now.ToString("yyMMddHHmmssfff");
                tokenrequest.oneTimePin    = oneTimePin;
                tokenrequest.providerToken = otp;// GeneratedToken;//

                if (IsLive())
                {
                    nLogger.Info("is live  credential");
                    tokenrequest.paymentMethodTypeCode = PaymentMethodTypes.MMO;   //Mandatory this is for production,
                    tokenrequest.frontEndPartnerId     = FrontEndPartners.Octopus; //Mandatory this is for production,
                    tokenrequest.paymentMethodCode     = PaymentMethods.Octopus;   //Mandatory
                }
                else
                {
                    nLogger.Info("is test  credential");
                    tokenrequest.frontEndPartnerId     = FrontEndPartners.HbOnline; //Mandatory:  this code needs to be agreed with ISW
                    tokenrequest.paymentMethodTypeCode = PaymentMethodTypes.MMO;    //Mandatory t
                    tokenrequest.paymentMethodCode     = PaymentMethods.Octopus;    //Mandatory
                }

                //tokenrequest.paymentMethodTypeCode = PaymentMethodTypes.MMO ;//Mandatory this is for test


                tokenrequest.tokenLifeTimeInMinutes = tokenLifeTimeInMinute;
                tokenrequest.payWithMobileChannel   = PayWithMobileChannels.ATM;//ATM, POS,MOBILE and WEB.
                //tokenrequest.autoEnroll = "true";
                //tokenrequest.accountNo = AccountNumber;
                //tokenrequest.accountType = accountType;
                tokenrequest.ttid = "1234";

                tokenrequest.transactionType       = TransactionTypes.CashWithdrawal; //A code to indicate the transaction type e.g Payment, Cash Withdrawal, Deposit
                tokenrequest.codeGenerationChannel = CodeGenerationChannels.Mobile;   //Conditional//A code to identify the channel where the code is generated e.g. USSD, Mobile et al
                tokenrequest.Amount = Amount;                                         // 9000.00;//Conditional


                //if (SessionKey != Hash512("GENTOKEN" + AccountNumber + Amount + subscriberID + oneTimePin + SourceChannel + CIF))
                if (false)

                {
                    transaction.TransactionReference = "67|Security Validation Failed";
                }
                else
                if ((Amount % 1000) != 0)
                {
                    transaction.TransactionReference = "67|Amount must be in multiples of 1000 (NGN).";
                }
                else if (Amount > 20000 || Amount < 1000)
                {
                    transaction.TransactionReference = "67|Amount cannot be greater than 20000 and less than 1000.";
                }
                else
                {
                    String hashKey = Hash512("GENTOKEN" + tokenrequest.oneTimePin + tokenrequest.subscriberId);
                    nLogger.Info("token request payload  :::::: " + JsonSerializer(tokenrequest));
                    TokenGeneration generation = new TokenGeneration();
                    String          response   = generation.GetAuthorizationToken(hashKey, additionalParameters, tokenrequest);
                    nLogger.Info("Before Getting AUthorisation");
                    nLogger.Info("response :::::: " + response);

                    if ((response + "").StartsWith("67|"))
                    {
                        transaction.TransactionReference = response;
                    }
                    else
                    if (response.Length > 3)
                    {
                        nLogger.Info("response :::2::: " + response);
                        TokenRequest retobject = JsonConvert.DeserializeObject <TokenRequest>(response);

                        //Send WICODE to registered Phone Number
                        //Place Lien On Account
                        //Check Available Balance
                        nLogger.Info("response :::3::: " + response);
                        transaction = new CardlessWithdrawalTransaction()
                        {
                            SourceChannel         = SourceChannel,
                            AccountNumber         = AccountNumber,
                            CodeGenerationChannel = tokenrequest.codeGenerationChannel,
                            CIF = CIF,
                            FrontEndPartnerId      = tokenrequest.frontEndPartnerId,
                            OneTimePassword        = Hash512(tokenrequest.oneTimePin),
                            PaymentMethodCode      = tokenrequest.paymentMethodCode,
                            PaymentMethodTypeCode  = tokenrequest.paymentMethodTypeCode,
                            PayWithMobileChannel   = tokenrequest.payWithMobileChannel,
                            ProviderToken          = tokenrequest.providerToken,
                            RequestDate            = DateTime.Now,
                            TokenUsageCount        = 0,
                            AmountAuthorized       = 0,
                            TokenLifeTimeInMinutes = tokenrequest.tokenLifeTimeInMinutes,
                            TransactionAmount      = tokenrequest.Amount,
                            TransactionType        = tokenrequest.transactionType,
                            TransactionReference   = transactionreference,
                            PayWithMobileToken     = retobject.payWithMobileToken,
                            IsCanceled             = false,
                            IsExpired   = false,
                            IsTokenUsed = false
                        };



                        String        signatureMethod = "SHA1";
                        String        CypherKey       = String.Format("{0}|{1}|{2}", transaction.AccountNumber, transaction.ProviderToken, transaction.TransactionType);
                        MessageDigest messageDigest   = MessageDigest
                                                        .GetInstance(signatureMethod);
                        byte[] signatureBytes = messageDigest
                                                .Digest(Encoding.UTF8.GetBytes(CypherKey)); // encode signature as base 64
                        String signature = Convert.ToBase64String(signatureBytes);
                        nLogger.Info("response :::5::: " + signature);
                        transaction.AuthorizationSessionKey = signature;


                        DateTime ExpiryDate = transaction.RequestDate.Value.AddMinutes(Convert.ToInt32(transaction.TokenLifeTimeInMinutes));


                        transaction.ExpiryDate = ExpiryDate;
                        nLogger.Info("response :::6::: " + ExpiryDate);
                        nLogger.Info("response :::7:: " + JsonConvert.SerializeObject(transaction));
                        var clearPayCode = transaction.PayWithMobileToken;

                        //send mail and sms
                    }
                    else
                    {
                        nLogger.Info(response);
                        transaction.TransactionReference = "67|Cannot generate Paycode at the moment. Please try again later.";//Could not generate WICode
                    }
                }
            }
            catch (WebException ex)
            {
                nLogger.Info(ex.ToString());
                try
                {
                    using (WebResponse response = ex.Response)
                    {
                        HttpWebResponse httpResponse = (HttpWebResponse)response;
                        nLogger.Info("Error code: {0}", httpResponse.StatusCode);
                        nLogger.Info("Status Description: {0}", httpResponse.StatusDescription);
                        string text = "";
                        using (Stream data = response.GetResponseStream())
                        {
                            text = new StreamReader(data).ReadToEnd();
                            nLogger.Info(text);
                        }
                    }
                }
                catch
                { nLogger.Info("Something went wrong"); }


                transaction.TransactionReference = "67|Cannot generate Paycode at the moment. Please try again later.";
                nLogger.Error(ex);
            }
            catch (Exception ex)
            {
                transaction.TransactionReference = "67|Cannot generate Paycode at the moment. Please try again later.";
                nLogger.Error(ex);
            }

            return(transaction);
        }