Beispiel #1
0
        private bool doRefund(StripeSession session, Transaction charge, decimal?amount = null, string description = null, object extraData = null)
        {
            var fromActualData = session.FetchAccountData(charge.From);

            var refundAmount = amount ?? charge.Amount.Value;

            try
            {
                var bodyPrms = new Dictionary <string, string>()
                {
                    { PRM_AMOUNT, ((int)((refundAmount * 100))).ToString() }
                };

                if (description.IsNotNullOrWhiteSpace())
                {
                    bodyPrms.Add(PRM_REASON, description);
                }

                var prms = new WebClient.RequestParams(this)
                {
                    UserName       = session.SecretKey,
                    Method         = HTTPRequestMethod.POST,
                    BodyParameters = bodyPrms
                };

                dynamic obj = WebClient.GetJsonAsDynamic(new Uri(REFUND_URI.Args(charge.Token)), prms);

                dynamic lastRefund = ((NFX.Serialization.JSON.JSONDataArray)obj.refunds.Data).First();

                var created = ((long)obj.created).FromSecondsSinceUnixEpochStart();

                StatRefund(charge, amount);

                return(true);
            }
            catch (Exception ex)
            {
                StatRefundError();

                var wex = ex as System.Net.WebException;
                if (wex != null)
                {
                    var response = wex.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        string errorMessage = this.GetType().Name +
                                              ".Refund(money: {0}, card: {1}, description: '{2}')"
                                              .Args(charge.Amount, fromActualData.AccountID, description);
                        PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
                        if (stripeEx != null)
                        {
                            throw stripeEx;
                        }
                    }
                }

                throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CAPTURE_CAPTURED_PAYMENT_ERROR + this.GetType()
                                                 + " .Refund(session='{0}', charge='{1}')".Args(session, charge), ex);
            }
        }
Beispiel #2
0
        private bool doCall(string from, string to, string body, string auth)
        {
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.FORM_URL_ENCODED,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, auth }
                },
                BodyParameters = new Dictionary <string, string>
                {
                    { "From", from },
                    { "To", to },
                    { "Body", body }
                }
            };
            var response = WebClient.GetJson(new Uri(URI_MESSAGES.Args(AccountSid)), request);

            if (response[ERROR_MESSAGE].AsString().IsNotNullOrEmpty())
            {
                return(false);
            }
            return(true);
        }
Beispiel #3
0
        private JSONDataMap doGetRate(ShippoSession session, string rateID, Guid logID)
        {
            try
            {
                var cred = (ShippoCredentials)session.User.Credentials;

                var request = new WebClient.RequestParams(this)
                {
                    Method      = HTTPRequestMethod.GET,
                    ContentType = ContentType.JSON,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                    }
                };

                var response = WebClient.GetJson(new Uri((URI_API_BASE + URI_RATES).Args(rateID)), request);

                checkResponse(response);

                return(response);
            }
            catch (Exception ex)
            {
                var error = ShippingException.ComposeError(ex.Message, ex);
                Log(MessageType.Error, "getRate()", StringConsts.SHIPPO_CREATE_LABEL_ERROR, error, relatedMessageID: logID);
                return(null);
            }
        }
Beispiel #4
0
        public void PutResource <TResource, TResult>(string path, TResource networkInterface, out TResult result)
            where TResource : Resource
            where TResult : Resource
        {
            var logID = Log(MessageType.Info, "putResource()", "Get " + typeof(TResource).Name);

            try
            {
                var request = new WebClient.RequestParams(Caller)
                {
                    Method      = HTTPRequestMethod.PUT,
                    ContentType = ContentType.JSON,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, Token.AuthorizationHeader }
                    },
                    Body = networkInterface.ToJSON(JSON)
                };

                var response = WebClient.GetJson(new Uri(Host, path), request);
                result = JSONReader.ToRow <TResult>(response, nameBinding: JSONReader.NameBinding.ByBackendName("*"));
                result.Validate();
            }
            catch (Exception error)
            {
                Log(MessageType.Error, "putResource()", error.Message, error, relatedMessageID: logID);
                throw error;
            }
        }
Beispiel #5
0
        public TResource GetResource <TResource>(string path)
            where TResource : Resource
        {
            var logID = Log(MessageType.Info, "getResource()", "Get " + typeof(TResource).Name);

            try
            {
                var request = new WebClient.RequestParams(Caller)
                {
                    Method  = HTTPRequestMethod.GET,
                    Headers = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, Token.AuthorizationHeader }
                    }
                };

                var response = WebClient.GetJson(new Uri(Host, path), request);
                var result   = JSONReader.ToRow <TResource>(response, nameBinding: JSONReader.NameBinding.ByBackendName("*"));
                result.Validate();
                return(result);
            }
            catch (Exception error)
            {
                Log(MessageType.Error, "getResource()", error.Message, error, relatedMessageID: logID);
                throw error;
            }
        }
Beispiel #6
0
        private payoutBatch createPayouts(payout payout, PayPalOAuthToken authToken, Guid logID)
        {
            Log(MessageType.Info, "createPayouts()", "Create payouts", relatedMessageID: logID);

            try
            {
                var request = new WebClient.RequestParams(this)
                {
                    Method      = HTTPRequestMethod.POST,
                    ContentType = ContentType.JSON,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, authToken.AuthorizationHeader }
                    },
                    QueryParameters = new Dictionary <string, string>
                    {
                        { PRM_SYNC_MODE, m_SyncMode.AsString() }
                    },
                    Body = payout.ToJSONDataMap().ToJSON(JSONWritingOptions.Compact)
                };

                var response = WebClient.GetJson(URI_CreatePayouts(), request);
                Log(MessageType.Trace, "createPayouts()", "Payouts", relatedMessageID: logID, parameters: response.ToJSON());
                Log(MessageType.Info, "createPayouts()", "Payouts created", relatedMessageID: logID);
                return(new payoutBatch(response));
            }
            catch (Exception ex)
            {
                var error = composeError(StringConsts.PAYPAL_PAYOUTS_CREATE_ERROR_MESSAGE.Args(ex.ToMessageWithType()), ex);
                Log(MessageType.Error, "createPayouts()", error.Message, relatedMessageID: logID);
                throw error;
            }
        }
Beispiel #7
0
        private payoutItemDetails getPayoutItem(string payoutItemID, PayPalOAuthToken authToken, Guid logID)
        {
            Log(MessageType.Info, "getPayouts()", "Fetch payouts", relatedMessageID: logID);

            try
            {
                var request = new WebClient.RequestParams(this)
                {
                    Method      = HTTPRequestMethod.GET,
                    ContentType = ContentType.JSON,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, authToken.AuthorizationHeader }
                    }
                };

                var response = WebClient.GetJson(URI_GetPayoutItem(payoutItemID), request);
                Log(MessageType.Trace, "getPayouts()", "Payouts", relatedMessageID: logID, parameters: response.ToJSON());
                Log(MessageType.Info, "getPayouts()", "Payotus fetched", relatedMessageID: logID);

                return(new payoutItemDetails(response));
            }
            catch (Exception ex)
            {
                var error = composeError(StringConsts.PAYPAL_PAYOUT_ITEM_FETCH_ERROR_MESSAGE.Args(ex.ToMessageWithType()), ex);
                Log(MessageType.Error, "getPayouts()", error.Message, relatedMessageID: logID);
                throw error;
            }
        }
