WebClientResponse ProcessWebClient(dynamic outrequest)
        {
            WebClientResponse wcresponse = new WebClientResponse();
            List <string>     errors     = new List <string>();
            WebClient         client     = WePayPaymentHelper.WePayWebClient(_wepayPaymentSettings);
            string            uriString  = GetWePayUrl() + outrequest.actionUrl;
            var data = JsonConvert.SerializeObject(outrequest);

            try
            {
                client.UploadString(new Uri(uriString), "POST", data);

                var chkoutreq = new CheckoutRequest {
                    checkout_id = Convert.ToInt64(outrequest.checkout_id)
                };
                data      = JsonConvert.SerializeObject(chkoutreq);
                uriString = GetWePayUrl() + chkoutreq.actionUrl;
                client    = WePayPaymentHelper.WePayWebClient(_wepayPaymentSettings);
                var     clientresp = client.UploadString(new Uri(uriString), "POST", data);
                dynamic response   = JsonConvert.DeserializeObject(clientresp);
                wcresponse.state = Convert.ToString(response.state);
            }
            catch (WebException we)
            {
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse httpErrorResponse = (HttpWebResponse)we.Response as HttpWebResponse;
                    StreamReader    reader            = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8);
                    string          responseBody      = reader.ReadToEnd();
                    var             errResp           = JsonConvert.DeserializeObject <ErrorResponse>(responseBody);
                    errors.Add(string.Format("Error: {0};" + Environment.NewLine + " Error Message: {1};" + Environment.NewLine + " Error Description: {2}", errResp.error, errResp.error_description, we.Message));
                }
                else
                {
                    errors.Add(string.Format("Error: {0}", we.Message));
                }
            }
            catch (Exception exc)
            {
                errors.Add(string.Format("Error: {0}", exc.Message));
            }
            wcresponse.Errors = errors;
            return(wcresponse);
        }
        /// <summary>
        /// Gets PDT details
        /// </summary>
        /// <param name="tx">TX</param>
        /// <param name="values">Values</param>
        /// <param name="response">Response</param>
        /// <returns>Result</returns>
        public bool GetPDTDetails(string checkout_id, out Dictionary <string, string> values, out string response)
        {
            WebClient client = WePayPaymentHelper.WePayWebClient(_wepayPaymentSettings);

            long iid   = 0;
            bool valid = Int64.TryParse(checkout_id, out iid);

            var outresp = new CheckoutRequest {
                checkout_id = iid
            };
            bool   success   = false;
            string uriString = GetWePayUrl() + outresp.actionUrl;
            var    data      = JsonConvert.SerializeObject(outresp);
            var    json      = "";

            response = null;
            values   = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            try
            {
                json = (data.Length > 3) ?
                       client.UploadString(new Uri(uriString), "POST", data) :
                       client.DownloadString(new Uri(uriString));

                dynamic jsonresponse = JsonConvert.DeserializeObject(json);
                values.Add("reference_id", Convert.ToString(jsonresponse.reference_id));
                values.Add("checkout_id", Convert.ToString(jsonresponse.checkout_id));
                values.Add("gross", Convert.ToString(jsonresponse.gross));
                values.Add("state", Convert.ToString(jsonresponse.state));
                values.Add("currency", Convert.ToString(jsonresponse.currency));
                values.Add("fee", Convert.ToString(jsonresponse.fee));
                values.Add("shipping_fee", Convert.ToString(jsonresponse.shipping_fee));

                success = true;

                // Log details for testing
                if (_wepayPaymentSettings.UseSandbox)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine("PDT Details:");
                    sb.AppendLine(" checkout_id: " + checkout_id);
                    sb.AppendLine(" uriString: " + uriString);
                    sb.AppendLine(" response: " + json);
                    _logger.Information(sb.ToString());
                }
            }
            catch (WebException we)
            {
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse httpErrorResponse = (HttpWebResponse)we.Response as HttpWebResponse;

                    StreamReader reader       = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8);
                    string       responseBody = reader.ReadToEnd();
                    var          errResp      = JsonConvert.DeserializeObject <ErrorResponse>(responseBody);
                    response = string.Format("Error: {0}" + Environment.NewLine + " Error Message: {1}" + Environment.NewLine + " Error Description: {2}", errResp.error, errResp.error_description, we.Message);
                }
                else
                {
                    response = string.Format("Error: {0}", we.Message);
                }
            }
            catch (Exception exc) {
                response = string.Format("Error: {0}", exc.Message);
            }

            if (!string.IsNullOrEmpty(response))
            {
                _logger.Error(response);
            }

            return(success);
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult()
            {
                NewPaymentStatus = PaymentStatus.Pending
            };
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            WebClient client      = WePayPaymentHelper.WePayWebClient(_wepayPaymentSettings);
            string    returnUrl   = _webHelper.GetStoreLocation(_storeContext.CurrentStore.SslEnabled) + "Plugins/PaymentWePay/PDTHandler";
            string    callbackUrl = _webHelper.GetStoreLocation(_storeContext.CurrentStore.SslEnabled) + "Plugins/PaymentWePay/WCBHandler";

            var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);
            var shipping   = 0;

            CheckoutCreateCaptureRequest outrequest = new CheckoutCreateCaptureRequest
            {
                account_id        = _wepayPaymentSettings.AccountId,
                type              = _wepayPaymentSettings.CheckoutType,
                amount            = orderTotal,
                short_description = _storeService.GetStoreById(processPaymentRequest.StoreId).Name,
                long_description  = string.Format("{0} order #{1}", _storeService.GetStoreById(processPaymentRequest.StoreId).Name, processPaymentRequest.OrderGuid),
                reference_id      = processPaymentRequest.OrderGuid.ToString(),
                auto_capture      = (_wepayPaymentSettings.TransactMode == TransactMode.CreateAndCapture),
                redirect_uri      = returnUrl,
                callback_uri      = callbackUrl,
                fee_payer         = _wepayPaymentSettings.FeePayer,
                require_shipping  = _wepayPaymentSettings.RequireShipping,
                currency          = _wepayPaymentSettings.Currency,
                funding_sources   = _wepayPaymentSettings.FundingSources,
                shipping_fee      = shipping,
                prefill_info      = new PrefillInfo()
                {
                    name = customer.BillingAddress.FirstName + " " + customer.BillingAddress.LastName, email = customer.BillingAddress.Email
                }
            };
            string uriString = GetWePayUrl() + outrequest.actionUrl;
            var    data      = JsonConvert.SerializeObject(outrequest);

            try
            {
                var clientresp = client.UploadString(new Uri(uriString), "POST", data);

                dynamic response = JsonConvert.DeserializeObject(clientresp);
                var     settings = new WePayPaymentSettings()
                {
                    checkout_uri            = response.checkout_uri,
                    UseSandbox              = _wepayPaymentSettings.UseSandbox,
                    TransactMode            = _wepayPaymentSettings.TransactMode,
                    AccessToken             = _wepayPaymentSettings.AccessToken,
                    AccountId               = _wepayPaymentSettings.AccountId,
                    ClientSecret            = _wepayPaymentSettings.ClientSecret,
                    AdditionalFee           = _wepayPaymentSettings.AdditionalFee,
                    AdditionalFeePercentage = _wepayPaymentSettings.AdditionalFeePercentage,
                    ClientId = _wepayPaymentSettings.ClientId,
                    PdtValidateOrderTotal = _wepayPaymentSettings.PdtValidateOrderTotal,
                    FeePayer        = _wepayPaymentSettings.FeePayer,
                    RequireShipping = _wepayPaymentSettings.RequireShipping,
                    Currency        = _wepayPaymentSettings.Currency,
                    FundingSources  = _wepayPaymentSettings.FundingSources,
                    CheckoutType    = _wepayPaymentSettings.CheckoutType
                };
                _settingService.SaveSetting(settings);
            }
            catch (WebException we)
            {
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse httpErrorResponse = (HttpWebResponse)we.Response as HttpWebResponse;

                    StreamReader reader       = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8);
                    string       responseBody = reader.ReadToEnd();
                    var          errResp      = JsonConvert.DeserializeObject <ErrorResponse>(responseBody);
                    result.AddError(string.Format("Error: {0};" + Environment.NewLine + " Error Message: {1};" + Environment.NewLine + " Error Description: {2}", errResp.error, errResp.error_description, we.Message));
                }
                else
                {
                    result.AddError(string.Format("Error: {0}", we.Message));
                }
            }
            return(result);
        }