public object GenerateClientToken(BraintreeSession session) { dynamic response = getResponse(session, URI_ClientToken(session.MerchantID), HTTPRequestMethod.POST, new { client_token = new { version = "2" } }); return(response.clientToken.value); }
public Transaction Capture(BraintreeSession session, ITransactionContext context, ref Transaction charge, Amount?amount = default(Amount?), string description = null, object extraData = null) { if (!charge.ProcessorName.EqualsIgnoreCase(Name)) { throw new PaymentException(StringConsts.PAYMENT_INVALID_PAYSYSTEM_ERROR + GetType().Name + ".Capture(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, amount.Value)); } if (amount.HasValue && !charge.Amount.CurrencyISO.EqualsOrdIgnoreCase(amount.Value.CurrencyISO)) { throw new PaymentException(StringConsts.PAYMENT_CAPTURE_CURRENCY_MUST_MATCH_CHARGE_ERROR + GetType().Name + ".Capture(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, amount.Value)); } var orderContex = context as IOrderTransactionContext; try { var splitTran = charge.ProcessorToken.AsString().Split(':'); var transaction = new XElement("transaction"); if (amount.HasValue) { transaction.Add(new XElement("amount", amount.Value.Value)); } if (orderContex != null) { transaction.Add(new XElement("order-id", orderContex.OrderId)); } var response = getResponse(session, URI_SubmitForSettlement(session.MerchantID, splitTran[2]), new XDocument(transaction), HTTPRequestMethod.PUT); transaction = response.Root; var transactionID = transaction.Element("id").Value; var created = transaction.Element("created-at").Value.AsDateTime(); var customerID = transaction.Element("customer").Element("id").Value; var token = transaction.Element("credit-card").Element("token").Value; var amountCaptured = new Amount(charge.Amount.CurrencyISO, transaction.Element("amount").Value.AsDecimal()); charge = Transaction.Charge(charge.ID, Name, "{0}:{1}:{2}".Args(customerID, token, transactionID), charge.From, charge.To, charge.Amount, created, description, amountCaptured); StatCapture(charge, amount); return(charge); } catch (Exception ex) { StatChargeError(); if (ex is PaymentException) { throw ex; } throw new PaymentException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + GetType().Name + " .Capture(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, amount), ex); } }
private bool doRefund(BraintreeSession session, Transaction charge, decimal?amount = null, string description = null, object extraData = null) { if (!charge.Processor.EqualsIgnoreCase(Name)) { throw new PaymentException(StringConsts.PAYMENT_INVALID_PAYSYSTEM_ERROR + GetType().Name + ".Refund(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, charge.Amount)); } if (!charge.CanRefund) { return(false); } try { var useVoid = false; var transaction = new XElement("transaction"); if (amount.HasValue) { transaction.Add(new XElement("amount", amount.Value)); } else { var resp = getResponse(session, URI_Find(session.MerchantID, charge.Token.AsString()), method: HTTPRequestMethod.GET); var tran = resp.Root; var status = tran.Element("status").Value; useVoid = status.EqualsOrdIgnoreCase("submitted_for_settlement"); } var response = useVoid ? getResponse(session, URI_Void(session.MerchantID, charge.Token.AsString()), new XDocument(transaction), HTTPRequestMethod.PUT) : getResponse(session, URI_Refund(session.MerchantID, charge.Token.AsString()), new XDocument(transaction), HTTPRequestMethod.POST); transaction = response.Root; var transactionID = transaction.Element("id").Value; var updatedAt = transaction.Element("updated-at").Value.AsDateTime(); var amountRefunded = transaction.Element("amount").Value.AsDecimal(); charge.__Apply(Transaction.Operation.Refund(charge.LeftToRefund.Value >= amountRefunded ? TransactionStatus.Refunded : TransactionStatus.Success, updatedAt, token: transactionID, description: description, amount: amountRefunded, extraData: extraData)); StatRefund(charge, amountRefunded); return(true); } catch (Exception ex) { StatRefundError(); if (ex is PaymentException) { throw ex; } throw new PaymentException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + GetType().Name + ".Refund(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, amount), ex); } }
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; } }
private bool doCapture(BraintreeSession session, Transaction charge, decimal?amount = null, string description = null, object extraData = null) { if (!charge.Processor.EqualsIgnoreCase(Name)) { throw new PaymentException(StringConsts.PAYMENT_INVALID_PAYSYSTEM_ERROR + GetType().Name + ".Capture(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, charge.Amount)); } if (!charge.CanCapture) { return(false); } try { var transaction = new XElement("transaction"); if (amount.HasValue) { transaction.Add(new XElement("amount", amount.Value)); } var response = getResponse(session, URI_SubmitForSettlement(session.MerchantID, charge.Token.AsString()), new XDocument(transaction), HTTPRequestMethod.PUT); transaction = response.Root; var transactionID = transaction.Element("id").Value; var updatedAt = transaction.Element("updated-at").Value.AsDateTime(); var amountCaptured = transaction.Element("amount").Value.AsDecimal(); charge.__Apply(Transaction.Operation.Capture(TransactionStatus.Success, updatedAt, token: transactionID, description: description, amount: amountCaptured, extraData: extraData)); StatCapture(charge, amountCaptured); return(true); } catch (Exception ex) { StatCaptureError(); if (ex is PaymentException) { throw ex; } throw new PaymentException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + GetType().Name + ".Capture(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, amount), ex); } }
private bool doVoid(BraintreeSession session, Transaction charge, string description = null, object extraData = null) { if (!charge.Processor.EqualsIgnoreCase(Name)) { throw new PaymentException(StringConsts.PAYMENT_INVALID_PAYSYSTEM_ERROR + GetType().Name + ".Void(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, charge.Amount)); } if (!charge.CanVoid) { return(false); } try { var response = getResponse(session, URI_Void(session.MerchantID, charge.Token.AsString()), method: HTTPRequestMethod.PUT); var transaction = response.Root; var transactionID = transaction.Element("id").Value; var updatedAt = transaction.Element("updated-at").Value.AsDateTime(); var amountVoided = transaction.Element("amount").Value.AsDecimal(); charge.__Apply(Transaction.Operation.Void(TransactionStatus.Refunded, updatedAt, token: transactionID, description: description, extraData: extraData)); StatVoid(charge); return(true); } catch (Exception ex) { StatVoidError(); if (ex is PaymentException) { throw ex; } throw new PaymentException(StringConsts.PAYMENT_CANNOT_VOID_ERROR + GetType().Name + ".Void(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, charge.Amount), ex); } }
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)); }
private Transaction doCharge(BraintreeSession session, Account from, Account to, Amount amount, bool capture = true, string description = null, object extraData = null) { var fromActualData = session.FetchAccountData(from); var toActualData = session.FetchAccountData(to); try { var transaction = new XElement("transaction", new XElement("type", "sale"), new XElement("amount", amount.Value), new XElement(fromActualData.IsWebTerminal ? "payment-method-nonce" : "payment-method-token", fromActualData.AccountID)); if (toActualData != null) { transaction.Add(new XElement("order-id", "{0}:{1}:{2}".Args(toActualData.Identity, toActualData.IdentityID, toActualData.AccountID))); } if (fromActualData.IsWebTerminal) { if (fromActualData.IsNew) { transaction.Add(new XElement("customer", new XElement("id", fromActualData.IdentityID))); } else { try { getResponse(session, URI_Customer(session.MerchantID, fromActualData.IdentityID.ToString()), method: HTTPRequestMethod.GET); transaction.Add(new XElement("customer-id", fromActualData.IdentityID)); } catch { transaction.Add(new XElement("customer", new XElement("id", fromActualData.IdentityID))); } } } if (fromActualData.IsWebTerminal) { var billing = new XElement("billing"); if (fromActualData.FirstName.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("first-name", fromActualData.FirstName)); } if (fromActualData.LastName.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("last-name", fromActualData.LastName)); } if (fromActualData.BillingAddress.Address1.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("street-address", fromActualData.BillingAddress.Address1)); } if (fromActualData.BillingAddress.Address2.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("extended-address", fromActualData.BillingAddress.Address2)); } if (fromActualData.BillingAddress.City.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("locality", fromActualData.BillingAddress.City)); } if (fromActualData.BillingAddress.Country.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("country-code-alpha3", fromActualData.BillingAddress.Country)); } if (fromActualData.BillingAddress.Region.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("region", fromActualData.BillingAddress.Region)); } if (fromActualData.BillingAddress.PostalCode.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("postal-code", fromActualData.BillingAddress.PostalCode)); } if (fromActualData.BillingAddress.Company.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("company", fromActualData.BillingAddress.Company)); } transaction.Add(billing); } var descriptorName = buildDescriptor(toActualData.IssuerName, description); if (descriptorName.IsNotNullOrWhiteSpace()) { var descriptor = new XElement("descriptor"); descriptor.Add(new XElement("name", descriptorName)); if (toActualData.IssuerUri.IsNotNullOrWhiteSpace()) { descriptor.Add(new XElement("url", toActualData.IssuerUri.TakeFirstChars(13))); } if (toActualData.IssuerPhone.IsNotNullOrWhiteSpace()) { descriptor.Add(new XElement("phone", toActualData.IssuerPhone)); } transaction.Add(descriptor); } var options = new XElement("options", new XElement("submit-for-settlement", capture)); if (fromActualData.IsWebTerminal) { options.Add(new XElement("store-in-vault-on-success", true)); } transaction.Add(options); var response = getResponse(session, URI_Transactions(session.MerchantID), new XDocument(transaction)); transaction = response.Root; var transactionID = transaction.Element("id").Value; var status = transaction.Element("status").Value; var captured = status.EqualsOrdIgnoreCase("submitted_for_settlement"); var createdAt = transaction.Element("created-at").Value.AsDateTime(); var creditCard = transaction.Element("credit-card"); var token = creditCard.Element("token").Value; var cardBin = creditCard.Element("bin").Value; var cardLast4 = creditCard.Element("last-4").Value; var cardType = creditCard.Element("card-type").Value; var cardHolder = creditCard.Element("cardholder-name").Value; var cardExpMonth = creditCard.Element("expiration-month").Value.AsNullableInt(); var cardExpYear = creditCard.Element("expiration-year").Value.AsNullableInt(); var cardExpDate = cardExpMonth.HasValue && cardExpYear.HasValue ? new DateTime(cardExpYear.Value, cardExpMonth.Value, 1) : (DateTime?)null; var cardMaskedName = "{2}{0}..{1}".Args(cardType, cardLast4, cardExpMonth.HasValue && cardExpYear.HasValue ? "{0}/{1} ".Args(cardExpMonth, cardExpYear) : string.Empty); var amountAuth = transaction.Element("amount").Value.AsDecimal(); var taId = session.GenerateTransactionID(TransactionType.Charge); var ta = new Transaction(taId, TransactionType.Charge, TransactionStatus.Success, from, to, Name, transactionID, createdAt, new Amount(amount.CurrencyISO, amountAuth), description: description, extraData: extraData); if (captured) { ta.__Apply(Transaction.Operation.Capture(TransactionStatus.Success, createdAt, token: transactionID, description: description, amount: amountAuth, extraData: extraData)); } session.StoreAccountData(new ActualAccountData(fromActualData.Account) { IdentityID = fromActualData.IdentityID, AccountID = token, AccountType = fromActualData.AccountType, CardHolder = cardHolder, CardMaskedName = cardMaskedName, CardExpirationDate = cardExpDate, FirstName = fromActualData.FirstName, MiddleName = fromActualData.MiddleName, LastName = fromActualData.LastName, Phone = fromActualData.Phone, EMail = fromActualData.EMail, BillingAddress = fromActualData.BillingAddress, IsNew = fromActualData.IsNew, IsWebTerminal = false, IssuerID = fromActualData.IssuerID, IssuerName = fromActualData.IssuerName, IssuerPhone = fromActualData.IssuerPhone, IssuerEMail = fromActualData.IssuerEMail, IssuerUri = fromActualData.IssuerUri, HadSuccessfullTransactions = true, // TODO: useless fields ShippingAddress = fromActualData.ShippingAddress, CardVC = fromActualData.CardVC, RoutingNumber = fromActualData.RoutingNumber, }); StatCharge(amount); if (capture) { StatCapture(ta, amount.Value); } return(ta); } catch (Exception ex) { StatChargeError(); if (ex is PaymentException) { throw ex; } throw new PaymentException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + GetType().Name + ".Charge(session='{0}', card='{1}', amount='{2}')".Args(session, from, amount), ex); } }
private object doGenerateClientToken(BraintreeSession session) { var response = getResponse(session, URI_ClientToken(session.MerchantID), new XDocument(new XElement("client-token", new XElement("version", 2)))); return(response.Element("client-token").Element("value").Value); }
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; } }
public Transaction Refund(BraintreeSession session, ITransactionContext context, ref Transaction charge, Amount? amount = default(Amount?), string description = null, object extraData = null) { if (!charge.ProcessorName.EqualsIgnoreCase(Name)) throw new PaymentException(StringConsts.PAYMENT_INVALID_PAYSYSTEM_ERROR + GetType().Name + ".Refund(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, amount.Value)); if (amount.HasValue && !charge.Amount.CurrencyISO.EqualsOrdIgnoreCase(amount.Value.CurrencyISO)) throw new PaymentException(StringConsts.PAYMENT_REFUND_CURRENCY_MUST_MATCH_CHARGE_ERROR + GetType().Name + ".Refund(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, amount.Value)); var orderContex = context as IOrderTransactionContext; try { var splitTran = charge.ProcessorToken.AsString().Split(':'); if (charge.AmountCaptured.Value != 0m) throw new NotImplementedException(); var response = getResponse(session, URI_Void(session.MerchantID, splitTran[2]), method: HTTPRequestMethod.PUT); var transaction = response.Root; var transactionID = transaction.Element("id").Value; var created = transaction.Element("created-at").Value.AsDateTime(); var customerID = transaction.Element("customer").Element("id").Value; var token = transaction.Element("credit-card").Element("token").Value; var amountRefunded = new Amount(charge.Amount.CurrencyISO, transaction.Element("amount").Value.AsDecimal()); charge = Transaction.Refund(charge.ID, Name, "{0}:{1}:{2}".Args(customerID, token, transactionID), charge.From, charge.To, charge.Amount, created, description, amountRefunded, charge.ID); StatRefund(charge, charge.AmountCaptured); return charge; } catch (Exception ex) { StatRefundError(); if (ex is PaymentException) throw ex; throw new PaymentException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + GetType().Name + " .Refund(session='{0}', charge='{1}', amount='{2}')".Args(session, charge, amount), ex); } }
public object GenerateClientToken(BraintreeSession session) { var response = getResponse(session, URI_ClientToken(session.MerchantID), new XDocument(new XElement("client-token", new XElement("version", 2)))); return response.Element("client-token").Element("value").Value; }
public Transaction Charge(BraintreeSession session, ITransactionContext context, Account from, Account to, Amount amount, bool capture = true, string description = null, object extraData = null) { var orderContex = context as IOrderTransactionContext; var fromActualData = PaySystemHost.AccountToActualData(context, from); try { var isWeb = fromActualData.Account.IsWebTerminalToken; var transaction = new XElement("transaction", new XElement("type", "sale"), new XElement("amount", amount.Value), new XElement(isWeb ? "payment-method-nonce" : "payment-method-token", fromActualData.Account.AccountID)); if (orderContex != null) { transaction.Add(new XElement("order-id", orderContex.OrderId)); if (isWeb) { if (orderContex.IsNewCustomer) transaction.Add(new XElement("customer", new XElement("id", orderContex.CustomerId))); else try { getResponse(session, URI_Customer(session.MerchantID, orderContex.CustomerId.AsString()), method: HTTPRequestMethod.GET); transaction.Add(new XElement("customer-id", orderContex.CustomerId)); } catch { transaction.Add(new XElement("customer", new XElement("id", orderContex.CustomerId))); } } } if (isWeb) { var billing = new XElement("billing"); if (fromActualData.FirstName.IsNotNullOrWhiteSpace()) billing.Add(new XElement("first-name", fromActualData.FirstName)); if (fromActualData.LastName.IsNotNullOrWhiteSpace()) billing.Add(new XElement("last-name", fromActualData.LastName)); if (fromActualData.BillingAddress.Address1.IsNotNullOrWhiteSpace()) billing.Add(new XElement("street-address", fromActualData.BillingAddress.Address1)); if (fromActualData.BillingAddress.Address2.IsNotNullOrWhiteSpace()) billing.Add(new XElement("extended-address", fromActualData.BillingAddress.Address2)); if (fromActualData.BillingAddress.City.IsNotNullOrWhiteSpace()) billing.Add(new XElement("locality", fromActualData.BillingAddress.City)); if (fromActualData.BillingAddress.Country.IsNotNullOrWhiteSpace()) billing.Add(new XElement("country-code-alpha3", fromActualData.BillingAddress.Country)); if (fromActualData.BillingAddress.Region.IsNotNullOrWhiteSpace()) billing.Add(new XElement("region", fromActualData.BillingAddress.Region)); if (fromActualData.BillingAddress.PostalCode.IsNotNullOrWhiteSpace()) billing.Add(new XElement("postal-code", fromActualData.BillingAddress.PostalCode)); if (fromActualData.BillingAddress.Company.IsNotNullOrWhiteSpace()) billing.Add(new XElement("company", fromActualData.BillingAddress.Company)); transaction.Add(billing); } var options = new XElement("options", new XElement("submit-for-settlement", capture)); if (orderContex != null && isWeb) options.Add(new XElement("store-in-vault-on-success", true)); transaction.Add(options); var response = getResponse(session, URI_Transactions(session.MerchantID), new XDocument(transaction)); transaction = response.Root; var transactionID = transaction.Element("id").Value; var status = transaction.Element("status").Value; var captured = status.EqualsOrdIgnoreCase("submitted_for_settlement"); var created = transaction.Element("created-at").Value.AsDateTime(); var customerID = transaction.Element("customer").Element("id").Value; var token = transaction.Element("credit-card").Element("token").Value; var amountAuth = new Amount(amount.CurrencyISO, transaction.Element("amount").Value.AsDecimal()); var amountCaptured = captured ? (Amount?)amountAuth : null; var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Charge); var ta = Transaction.Charge(taId, Name, "{0}:{1}:{2}".Args(customerID, token, transactionID), from, to, amountAuth, created, description, amountCaptured: amountCaptured); StatCharge(amount); return ta; } catch (Exception ex) { StatChargeError(); if (ex is PaymentException) throw ex; throw new PaymentException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + GetType().Name + " .Charge(session='{0}', card='{1}', amount='{2}')".Args(session, from, amount), ex); } }
public Transaction Charge(BraintreeSession session, ITransactionContext context, Account from, Account to, Amount amount, bool capture = true, string description = null, object extraData = null) { var orderContex = context as IOrderTransactionContext; var fromActualData = PaySystemHost.AccountToActualData(context, from); try { var isWeb = fromActualData.Account.IsWebTerminalToken; var request = new JSONDataMap(); var transaction = (JSONDataMap)(request["transaction"] = new JSONDataMap()); transaction["type"] = "sale"; transaction["amount"] = amount.Value; transaction[isWeb ? "payment_method_nonce" : "payment_method_token"] = fromActualData.Account.AccountID; if (orderContex != null) { transaction["order_id"] = orderContex.OrderId; if (orderContex.IsNewCustomer) { var customer = (JSONDataMap)(transaction["customer"] = new JSONDataMap()); customer["id"] = orderContex.CustomerId; } else { transaction["customer_id"] = orderContex.CustomerId; } } var billing = (JSONDataMap)(transaction["billing"] = new JSONDataMap()); if (fromActualData.FirstName.IsNotNullOrWhiteSpace()) { billing["first_name"] = fromActualData.FirstName; } if (fromActualData.LastName.IsNotNullOrWhiteSpace()) { billing["last_name"] = fromActualData.LastName; } if (fromActualData.BillingAddress.Address1.IsNotNullOrWhiteSpace()) { billing["street_address"] = fromActualData.BillingAddress.Address1; } if (fromActualData.BillingAddress.Address2.IsNotNullOrWhiteSpace()) { billing["extended_address"] = fromActualData.BillingAddress.Address2; } if (fromActualData.BillingAddress.City.IsNotNullOrWhiteSpace()) { billing["locality"] = fromActualData.BillingAddress.City; } if (fromActualData.BillingAddress.Country.IsNotNullOrWhiteSpace()) { billing["country_code_alpha3"] = fromActualData.BillingAddress.Country; } if (fromActualData.BillingAddress.Region.IsNotNullOrWhiteSpace()) { billing["region"] = fromActualData.BillingAddress.Region; } if (fromActualData.BillingAddress.PostalCode.IsNotNullOrWhiteSpace()) { billing["postal_code"] = fromActualData.BillingAddress.PostalCode; } if (fromActualData.BillingAddress.Company.IsNotNullOrWhiteSpace()) { billing["company"] = fromActualData.BillingAddress.Company; } var options = (JSONDataMap)(transaction["options"] = new JSONDataMap()); options["submit_for_settlement"] = capture; if (orderContex != null) { options["store_in_vault_on_success"] = isWeb; } dynamic obj = getResponse(session, URI_Transactions(session.MerchantID), HTTPRequestMethod.POST, request); string created = obj.transaction.createdAt; var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Charge); string customerID = obj.transaction.customer.id; string token = obj.transaction.creditCard.token; string transactionID = obj.transaction.id; var ta = Transaction.Charge(taId, this.Name, "{0}:{1}:{2}".Args(customerID, token, transactionID), from, to, amount, created.AsDateTime(), description); StatCharge(amount); return(ta); } catch (Exception ex) { StatChargeError(); var wex = ex as System.Net.WebException; if (wex != null) { using (var sr = new System.IO.StreamReader(wex.Response.GetResponseStream())) { var respStr = sr.ReadToEnd(); var resp = respStr.IsNotNullOrWhiteSpace() ? respStr.JSONToDynamic() : null; // TODO Exception Handilng } } throw new PaymentException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + this.GetType() + " .Capture(session='{0}', card='{1}', amount='{2}')".Args(session, from, amount), ex); } }
public Transaction Charge(BraintreeSession session, ITransactionContext context, Account from, Account to, Amount amount, bool capture = true, string description = null, object extraData = null) { var orderContex = context as IOrderTransactionContext; var fromActualData = PaySystemHost.AccountToActualData(context, from); try { var isWeb = fromActualData.Account.IsWebTerminalToken; var transaction = new XElement("transaction", new XElement("type", "sale"), new XElement("amount", amount.Value), new XElement(isWeb ? "payment-method-nonce" : "payment-method-token", fromActualData.Account.AccountID)); if (orderContex != null) { transaction.Add(new XElement("order-id", orderContex.OrderId)); if (isWeb) { if (orderContex.IsNewCustomer) { transaction.Add(new XElement("customer", new XElement("id", orderContex.CustomerId))); } else { try { getResponse(session, URI_Customer(session.MerchantID, orderContex.CustomerId.AsString()), method: HTTPRequestMethod.GET); transaction.Add(new XElement("customer-id", orderContex.CustomerId)); } catch { transaction.Add(new XElement("customer", new XElement("id", orderContex.CustomerId))); } } } } if (isWeb) { var billing = new XElement("billing"); if (fromActualData.FirstName.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("first-name", fromActualData.FirstName)); } if (fromActualData.LastName.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("last-name", fromActualData.LastName)); } if (fromActualData.BillingAddress.Address1.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("street-address", fromActualData.BillingAddress.Address1)); } if (fromActualData.BillingAddress.Address2.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("extended-address", fromActualData.BillingAddress.Address2)); } if (fromActualData.BillingAddress.City.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("locality", fromActualData.BillingAddress.City)); } if (fromActualData.BillingAddress.Country.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("country-code-alpha3", fromActualData.BillingAddress.Country)); } if (fromActualData.BillingAddress.Region.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("region", fromActualData.BillingAddress.Region)); } if (fromActualData.BillingAddress.PostalCode.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("postal-code", fromActualData.BillingAddress.PostalCode)); } if (fromActualData.BillingAddress.Company.IsNotNullOrWhiteSpace()) { billing.Add(new XElement("company", fromActualData.BillingAddress.Company)); } transaction.Add(billing); } var options = new XElement("options", new XElement("submit-for-settlement", capture)); if (orderContex != null && isWeb) { options.Add(new XElement("store-in-vault-on-success", true)); } transaction.Add(options); var response = getResponse(session, URI_Transactions(session.MerchantID), new XDocument(transaction)); transaction = response.Root; var transactionID = transaction.Element("id").Value; var status = transaction.Element("status").Value; var captured = status.EqualsOrdIgnoreCase("submitted_for_settlement"); var created = transaction.Element("created-at").Value.AsDateTime(); var customerID = transaction.Element("customer").Element("id").Value; var token = transaction.Element("credit-card").Element("token").Value; var amountAuth = new Amount(amount.CurrencyISO, transaction.Element("amount").Value.AsDecimal()); var amountCaptured = captured ? (Amount?)amountAuth : null; var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Charge); var ta = Transaction.Charge(taId, Name, "{0}:{1}:{2}".Args(customerID, token, transactionID), from, to, amountAuth, created, description, amountCaptured: amountCaptured); StatCharge(amount); return(ta); } catch (Exception ex) { StatChargeError(); if (ex is PaymentException) { throw ex; } throw new PaymentException(StringConsts.PAYMENT_CANNOT_CHARGE_PAYMENT_ERROR + GetType().Name + " .Charge(session='{0}', card='{1}', amount='{2}')".Args(session, from, amount), ex); } }