Beispiel #8
0
        private Label doCreateLabel(ShippoSession session, IShippingContext context, Shipment shipment, object labelID, Guid logID)
        {
            var cred = (ShippoCredentials)session.User.Credentials;

            // label request
            var request = new WebClient.RequestParams
            {
                Caller      = this,
                Uri         = new Uri(URI_API_BASE + URI_TRANSACTIONS),
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = getCreateLabelRequestBody(session, shipment, labelID)
            };

            var response = WebClient.GetJson(request);

            Log(MessageType.Info, "doCreateLabel()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            // get label bin data from URL in response
            string labelURL = response["label_url"].AsString().EscapeURIStringWithPlus();
            string contentType;
            var    data = WebClient.GetData(new Uri(labelURL), this, out contentType);

            // get used rate, fill label's data
            var id             = response["object_id"];
            var trackingNumber = response["tracking_number"].AsString();
            var rate           = getRate(session, response["rate"].AsString(), logID);
            var carrier        = rate != null?
                                 CARRIERS.First(c => c.Value.EqualsIgnoreCase(rate["provider"].AsString())).Key:
                                 Carrier.Unknown;

            var amount = rate != null ?
                         new NFX.Financial.Amount(rate["currency"].AsString(), rate["amount"].AsDecimal()) :
                         new NFX.Financial.Amount(string.Empty, 0);

            var label = new Label(id,
                                  labelURL,
                                  data,
                                  shipment.LabelFormat,
                                  trackingNumber,
                                  carrier,
                                  amount);

            if (labelID == null)
            {
                StatCreateLabel();
            }
            else
            {
                StatCreateReturnLabel();
            }

            return(label);
        }
Beispiel #9
0
        private void cancelUnclaimedPayout(string itemID, PayPalSession payPalSession)
        {
            try
            {
                var request = new WebClient.RequestParams
                {
                    Caller      = this,
                    Uri         = new Uri(m_ApiUri + URI_CANCEL_UNCLAIMED_PAYOUT.Args(itemID)),
                    Method      = HTTPRequestMethod.POST,
                    ContentType = ContentType.JSON,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, HDR_AUTHORIZATION_OAUTH.Args(payPalSession.AuthorizationToken.AccessToken) },
                    }
                };

                var response = WebClient.GetJson(request);
                Log(MessageType.Info, "cancelUnclaimedPayout()", response.ToJSON());
            }
            catch (Exception ex)
            {
                var message = StringConsts.PAYPAL_PAYOUT_CANCEL_ERROR.Args(ex.ToMessageWithType());
                var error   = PayPalPaymentException.ComposeError(message, ex);
                Log(MessageType.Error, "cancelUnclaimedPayout()", error.Message, ex);

                throw error;
            }
        }
Beispiel #10
0
        /// <summary>
        /// Overload of Charge method with Stripe-typed session parameter
        /// </summary>
        public Transaction Charge(StripeSession session, ITransactionContext context, Account from, Account to, Amount amount, bool capture = true, string description = null, object extraData = null)
        {
            var fromActualData = PaySystemHost.AccountToActualData(context, from);

            try
            {
                var bodyPrms = new Dictionary <string, string>()
                {
                    { PRM_AMOUNT, ((int)((amount.Value * 100))).ToString() },
                    { PRM_CURRENCY, amount.CurrencyISO.ToString().ToLower() },
                    { PRM_DESCRIPTION, description },
                    { PRM_CAPTURE, capture.ToString() }
                };

                fillBodyParametersFromAccount(bodyPrms, fromActualData);

                var prms = new WebClient.RequestParams()
                {
                    Uri            = new Uri(CHARGE_URI),
                    Caller         = this,
                    UName          = session.SecretKey,
                    Method         = HTTPRequestMethod.POST,
                    BodyParameters = bodyPrms
                };

                dynamic obj = WebClient.GetJson(prms);

                var created = ((long)obj.created).FromSecondsSinceUnixEpochStart();

                var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Charge);

                var ta = new Transaction(taId, TransactionType.Charge, from, to, this.Name, obj.id, amount, created, description);

                StatCharge(amount);

                return(ta);
            }
            catch (Exception ex)
            {
                var wex = ex as System.Net.WebException;

                if (wex != null)
                {
                    var response = wex.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        string errorMessage = this.GetType().Name +
                                              ".Charge(money: {0}, card: {1}, amount: '{2}')".Args(amount.Value, fromActualData.AccountNumber, amount);
                        var stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
                        throw stripeEx;
                    }
                }

                StatChargeError();

                throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + this.GetType()
                                                 + " .Capture(session='{0}', card='{1}', amount='{2}')".Args(session, from, amount), ex);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Transfers funds to customerAccount from current stripe account
        /// (which credentials is supplied in current session)
        /// </summary>
        private Transaction transfer(StripeSession stripeSession, ITransactionContext context, string recipientID, Account customerAccount, Amount amount, string description)
        {
            var actualAccountData = PaySystemHost.AccountToActualData(context, customerAccount);

            try
            {
                var prms = new WebClient.RequestParams()
                {
                    Uri            = new Uri(TRANSFER_URI),
                    Caller         = this,
                    UName          = stripeSession.SecretKey,
                    Method         = HTTPRequestMethod.POST,
                    BodyParameters = new Dictionary <string, string>()
                    {
                        { PRM_RECIPIENT, recipientID },
                        { PRM_AMOUNT, ((int)((amount.Value * 100))).ToString() },
                        { PRM_CURRENCY, amount.CurrencyISO.ToLower() },
                        { PRM_DESCRIPTION, description }
                    }
                };

                dynamic obj = WebClient.GetJson(prms);

                var created = ((long)obj.created).FromSecondsSinceUnixEpochStart();

                var taId = PaySystemHost.GenerateTransactionID(stripeSession, context, TransactionType.Transfer);

                var ta = new Transaction(taId, TransactionType.Transfer, Account.EmptyInstance, customerAccount, this.Name, obj.id, amount, created, description);

                StatTransfer(amount);

                return(ta);
            }
            catch (Exception ex)
            {
                var wex = ex as System.Net.WebException;
                if (wex == null)
                {
                    var response = wex.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        string errorMessage = this.GetType().Name +
                                              ".transfer(recipientID='{0}', customerAccount='{1}', amount='{2}')".Args(recipientID, actualAccountData, amount);
                        PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
                        if (stripeEx != null)
                        {
                            throw stripeEx;
                        }
                    }
                }

                StatTransferError();

                throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_TRANSFER_ERROR + this.GetType()
                                                 + " .transfer(customerAccout='{0}')".Args(actualAccountData), ex);
            }
        }
Beispiel #12
0
        private Address doValidateAddress(ShippoSession session, IShippingContext context, Address address, Guid logID, out ValidateShippingAddressException error)
        {
            error = null;
            var cred = (ShippoCredentials)session.User.Credentials;
            var body = getAddressBody(address);

            body["validate"] = true;

            // validate address request
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = body.ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(new Uri(URI_API_BASE + URI_ADDRESS), request);

            Log(MessageType.Info, "doValidateAddress()", response.ToJSON(), relatedMessageID: logID);

            // check for validation errors:
            // Shippo API can return STATUS_INVALID or (!!!) STATUS_VALID but with 'code'="Invalid"
            var         state    = response["object_state"].AsString(STATUS_INVALID);
            var         messages = response["messages"] as JSONDataArray;
            JSONDataMap message  = null;
            var         code     = string.Empty;
            var         text     = string.Empty;

            if (messages != null)
            {
                message = messages.FirstOrDefault() as JSONDataMap;
            }
            if (message != null)
            {
                code = message["code"].AsString(string.Empty);
                text = message["text"].AsString(string.Empty);
            }

            // error found
            if (!state.EqualsIgnoreCase(STATUS_VALID) || code.EqualsIgnoreCase(CODE_INVALID))
            {
                var errMess = StringConsts.SHIPPO_VALIDATE_ADDRESS_INVALID_ERROR.Args(text);
                Log(MessageType.Error, "doValidateAddress()", errMess, relatedMessageID: logID);
                error = new ValidateShippingAddressException(errMess, text);
                return(null);
            }

            // no errors
            var corrAddress = getAddressFromJSON(response);

            return(corrAddress);
        }
Beispiel #13
0
        /// <summary>
        /// Creates new recipient in Stripe system.
        /// Is used as a temporary entity to substitute recipient parameter in Transfer operation then deleted
        /// </summary>
        private string createRecipient(StripeSession stripeSession, ITransactionContext context, Account recipientAccount, string description)
        {
            var recipientActualAccountData = PaySystemHost.AccountToActualData(context, recipientAccount);

            try
            {
                var bodyPrms = new Dictionary <string, string>()
                {
                    { PRM_NAME, recipientActualAccountData.AccountTitle },
                    { PRM_TYPE, recipientActualAccountData.AccountType == AccountType.Corporation ? "corporation" : "individual" },
                    { PRM_EMAIL, recipientActualAccountData.BillingEmail }
                };

                fillBodyParametersFromAccount(bodyPrms, recipientActualAccountData);

                var prms = new WebClient.RequestParams()
                {
                    Uri            = new Uri(RECIPIENT_URI),
                    Caller         = this,
                    UName          = stripeSession.SecretKey,
                    Method         = HTTPRequestMethod.POST,
                    BodyParameters = bodyPrms
                };

                dynamic obj = WebClient.GetJson(prms);

                return(obj.id);
            }
            catch (Exception ex)
            {
                var wex = ex as System.Net.WebException;
                if (wex != null)
                {
                    var response = wex.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        string errorMessage = this.GetType().Name +
                                              ".createRecipient(customerAccout='{0}')".Args(recipientActualAccountData);
                        PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
                        if (stripeEx != null)
                        {
                            throw stripeEx;
                        }
                    }
                }

                throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CREATE_RECIPIENT_ERROR + this.GetType()
                                                 + " .Refund(customerAccout='{0}')".Args(recipientActualAccountData), ex);
            }

            throw new NotImplementedException();
        }
Beispiel #14
0
        private XDocument getResponse(BraintreeSession session, Uri uri, XDocument body = null, HTTPRequestMethod method = HTTPRequestMethod.POST)
        {
            if (!session.IsValid)
            {
                throw new PaymentException("Braintree: " + StringConsts.PAYMENT_BRAINTREE_SESSION_INVALID.Args(this.GetType().Name + ".getResponse"));
            }

            var prms = new WebClient.RequestParams()
            {
                Caller      = this,
                Uri         = uri,
                Method      = method,
                AcceptType  = ContentType.XML_APP,
                ContentType = ContentType.XML_APP,
                Headers     = new Dictionary <string, string>()
                {
                    { HDR_AUTHORIZATION, getAuthHeader(session.User.Credentials) },
                    { HDR_X_API_VERSION, API_VERSION }
                },
                Body = body != null ? new XDeclaration("1.0", "UTF-8", null).ToString() + body.ToString(SaveOptions.DisableFormatting) : null
            };

            try {
                return(WebClient.GetXML(prms));
            }
            catch (System.Net.WebException ex)
            {
                StatChargeError();
                var resp = (System.Net.HttpWebResponse)ex.Response;

                if (resp != null && resp.StatusCode == (System.Net.HttpStatusCode) 422)
                {
                    using (var sr = new StreamReader(resp.GetResponseStream()))
                    {
                        var respStr  = sr.ReadToEnd();
                        var response = respStr.IsNotNullOrWhiteSpace() ? XDocument.Parse(respStr) : null;
                        if (response != null)
                        {
                            var apiErrorResponse = response.Element("api-error-response");
                            throw new PaymentException(apiErrorResponse.Element("message").Value, ex);
                        }
                    }
                }
                throw;
            }
            catch
            {
                throw;
            }
        }
Beispiel #15
0
        /// <summary>
        /// MessageSink DoSendMsg implementation
        /// </summary>
        /// <param name="msg">Message</param>
        protected override void DoSendMsg(Message msg)
        {
            if (msg == null || msg.TOAddress.IsNullOrWhiteSpace())
            {
                return;
            }

            var request = new WebClient.RequestParams()
            {
                Caller         = this,
                Method         = HTTPRequestMethod.POST,
                Uri            = new Uri(ServiceUrl),
                Headers        = new Dictionary <string, string>(),
                BodyParameters = new Dictionary <string, string>(),
                UName          = "api",
                UPwd           = AuthorizationKey
            };

            var fromAddress = "{0} <{1}>".Args(DefaultFromName, DefaultFromAddress);

            if (msg.FROMAddress.IsNotNullOrWhiteSpace())
            {
                fromAddress = "{0} <{1}>".Args(msg.FROMName, msg.FROMAddress);
            }

            addParameter(request.BodyParameters, MAIL_PARAM_FROM, fromAddress);
            addParameter(request.BodyParameters, MAIL_PARAM_TO, "{0} <{1}>".Args(msg.TOName, msg.TOAddress));
            addParameter(request.BodyParameters, MAIL_PARAM_CC, msg.CC);
            addParameter(request.BodyParameters, MAIL_PARAM_BCC, msg.BCC);
            addParameter(request.BodyParameters, MAIL_PARAM_SUBJECT, msg.Subject);
            addParameter(request.BodyParameters, MAIL_PARAM_TEXT, msg.Body);
            addParameter(request.BodyParameters, MAIL_PARAM_HTML, msg.HTMLBody);

            if (TestMode)
            {
                request.BodyParameters.Add(API_PARAM_TESTMODE, "Yes");
            }
            try
            {
                var result = WebClient.GetJsonAsDynamic(request);
            }
            catch (Exception e)
            {
                if (m_FallbackSink != null)
                {
                    m_FallbackSink.SendMsg(msg);
                }
            }
        }
Beispiel #16
0
        private Transaction doTransfer(PaySession session, ITransactionContext context, Account from, Account to, Amount amount, string description = null, object extraData = null)
        {
            var id = Log(MessageType.Info, "doTransfer()", StringConsts.PAYPAL_PAYOUT_MESSAGE.Args(to, amount));

            try
            {
                var payPalSession     = session as PayPalSession;
                var actualAccountData = PaySystemHost.AccountToActualData(context, to);

                var request = new WebClient.RequestParams
                {
                    Caller          = this,
                    Uri             = new Uri(m_ApiUri + URI_PAYOUTS),
                    QueryParameters = new Dictionary <string, string>
                    {
                        { PRM_SYNC_MODE, m_SyncMode.AsString() }
                    },
                    Method      = HTTPRequestMethod.POST,
                    ContentType = ContentType.JSON,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, HDR_AUTHORIZATION_OAUTH.Args(payPalSession.AuthorizationToken.AccessToken) },
                    },
                    Body = getPayoutJSONBody(actualAccountData, amount, description)
                };

                var response = WebClient.GetJson(request);
                Log(MessageType.Info, "doTransfer()", response.ToJSON(), null, id);

                checkPayoutStatus(response, payPalSession);

                var transaction = createPayoutTransaction(session, context, response, to, amount, description);

                StatTransfer(amount);

                return(transaction);
            }
            catch (Exception ex)
            {
                StatTransferError();

                var message = StringConsts.PAYPAL_PAYOUT_ERROR.Args(to, amount, ex.ToMessageWithType());
                var error   = PayPalPaymentException.ComposeError(message, ex);
                Log(MessageType.Error, "doTransfer()", error.Message, ex, id);

                throw error;
            }
        }
Beispiel #17
0
        private Exception doValidateAddress(ShippoSession session, IShippingContext context, Address address, Guid logID)
        {
            var cred = (ShippoCredentials)session.User.Credentials;
            var body = getAddressBody(address);

            body["validate"] = true;

            // validate address request
            var request = new WebClient.RequestParams
            {
                Caller      = this,
                Uri         = new Uri(URI_API_BASE + URI_ADDRESS),
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = body.ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(request);
            var state    = response["object_state"].AsString(STATUS_INVALID);

            if (state.EqualsIgnoreCase(STATUS_VALID))
            {
                return(null);
            }

            Log(MessageType.Info, "doValidateAddress()", response.ToJSON(), relatedMessageID: logID);

            // if any error
            var         messages = response["messages"] as JSONDataArray;
            JSONDataMap message  = null;

            if (messages != null)
            {
                message = messages.FirstOrDefault() as JSONDataMap;
            }

            string details = message == null ?
                             UNKNOWN_TXT :
                             "{0} - {1}".Args(message["code"].AsString(UNKNOWN_TXT), message["text"].AsString(UNKNOWN_TXT));

            Log(MessageType.Error, "doValidateAddress()", response.ToJSON(), relatedMessageID: logID);

            return(new ShippingException(StringConsts.SHIPPO_VALIDATE_ADDRESS_INVALID_ERROR.Args(details)));
        }
        public void AddAuthHeader(ref WebClient.RequestParams request)
        {
            if (request.Headers != null)
            {
                if (request.Headers.ContainsKey(AUTHORIZATION_HEADER))
                {
                    return;
                }
            }
            else
            {
                request.Headers = new Dictionary <string, string>();
            }

            request.Headers.Add(AUTHORIZATION_HEADER, m_AuthHeader);
        }
Beispiel #19
0
        private Financial.Amount?doEstimateShippingCost(ShippoSession session, IShippingContext context, Shipment shipment, Guid logID)
        {
            var cred  = (ShippoCredentials)session.User.Credentials;
            var sbody = getShipmentBody(shipment);

            // get shipping request
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = sbody.ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(new Uri(URI_API_BASE + URI_SHIPMENTS), request);

            Log(MessageType.Info, "doEstimateShippingCost()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            var rates = response["rates_list"] as JSONDataArray;

            if (rates == null)
            {
                return(null);
            }

            foreach (JSONDataMap rate in rates)
            {
                var carrierID = rate["carrier_account"].AsString();
                if (carrierID.IsNotNullOrWhiteSpace() &&
                    string.Equals(carrierID, shipment.Carrier.Name, StringComparison.InvariantCultureIgnoreCase) &&
                    string.Equals(rate["servicelevel_token"].AsString(), shipment.Method.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(new Financial.Amount(rate["currency_local"].AsString(), rate["amount_local"].AsDecimal()));
                }

                // todo: where is Template?! minimize cost among all mathced rates?
            }

            return(null);
        }
Beispiel #20
0
        /// <summary>
        /// Overload of Capture method with Stripe-typed session parameter
        /// </summary>
        public Transaction Capture(StripeSession session, ITransactionContext context, ref Transaction charge, Amount?amount = null, string description = null, object extraData = null)
        {
            try
            {
                var bodyPrms = new Dictionary <string, string>();

                if (amount.HasValue)
                {
                    bodyPrms.Add(PRM_AMOUNT, ((int)((amount.Value.Value * 100))).ToString());
                }

                var prms = new WebClient.RequestParams()
                {
                    Uri            = new Uri(CAPTURE_URI.Args(charge.ProcessorToken)),
                    Caller         = this,
                    Method         = HTTPRequestMethod.POST,
                    UName          = session.SecretKey,
                    BodyParameters = bodyPrms
                };

                dynamic obj = WebClient.GetJsonAsDynamic(prms);

                StatCapture(charge, amount);
                return(charge);
            }
            catch (Exception ex)
            {
                StatCaptureError();

                var wex = ex as System.Net.WebException;
                if (wex != null)
                {
                    var response = wex.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        string errorMessage = this.GetType().Name + ".Capture(id: {0})".Args(charge.ID);
                        var    stripeEx     = PaymentStripeException.Compose(response, errorMessage, wex);
                        throw stripeEx;
                    }
                }

                throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CAPTURE_CAPTURED_PAYMENT_ERROR + this.GetType()
                                                 + " .Capture(session='{0}', charge='{1}')".Args(session, charge), ex);
            }
        }
Beispiel #21
0
        private Label doCreateLabel(ShippoSession session, IShippingContext context, Shipment shipment, Guid logID)
        {
            var cred = (ShippoCredentials)session.User.Credentials;

            // label request
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = getCreateLabelRequestBody(session, shipment).ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(new Uri(URI_API_BASE + URI_TRANSACTIONS), request);

            Log(MessageType.Info, "doCreateLabel()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            // get label bin data from URL in response
            string labelURL = response["label_url"].AsString().EscapeURIStringWithPlus();

            // get used rate, fill label's data
            var id             = response["object_id"].AsString();
            var trackingNumber = response["tracking_number"].AsString();
            var rate           = doGetRate(session, response["rate"].AsString(), logID);
            var amount         = rate != null ?
                                 new NFX.Financial.Amount(rate["currency"].AsString(), rate["amount"].AsDecimal()) :
                                 new NFX.Financial.Amount(string.Empty, 0);

            var label = new Label(id,
                                  labelURL,
                                  shipment.LabelFormat,
                                  trackingNumber,
                                  shipment.Carrier.Type,
                                  amount);

            StatCreateLabel();

            return(label);
        }
Beispiel #22
0
        private void refreshOAuthToken(PayPalConnectionParameters connectParameters)
        {
            try
            {
                Log(MessageType.Info, "refreshOAuthToken()", StringConsts.PAYPAL_REFRESH_TOKEN_MESSAGE);

                var user = connectParameters.User;

                var request = new WebClient.RequestParams
                {
                    Caller      = this,
                    Uri         = new Uri(m_ApiUri + URI_GET_OAUTH_TOKEN),
                    Method      = HTTPRequestMethod.POST,
                    ContentType = ContentType.FORM_URL_ENCODED,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, HDR_AUTHORIZATION_BASIC.Args(getBaseAuthString(user.Credentials)) }
                    },
                    BodyParameters = new Dictionary <string, string>
                    {
                        { PRM_GRANT_TYPE, PRM_CLIENT_CREDENTIALS }
                    }
                };

                var response = WebClient.GetJson(request);
                Log(MessageType.Info, "refreshOAuthToken()", response.ToJSON());

                var oauthToken = new PayPalOAuthToken(response, m_OAuthTokenExpirationMargin);
                var token      = new AuthenticationToken(PAYPAL_REALM, oauthToken);
                connectParameters.User = new User(user.Credentials, token, user.Name, user.Rights);

                Log(MessageType.Info, "refreshOAuthToken()", StringConsts.PAYPAL_TOKEN_REFRESHED_MESSAGE);
            }
            catch (Exception ex)
            {
                var message = StringConsts.PAYPAL_REFRESH_TOKEN_ERROR.Args(ex.ToMessageWithType());
                var error   = PayPalPaymentException.ComposeError(message, ex);
                Log(MessageType.Error, "refreshOAuthToken()", error.Message, ex);

                throw error;
            }
        }
Beispiel #23
0
        internal PayPalOAuthToken generateOAuthToken(PayPalCredentials credentials)
        {
            var logID = Log(MessageType.Info, "generateOAuthToken()", "Generate OAuth token");

            try
            {
                var request = new WebClient.RequestParams(this)
                {
                    Method      = HTTPRequestMethod.POST,
                    ContentType = ContentType.FORM_URL_ENCODED,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, credentials.AuthorizationHeader }
                    },
                    BodyParameters = new Dictionary <string, string>
                    {
                        { PRM_GRANT_TYPE, PRM_CLIENT_CREDENTIALS }
                    }
                };

                var response = WebClient.GetJson(URI_GenerateOAuthToken(), request);
                Log(MessageType.Trace, "generateOAuthToken()", response.ToJSON(), relatedMessageID: logID);
                Log(MessageType.Info, "generateOAuthToken()", "OAuth token generated", relatedMessageID: logID);
                return(new PayPalOAuthToken(
                           response["app_id"].AsString(),
                           response["expires_in"].AsInt(),
                           response["token_type"].AsString(),
                           response["access_token"].AsString(),
                           response["scope"].AsString(),
                           response["nonce"].AsString(),
                           m_OAuthExpirationMargin));
            }
            catch (Exception ex)
            {
                var error = composeError(StringConsts.PAYPAL_GENERATE_OAUTH_ERROR_MESSAGE.Args(ex.ToMessageWithType()), ex);
                Log(MessageType.Error, "generateOAuthToken()", error.Message, ex, relatedMessageID: logID);

                throw error;
            }
        }
Beispiel #24
0
        /// <summary>
        /// Deletes existing recipient in Stripe system.
        /// It is used to delete temporary recipient created to perform Transfer operation
        /// </summary>
        private void deleteRecipient(StripeSession stripeSession, string recipientID)
        {
            try
            {
                var prms = new WebClient.RequestParams()
                {
                    Uri    = new Uri(RECIPIENT_DELETE_URI.Args(recipientID)),
                    Caller = this,
                    UName  = stripeSession.SecretKey,
                    Method = HTTPRequestMethod.DELETE
                };

                dynamic obj = WebClient.GetJson(prms);

                return;
            }
            catch (Exception ex)
            {
                var wex = ex as System.Net.WebException;
                if (wex != null)
                {
                    var response = wex.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        string errorMessage = this.GetType().Name +
                                              ".deleteRecipient(recipientID: '{0}')".Args(recipientID);
                        PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
                        if (stripeEx != null)
                        {
                            throw stripeEx;
                        }
                    }
                }

                throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CREATE_RECIPIENT_ERROR + this.GetType()
                                                 + " .deleteRecipient(recipientID: '{0}')".Args(recipientID), ex);
            }
        }
Beispiel #25
0
        internal AzureOAuth2Token getAccessToken(AzureCredentials credentials)
        {
            var logID = Log(MessageType.Info, "getAccessToken()", "Get Access Token");

            try
            {
                var request = new WebClient.RequestParams(this)
                {
                    Method         = HTTPRequestMethod.POST,
                    ContentType    = ContentType.FORM_URL_ENCODED,
                    BodyParameters = new Dictionary <string, string>
                    {
                        { PRM_GRANT_TYPE, PRM_CLIENT_CREDENTIALS },
                        { PRM_RESOURCE, Uri.EscapeDataString(m_Resource) },
                        { PRM_CLIENT_ID, credentials.ClientID },
                        { PRM_CLIENT_SECRET, credentials.ClientSecret }
                    }
                };

                var response = WebClient.GetJson(URI_GetAccessToken(credentials.TenantID), request);
                Log(MessageType.Trace, "generateOAuthToken()", response.ToJSON(), relatedMessageID: logID);
                Log(MessageType.Info, "generateOAuthToken()", "OAuth token generated", relatedMessageID: logID);
                return(new AzureOAuth2Token(
                           response["token_type"].AsString(),
                           response["access_token"].AsString(),
                           response["resource"].AsString(),
                           response["expires_in"].AsInt(),
                           response["ext_expires_in"].AsInt(),
                           response["expires_on"].AsLong().FromSecondsSinceUnixEpochStart(),
                           response["not_before"].AsLong().FromSecondsSinceUnixEpochStart()));
            }
            catch (Exception error)
            {
                Log(MessageType.Error, "generateOAuthToken()", error.Message, error, relatedMessageID: logID);
                throw error;
            }
        }
Beispiel #26
0
        private payoutItemDetails cancelPayoutItem(string payoutItemID, PayPalOAuthToken authToken, Guid logID)
        {
            Log(MessageType.Info, "cancelPayoutIyem()", "Cancel payout item", relatedMessageID: logID);

            try
            {
                var request = new WebClient.RequestParams(this)
                {
                    Method      = HTTPRequestMethod.POST,
                    ContentType = ContentType.JSON,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, authToken.AuthorizationHeader }
                    }
                };

                var response = WebClient.GetJson(URI_CancelPayoutItem(payoutItemID), request);
                Log(MessageType.Trace, "cancelPayoutIyem()", "Payout Item", relatedMessageID: logID, parameters: response.ToJSON());
                var payoutItem = new payoutItemDetails(response);
                if (payoutItem.TransactionStatus == payoutTransactionStatus.RETURNED)
                {
                    Log(MessageType.Info, "cancelPayoutIyem()", "Payout item canceled", relatedMessageID: logID);
                }
                else
                {
                    Log(MessageType.Info, "cancelPayoutIyem()", "Payout item not canceled", relatedMessageID: logID);
                }

                return(payoutItem);
            }
            catch (Exception ex)
            {
                var error = composeError(StringConsts.PAYPAL_PAYOUT_ITEM_CANCEL_ERROR_MESSAGE.Args(ex.ToMessageWithType()), ex);
                Log(MessageType.Error, "cancelPayoutIyem()", error.Message, ex, relatedMessageID: logID);
                throw error;
            }
        }
Beispiel #27
0
        private JSONDynamicObject getResponse(BraintreeSession session, Uri uri, HTTPRequestMethod method, object body)
        {
            if (!session.IsValid)
            {
                throw new PaymentException("Braintree: " + StringConsts.PAYMENT_BRAINTREE_SESSION_INVALID.Args(this.GetType().Name + ".getResponse"));
            }

            var prms = new WebClient.RequestParams()
            {
                Caller      = this,
                Uri         = uri,
                Method      = HTTPRequestMethod.POST,
                AcceptType  = ContentType.JSON,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>()
                {
                    { HDR_AUTHORIZATION, getAuthHeader(session.User.Credentials) },
                    { HDR_X_API_VERSION, API_VERSION }
                },
                Body = body != null?body.ToJSON(JSONWritingOptions.Compact) : null
            };

            return(WebClient.GetJsonAsDynamic(prms));
        }
Beispiel #28
0
        /// <summary>
        /// MessageSink DoSendMsg implementation
        /// </summary>
        /// <param name="msg">Message</param>
        protected override void DoSendMsg(Message msg)
        {
            if (msg == null || msg.TOAddress.IsNullOrWhiteSpace()) return;

            var request = new WebClient.RequestParams()
            {
              Caller = this,
              Method = HTTPRequestMethod.POST,
              Uri = new Uri(ServiceUrl),
              Headers = new Dictionary<string, string>(),
              BodyParameters = new Dictionary<string, string>(),
              UName = "api",
              UPwd = AuthorizationKey
            };

            var fromAddress = "{0} <{1}>".Args(DefaultFromName, DefaultFromAddress);
            if (msg.FROMAddress.IsNotNullOrWhiteSpace())
            {
              fromAddress = "{0} <{1}>".Args(msg.FROMName, msg.FROMAddress);
            }

            addParameter(request.BodyParameters, MAIL_PARAM_FROM, fromAddress);
            addParameter(request.BodyParameters, MAIL_PARAM_TO, "{0} <{1}>".Args(msg.TOName, msg.TOAddress));
            addParameter(request.BodyParameters, MAIL_PARAM_CC, msg.CC);
            addParameter(request.BodyParameters, MAIL_PARAM_BCC, msg.BCC);
            addParameter(request.BodyParameters, MAIL_PARAM_SUBJECT, msg.Subject);
            addParameter(request.BodyParameters, MAIL_PARAM_TEXT, msg.Body);
            addParameter(request.BodyParameters, MAIL_PARAM_HTML, msg.HTMLBody);
            // todo: attachments

            if (TestMode)
              request.BodyParameters.Add(API_PARAM_TESTMODE, "Yes");

            WebClient.GetString(request);
        }
Beispiel #29
0
      /// <summary>
      /// Deletes existing recipient in Stripe system.
      /// It is used to delete temporary recipient created to perform Transfer operation
      /// </summary>
      private void deleteRecipient(StripeSession stripeSession, string recipientID)
      {
        try
        {
          var prms = new WebClient.RequestParams()
          {
            Uri = new Uri(RECIPIENT_DELETE_URI.Args(recipientID)),
            Caller = this,
            UName = stripeSession.SecretKey,
            Method = HTTPRequestMethod.DELETE
          };

          dynamic obj = WebClient.GetJson(prms);

          return;
        }
        catch (Exception ex)
        {
          var wex = ex as System.Net.WebException;
          if (wex != null)
          {
            var response = wex.Response as System.Net.HttpWebResponse;
            if (response != null)
            {
              string errorMessage = this.GetType().Name +
                        ".deleteRecipient(recipientID: '{0}')".Args(recipientID);
              PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
              if (stripeEx != null) throw stripeEx; 
            }
          }

          throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CREATE_RECIPIENT_ERROR + this.GetType()
            + " .deleteRecipient(recipientID: '{0}')".Args(recipientID), ex);
        }
      }
Beispiel #30
0
        public ITaxStructured DoCalc(
            TaxJarSession session,
            IAddress fromAddress,
            IAddress toAddress,
            Amount amount,
            Amount shipping)
        {
            if (fromAddress == null)
            {
                throw new TaxException(StringConsts.TAX_TAXJAR_TOADDRESS_ISNT_SUPPLIED_ERROR + this.GetType() + ".DoCalc");
            }

            if (toAddress == null)
            {
                throw new TaxException(StringConsts.TAX_TAXJAR_TOADDRESS_ISNT_SUPPLIED_ERROR + this.GetType() + ".DoCalc");
            }

            try
            {
                var bodyPrms = new Dictionary <string, string>()
                {
                    { PRM_AMOUNT, amount.Value.ToString() },
                    { PRM_SHIPPING, 0.ToString() }
                };

                bodyPrms.Add(PRM_FROM_COUNTRY, fromAddress.Country);
                bodyPrms.Add(PRM_FROM_STATE, fromAddress.Region);
                bodyPrms.Add(PRM_FROM_ZIP, fromAddress.PostalCode);

                bodyPrms.Add(PRM_TO_COUNTRY, toAddress.Country);
                bodyPrms.Add(PRM_TO_STATE, toAddress.Region);
                bodyPrms.Add(PRM_TO_ZIP, toAddress.PostalCode);

                var prms = new WebClient.RequestParams()
                {
                    Uri     = new Uri(CALC_URI),
                    Caller  = this,
                    Headers = new Dictionary <string, string>()
                    {
                        { AUTH_HEADER_KEY, AUTH_HEADER_VALUE_PATTERN.Args(session.ApiKey) }
                    },
                    Method         = HTTPRequestMethod.POST,
                    BodyParameters = bodyPrms
                };

                dynamic obj = WebClient.GetJsonAsDynamic(prms);

                var result = new TaxStructured();

                result.Total = (decimal)obj.Data["tax"]["amount_to_collect"];

                return(result);
            }
            catch (Exception ex)
            {
                var wex = ex as System.Net.WebException;

                if (wex != null)
                {
                    var response = wex.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        string errorMessage = this.GetType().Name +
                                              ".DoCalc(fromAddress: {0}, toAddress: {1}, amount: '{2}', shipping: '{3}')".Args(fromAddress, toAddress, amount, shipping);
                        var taxEx = TaxException.Compose(response, errorMessage, wex);
                        throw taxEx;
                    }
                }

                throw new TaxException(StringConsts.TAX_CALC_ERROR + this.GetType()
                                       + " .Calc(session='{0}', fromAddress='{1}', toAddress='{2}', amount='{3}', shipping='{4}')"
                                       .Args(session, fromAddress, toAddress, amount, shipping), ex);
            }
        }
Beispiel #31
0
        /// <summary>
        /// MessageSink DoSendMsg implementation
        /// </summary>
        /// <param name="msg">Message</param>
        protected override bool DoSendMsg(Message msg)
        {
            if (msg == null || msg.TOAddress.IsNullOrWhiteSpace())
            {
                return(false);
            }

            var addressees =
                msg.MessageAddress.All.Where(a => SupportedChannelNames.Any(n => n.EqualsOrdIgnoreCase(a.ChannelName)));

            var fa = msg.FROMAddress;
            var fn = msg.FROMName;

            if (fa.IsNullOrWhiteSpace())
            {
                fa = DefaultFromAddress;
            }
            if (fn.IsNullOrWhiteSpace())
            {
                fn = DefaultFromName;
            }

            var fromAddress = "{0} <{1}>".Args(fn, fa);

            var sent = false;

            foreach (var addressee in addressees)
            {
                var request = new WebClient.RequestParams(this)
                {
                    Method         = HTTPRequestMethod.POST,
                    BodyParameters = new Dictionary <string, string>(),
                    UserName       = "******",
                    Password       = AuthorizationKey
                };

                addParameter(request.BodyParameters, MAIL_PARAM_FROM, fromAddress);
                addParameter(request.BodyParameters, MAIL_PARAM_TO,
                             "{0} <{1}>".Args(addressee.Name, addressee.ChannelAddress));
                if (msg.CC.IsNotNullOrWhiteSpace())
                {
                    addParameter(request.BodyParameters, MAIL_PARAM_CC, msg.CC);
                }
                if (msg.BCC.IsNotNullOrWhiteSpace())
                {
                    addParameter(request.BodyParameters, MAIL_PARAM_BCC, msg.BCC);
                }
                if (msg.Subject.IsNotNullOrWhiteSpace())
                {
                    addParameter(request.BodyParameters, MAIL_PARAM_SUBJECT, msg.Subject);
                }
                if (msg.Body.IsNotNullOrWhiteSpace())
                {
                    addParameter(request.BodyParameters, MAIL_PARAM_TEXT, msg.Body);
                }
                if (msg.RichBody.IsNotNullOrWhiteSpace())
                {
                    addParameter(request.BodyParameters, MAIL_PARAM_HTML, msg.RichBody);
                }

                if (msg.Attachments != null)
                {
                    foreach (var attachment in msg.Attachments.Where(a => a.Content != null))
                    {
                        //TODO
                    }
                }

                try
                {
                    if (TestMode)
                    {
                        request.BodyParameters.Add(API_PARAM_TESTMODE, "yes");
                    }

                    WebClient.GetString(ServiceUrl, request);
                    sent = true;
                }
                catch (Exception error)
                {
                    var et = error.ToMessageWithType();
                    Log(MessageType.Error, "{0}.DoSendMsg(msg): {1}".Args(this.GetType().FullName, et), et);
                }
            }

            return(sent);
        }
Beispiel #32
0
          private Transaction doTransfer(PaySession session, ITransactionContext context, Account from, Account to, Amount amount, string description = null, object extraData = null)
          {     
              var id = Log(MessageType.Info, "doTransfer()", StringConsts.PAYPAL_PAYOUT_MESSAGE.Args(to, amount));

              try
              {
                  var payPalSession = session as PayPalSession;
                  var actualAccountData = PaySystemHost.AccountToActualData(context, to);

                  var request = new WebClient.RequestParams
                  {
                      Caller = this,
                      Uri = new Uri(m_ApiUri + URI_PAYOUTS),
                      QueryParameters = new Dictionary<string, string> 
                          { 
                              { PRM_SYNC_MODE, m_SyncMode.AsString() } 
                          },
                      Method = HTTPRequestMethod.POST,
                      ContentType = ContentType.JSON,
                      Headers = new Dictionary<string, string>
                          { 
                              { HDR_AUTHORIZATION, HDR_AUTHORIZATION_OAUTH.Args(payPalSession.AuthorizationToken.AccessToken) },
                          },
                      Body = getPayoutJSONBody(actualAccountData, amount, description)
                  };
                  
                  var response = WebClient.GetJson(request);
                  Log(MessageType.Info, "doTransfer()", response.ToJSON(), null, id);
                  checkPayoutStatus(response);

                  var transaction = createPayoutTransaction(session, context, response, to, amount, description);
                  
                  StatTransfer(amount);
                  
                  return transaction;
              }
              catch (Exception ex)
              {
                  StatTransferError();

                  var message = StringConsts.PAYPAL_PAYOUT_ERROR.Args(to, amount, ex.ToMessageWithType());
                  var error = PayPalPaymentException.ComposeError(message, ex);
                  Log(MessageType.Error, "doTransfer()", error.Message, ex, id);
                  
                  throw error;
              }
          }
Beispiel #33
0
          private void refreshOAuthToken(PayPalConnectionParameters connectParameters)
          {   
              try
              {
                  Log(MessageType.Info, "refreshOAuthToken()", StringConsts.PAYPAL_REFRESH_TOKEN_MESSAGE);

                  var user = connectParameters.User;
                  
                  var request = new WebClient.RequestParams
                  { 
                      Caller = this,
                      Uri = new Uri(m_ApiUri + URI_GET_OAUTH_TOKEN),
                      Method = HTTPRequestMethod.POST,
                      ContentType = ContentType.FORM_URL_ENCODED,
                      Headers = new Dictionary<string, string> 
                          { 
                              { HDR_AUTHORIZATION, HDR_AUTHORIZATION_BASIC.Args(getBaseAuthString(user.Credentials)) } 
                          },
                      BodyParameters = new Dictionary<string, string> 
                          { 
                              { PRM_GRANT_TYPE, PRM_CLIENT_CREDENTIALS } 
                          }
                  };
                  
                  var response = WebClient.GetJson(request);
                  Log(MessageType.Info, "refreshOAuthToken()", response.ToJSON());
                  
                  var oauthToken = new PayPalOAuthToken(response, m_OAuthTokenExpirationMargin);
                  var token = new AuthenticationToken(PAYPAL_REALM, oauthToken);
                  connectParameters.User = new User(user.Credentials, token, user.Name, user.Rights);

                  Log(MessageType.Info, "refreshOAuthToken()", StringConsts.PAYPAL_TOKEN_REFRESHED_MESSAGE);
              }
              catch (Exception ex)
              {   
                  var message = StringConsts.PAYPAL_REFRESH_TOKEN_ERROR.Args(ex.ToMessageWithType());
                  var error = PayPalPaymentException.ComposeError(message, ex);
                  Log(MessageType.Error, "refreshOAuthToken()", error.Message, ex);
                  
                  throw error;
              }
          } 
Beispiel #34
0
    public ITaxStructured DoCalc(
        TaxJarSession session,
        IAddress fromAddress, 
        IAddress toAddress, 
        Amount amount, 
        Amount shipping)
    {
      if (fromAddress == null)
        throw new TaxException(StringConsts.TAX_TAXJAR_TOADDRESS_ISNT_SUPPLIED_ERROR + this.GetType() + ".DoCalc");

      if (toAddress == null)
        throw new TaxException(StringConsts.TAX_TAXJAR_TOADDRESS_ISNT_SUPPLIED_ERROR + this.GetType() + ".DoCalc");

      try
      {
        var bodyPrms = new Dictionary<string, string>() { 
          {PRM_AMOUNT, amount.Value.ToString()},
          {PRM_SHIPPING, 0.ToString()}
        };

        bodyPrms.Add(PRM_FROM_COUNTRY, fromAddress.Country);
        bodyPrms.Add(PRM_FROM_STATE, fromAddress.Region);
        bodyPrms.Add(PRM_FROM_ZIP, fromAddress.PostalCode);

        bodyPrms.Add(PRM_TO_COUNTRY, toAddress.Country);
        bodyPrms.Add(PRM_TO_STATE, toAddress.Region);
        bodyPrms.Add(PRM_TO_ZIP, toAddress.PostalCode);

        var prms = new WebClient.RequestParams() {
          Uri = new Uri(CALC_URI),
          Caller = this,
          Headers = new Dictionary<string, string>() { { AUTH_HEADER_KEY, AUTH_HEADER_VALUE_PATTERN.Args(session.ApiKey) } },
          Method = HTTPRequestMethod.POST,
          BodyParameters = bodyPrms
        };

        dynamic obj = WebClient.GetJsonAsDynamic(prms);

        var result = new TaxStructured();

        result.Total = (decimal)obj.Data["tax"]["amount_to_collect"];

        return result;
      }
      catch (Exception ex)
      {
        var wex = ex as System.Net.WebException;

        if (wex != null)
        {
          var response = wex.Response as System.Net.HttpWebResponse;
          if (response != null)
          {
            string errorMessage = this.GetType().Name +
              ".DoCalc(fromAddress: {0}, toAddress: {1}, amount: '{2}', shipping: '{3}')".Args(fromAddress, toAddress, amount, shipping);
            var taxEx = TaxException.Compose(response, errorMessage, wex);
            throw taxEx;  
          }
        }

        throw new TaxException(StringConsts.TAX_CALC_ERROR + this.GetType()
          + " .Calc(session='{0}', fromAddress='{1}', toAddress='{2}', amount='{3}', shipping='{4}')"
            .Args(session, fromAddress, toAddress, amount, shipping), ex);
      }
    }
Beispiel #35
0
      /// <summary>
      /// Transfers funds to customerAccount from current stripe account 
      /// (which credentials is supplied in current session)
      /// </summary>
      private Transaction transfer(StripeSession stripeSession, ITransactionContext context, string recipientID, Account customerAccount, Amount amount, string description)
      {
        var actualAccountData = PaySystemHost.AccountToActualData(context, customerAccount);

        try
        {
          var prms = new WebClient.RequestParams()
          {
            Uri = new Uri(TRANSFER_URI),
            Caller = this,
            UName = stripeSession.SecretKey,
            Method = HTTPRequestMethod.POST,
            BodyParameters = new Dictionary<string, string>() 
            {
              {PRM_RECIPIENT, recipientID},
              {PRM_AMOUNT, ((int)((amount.Value * 100))).ToString()},
              {PRM_CURRENCY, amount.CurrencyISO.ToLower()},
              {PRM_DESCRIPTION, description}
            }
          };

          dynamic obj = WebClient.GetJson(prms);

          var created = ((long)obj.created).FromSecondsSinceUnixEpochStart();

          var taId = PaySystemHost.GenerateTransactionID(stripeSession, context, TransactionType.Transfer);

          var ta = new Transaction(taId, TransactionType.Transfer, this.Name, obj.id, Account.EmptyInstance, customerAccount, amount, created, description);

          StatTransfer(amount);

          return ta;
        }
        catch (Exception ex)
        {
          StatTransferError();

          var wex = ex as System.Net.WebException;
          if (wex == null)
          {
            var response = wex.Response as System.Net.HttpWebResponse;
            if (response != null)
            {
              string errorMessage = this.GetType().Name +
                        ".transfer(recipientID='{0}', customerAccount='{1}', amount='{2}')".Args(recipientID, actualAccountData, amount);
              PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
              if (stripeEx != null) throw stripeEx; 
            }
          }

          throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_TRANSFER_ERROR + this.GetType()
            + " .transfer(customerAccout='{0}')".Args(actualAccountData), ex);
        }
      }
Beispiel #36
0
      /// <summary>
      /// Overload of Refund method with Stripe-typed session parameter
      /// Developers, don't call this method directly. Call Transaction.Refund instead.
      /// </summary>
      public Transaction Refund(StripeSession session, ITransactionContext context, ref Transaction charge, Amount? amount = null, string description = null, object extraData = null)
      {
        var fromActualData = PaySystemHost.AccountToActualData(context, charge.From);

        var refundAmount = amount ?? charge.Amount;

        try
        {
          var bodyPrms = new Dictionary<string, string>() { 
            {PRM_AMOUNT, ((int)((refundAmount.Value * 100))).ToString()}
          };

          if (description.IsNotNullOrWhiteSpace())
            bodyPrms.Add(PRM_REASON, description);

          var prms = new WebClient.RequestParams()
          {
            Uri = new Uri(REFUND_URI.Args(charge.ProcessorToken)),
            Caller = this,
            UName = session.SecretKey,
            Method = HTTPRequestMethod.POST,
            BodyParameters = bodyPrms
          };

          dynamic obj = WebClient.GetJson(prms);

          dynamic lastRefund = ((NFX.Serialization.JSON.JSONDataArray)obj.refunds.data.Data).First();

          var created = ((long)obj.created).FromSecondsSinceUnixEpochStart();

          var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Refund);

          var refundTA = new Transaction(taId, TransactionType.Refund, this.Name,
            lastRefund["id"], Account.EmptyInstance, charge.From, refundAmount, created, description, canRefund: false);

          StatRefund(charge, amount);

          return refundTA;
        }
        catch (Exception ex)
        {
          StatRefundError();

          var wex = ex as System.Net.WebException;
          if (wex != null)
          {
            var response = wex.Response as System.Net.HttpWebResponse;
            if (response != null)
            {
              string errorMessage = this.GetType().Name +
                ".Refund(money: {0}, card: {1}, description: '{2}')"
                  .Args(charge.Amount, fromActualData.AccountNumber, description);
              PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
              if (stripeEx != null) throw stripeEx;
            }
          }

          throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CAPTURE_CAPTURED_PAYMENT_ERROR + this.GetType()
            + " .Refund(session='{0}', charge='{1}')".Args(session, charge), ex);
        }
      }
Beispiel #37
0
        /// <summary>
        /// Overload of Refund method with Stripe-typed session parameter
        /// Developers, don't call this method directly. Call Transaction.Refund instead.
        /// </summary>
        public Transaction Refund(StripeSession session, ITransactionContext context, ref Transaction charge, Amount?amount = null, string description = null, object extraData = null)
        {
            var fromActualData = PaySystemHost.AccountToActualData(context, charge.From);

            var refundAmount = amount ?? charge.Amount;

            try
            {
                var bodyPrms = new Dictionary <string, string>()
                {
                    { PRM_AMOUNT, ((int)((refundAmount.Value * 100))).ToString() }
                };

                if (description.IsNotNullOrWhiteSpace())
                {
                    bodyPrms.Add(PRM_REASON, description);
                }

                var prms = new WebClient.RequestParams()
                {
                    Uri            = new Uri(REFUND_URI.Args(charge.ProcessorToken)),
                    Caller         = this,
                    UName          = session.SecretKey,
                    Method         = HTTPRequestMethod.POST,
                    BodyParameters = bodyPrms
                };

                dynamic obj = WebClient.GetJson(prms);

                dynamic lastRefund = ((NFX.Serialization.JSON.JSONDataArray)obj.refunds.Data).First();

                var created = ((long)obj.created).FromSecondsSinceUnixEpochStart();

                var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Refund);

                var refundTA = new Transaction(taId, TransactionType.Refund, Account.EmptyInstance, charge.From, this.Name,
                                               lastRefund["id"], refundAmount, created, description,
                                               isCaptured: true, canRefund: false);

                StatRefund(charge, amount);

                return(refundTA);
            }
            catch (Exception ex)
            {
                var wex = ex as System.Net.WebException;
                if (wex != null)
                {
                    var response = wex.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        string errorMessage = this.GetType().Name +
                                              ".Refund(money: {0}, card: {1}, description: '{2}')"
                                              .Args(charge.Amount, fromActualData.AccountNumber, description);
                        PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
                        if (stripeEx != null)
                        {
                            throw stripeEx;
                        }
                    }
                }

                StatRefundError();

                throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CAPTURE_CAPTURED_PAYMENT_ERROR + this.GetType()
                                                 + " .Refund(session='{0}', charge='{1}')".Args(session, charge), ex);
            }
        }
Beispiel #38
0
        private Label doCreateLabel(ShippoSession session, IShippingContext context, Shipment shipment, object labelID, Guid logID)
        {
            var cred = (ShippoCredentials)session.User.Credentials;

            // label request
            var request = new WebClient.RequestParams
            {
              Caller = this,
              Uri = new Uri(URI_API_BASE + URI_TRANSACTIONS),
              Method = HTTPRequestMethod.POST,
              ContentType = ContentType.JSON,
              Headers = new Dictionary<string, string>
            {
              { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
            },
              Body = getCreateLabelRequestBody(session, shipment, labelID)
            };

            var response = WebClient.GetJson(request);

            Log(MessageType.Info, "doCreateLabel()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            // get label bin data from URL in response
            string labelURL = response["label_url"].AsString().EscapeURIStringWithPlus();
            string contentType;
            var data = WebClient.GetData(new Uri(labelURL), this, out contentType);

            // get used rate, fill label's data
            var id = response["object_id"];
            var trackingNumber = response["tracking_number"].AsString();
            var rate = getRate(session, response["rate"].AsString(), logID);
            var carrier = rate != null ?
                      CARRIERS.First(c => c.Value.EqualsIgnoreCase(rate["provider"].AsString())).Key :
                      Carrier.Unknown;
            var amount = rate != null ?
                     new NFX.Financial.Amount(rate["currency"].AsString(), rate["amount"].AsDecimal()) :
                     new NFX.Financial.Amount(string.Empty, 0);

            var label = new Label(id,
                              labelURL,
                              data,
                              shipment.LabelFormat,
                              trackingNumber,
                              carrier,
                              amount);

            if (labelID == null) StatCreateLabel();
            else StatCreateReturnLabel();

            return label;
        }
Beispiel #39
0
      /// <summary>
      /// Creates new recipient in Stripe system.
      /// Is used as a temporary entity to substitute recipient parameter in Transfer operation then deleted
      /// </summary>
      private string createRecipient(StripeSession stripeSession, ITransactionContext context, Account recipientAccount, string description)
      {
        var recipientActualAccountData = PaySystemHost.AccountToActualData(context, recipientAccount);

        try
        {
          var bodyPrms = new Dictionary<string, string>() 
          {
            {PRM_NAME, recipientActualAccountData.AccountTitle},
            {PRM_TYPE, recipientActualAccountData.AccountType == AccountType.Corporation ? "corporation" : "individual"},
            {PRM_EMAIL, recipientActualAccountData.BillingEmail}
          };

          fillBodyParametersFromAccount(bodyPrms, recipientActualAccountData);

          var prms = new WebClient.RequestParams()
          {
            Uri = new Uri(RECIPIENT_URI),
            Caller = this,
            UName = stripeSession.SecretKey,
            Method = HTTPRequestMethod.POST,
            BodyParameters = bodyPrms
          };

          dynamic obj = WebClient.GetJson(prms);

          return obj.id;
        }
        catch (Exception ex)
        {
          var wex = ex as System.Net.WebException;
          if (wex != null)
          {
            var response = wex.Response as System.Net.HttpWebResponse;
            if (response != null)
            {
              string errorMessage = this.GetType().Name +
                ".createRecipient(customerAccout='{0}')".Args(recipientActualAccountData);
              PaymentStripeException stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
              if (stripeEx != null) throw stripeEx;
            }
          }

          throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CREATE_RECIPIENT_ERROR + this.GetType()
            + " .Refund(customerAccout='{0}')".Args(recipientActualAccountData), ex);
        }

        throw new NotImplementedException();
      }
Beispiel #40
0
        private JSONDataMap getRate(ShippoSession session, string rateID, Guid logID)
        {
            try
            {
              var cred = (ShippoCredentials)session.User.Credentials;

              var request = new WebClient.RequestParams
              {
            Caller = this,
            Uri = new Uri((URI_API_BASE + URI_RATES).Args(rateID)),
            Method = HTTPRequestMethod.GET,
            ContentType = ContentType.JSON,
            Headers = new Dictionary<string, string>
              {
                { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
              }
              };

              return WebClient.GetJson(request);
            }
            catch (Exception ex)
            {
              var error = ShippingException.ComposeError(ex.Message, ex);
              Log(MessageType.Error, "getRate()", StringConsts.SHIPPO_CREATE_LABEL_ERROR, error, relatedMessageID: logID);
              return null;
            }
        }
Beispiel #41
0
        private XDocument getResponse(BraintreeSession session, Uri uri, XDocument body = null, HTTPRequestMethod method = HTTPRequestMethod.POST)
        {
            if (!session.IsValid)
            throw new PaymentException("Braintree: " + StringConsts.PAYMENT_BRAINTREE_SESSION_INVALID.Args(this.GetType().Name + ".getResponse"));

              var prms = new WebClient.RequestParams()
              {
            Caller = this,
            Uri = uri,
            Method = method,
            AcceptType = ContentType.XML_APP,
            ContentType = ContentType.XML_APP,
            Headers = new Dictionary<string, string>()
            {
              { HDR_AUTHORIZATION, getAuthHeader(session.User.Credentials) },
              { HDR_X_API_VERSION, API_VERSION }
            },
            Body = body != null ? new XDeclaration("1.0", "UTF-8", null).ToString() + body.ToString(SaveOptions.DisableFormatting) : null
              };

              try {
            return WebClient.GetXML(prms);
              }
              catch (System.Net.WebException ex)
              {
            StatChargeError();
            var resp = (System.Net.HttpWebResponse)ex.Response;

            if (resp != null && resp.StatusCode == (System.Net.HttpStatusCode)422)
            {
              using (var sr = new StreamReader(resp.GetResponseStream()))
              {
            var respStr = sr.ReadToEnd();
            var response = respStr.IsNotNullOrWhiteSpace() ? XDocument.Parse(respStr) : null;
            if (response != null)
            {
              var apiErrorResponse = response.Element("api-error-response");
              throw new PaymentException(apiErrorResponse.Element("message").Value, ex);
            }
              }
            }
            throw;
              }
              catch
              {
            throw;
              }
        }
Beispiel #42
0
        private void cancelUnclaimedPayout(string itemID, PayPalSession payPalSession)
        {
            try
            {
                var request = new WebClient.RequestParams
                {
                    Caller = this,
                    Uri = new Uri(m_ApiUri + URI_CANCEL_UNCLAIMED_PAYOUT.Args(itemID)),
                    Method = HTTPRequestMethod.POST,
                    ContentType = ContentType.JSON,
                    Headers = new Dictionary<string, string>
                        {
                            { HDR_AUTHORIZATION, HDR_AUTHORIZATION_OAUTH.Args(payPalSession.AuthorizationToken.AccessToken) },
                        }
                };

                var response = WebClient.GetJson(request);
                Log(MessageType.Info, "cancelUnclaimedPayout()", response.ToJSON());
            }
            catch (Exception ex)
            {
                var message = StringConsts.PAYPAL_PAYOUT_CANCEL_ERROR.Args(ex.ToMessageWithType());
                var error = PayPalPaymentException.ComposeError(message, ex);
                Log(MessageType.Error, "cancelUnclaimedPayout()", error.Message, ex);

                throw error;
            }
        }
Beispiel #43
0
      /// <summary>
      /// Overload of Capture method with Stripe-typed session parameter
      /// </summary>
      public void Capture(StripeSession session, ITransactionContext context, ref Transaction charge, Amount? amount = null, string description = null, object extraData = null)
      {
        try
        {
          var bodyPrms = new Dictionary<string, string>();

          if (amount.HasValue)
          {
            bodyPrms.Add(PRM_AMOUNT, ((int)((amount.Value.Value * 100))).ToString());
          }

          var prms = new WebClient.RequestParams()
          {
            Uri = new Uri(CAPTURE_URI.Args(charge.ProcessorToken)),
            Caller = this,
            Method = HTTPRequestMethod.POST,
            UName = session.SecretKey,
            BodyParameters = bodyPrms
          };

          dynamic obj = WebClient.GetJson(prms);

          StatCapture(charge, amount);
        }
        catch (Exception ex)
        {
          StatCaptureError();

          var wex = ex as System.Net.WebException;
          if (wex != null)
          {
            var response = wex.Response as System.Net.HttpWebResponse;
            if (response != null)
            {
              string errorMessage = this.GetType().Name + ".Capture(id: {0})".Args(charge.ID);
              var stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
              throw stripeEx;
            }
          }

          throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CAPTURE_CAPTURED_PAYMENT_ERROR + this.GetType()
            + " .Capture(session='{0}', charge='{1}')".Args(session, charge), ex);
        }
      }
Beispiel #44
0
      /// <summary>
      /// Overload of Charge method with Stripe-typed session parameter
      /// </summary>
      public Transaction Charge(StripeSession session, ITransactionContext context, Account from, Account to, Amount amount, bool capture = true, string description = null, object extraData = null)
      {
        var fromActualData = PaySystemHost.AccountToActualData(context, from);

        try
        {
          var bodyPrms = new Dictionary<string, string>() { 
            {PRM_AMOUNT, ((int)((amount.Value * 100))).ToString()},
            {PRM_CURRENCY, amount.CurrencyISO.ToString().ToLower()},
            {PRM_DESCRIPTION, description},
            {PRM_CAPTURE, capture.ToString()}
          };

          fillBodyParametersFromAccount(bodyPrms, fromActualData);

          var prms = new WebClient.RequestParams() {
            Uri = new Uri(CHARGE_URI),
            Caller = this,
            UName = session.SecretKey,
            Method = HTTPRequestMethod.POST,
            BodyParameters = bodyPrms
          };

          dynamic obj = WebClient.GetJson(prms);

          var created = ((long)obj.created).FromSecondsSinceUnixEpochStart();

          var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Charge);

          var ta = new Transaction(taId, TransactionType.Charge, this.Name, obj.id, from, to, amount, created, description);

          StatCharge(amount);

          return ta;
        }
        catch (Exception ex)
        {
          StatChargeError();

          var wex = ex as System.Net.WebException;

          if (wex != null)
          {
            var response = wex.Response as System.Net.HttpWebResponse;
            if (response != null)
            {
              string errorMessage = this.GetType().Name +
                ".Charge(money: {0}, card: {1}, amount: '{2}')".Args(amount.Value, fromActualData.AccountNumber, amount);
              var stripeEx = PaymentStripeException.Compose(response, errorMessage, wex);
              throw stripeEx;  
            }
          }

          throw new PaymentStripeException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + this.GetType()
            + " .Capture(session='{0}', card='{1}', amount='{2}')".Args(session, from, amount), ex);
        }
      }