To process a transaction, initialize a BraintreeGateway with your credentials and environment, then use the gateway.Transaction.Sale method with a TransactionRequest.
Key steps in the workflow:
- Initialize the Gateway: Set the
Environment (e.g., Braintree.Environment.SANDBOX), MerchantId, PublicKey, and PrivateKey. - Construct the Request: Create a
TransactionRequest specifying the Amount, the PaymentMethodNonce (received from the client), and optional TransactionOptionsRequest (like SubmitForSettlement). - Execute the Sale: Call
gateway.Transaction.Sale(request). - Handle the Result: Use
result.IsSuccess() to check the outcome.- If successful, access the transaction via
result.Target. - If it fails due to a processor error, check
result.Transaction for status and error codes. - If it fails due to validation errors, iterate through
result.Errors.DeepAll() to inspect Attribute, Code, and Message.
using System;
using Braintree;
namespace BraintreeExample
{
class Program
{
static void Main(string[] args)
{
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "the_merchant_id",
PublicKey = "a_public_key",
PrivateKey = "a_private_key"
};
TransactionRequest request = new TransactionRequest
{
Amount = 1000.00M,
PaymentMethodNonce = nonceFromTheClient,
Options = new TransactionOptionsRequest
{
SubmitForSettlement = true
}
};
Result<Transaction> result = gateway.Transaction.Sale(request);
if (result.IsSuccess())
{
Transaction transaction = result.Target;
Console.WriteLine("Success!: " + transaction.Id);
}
else if (result.Transaction != null)
{
Transaction transaction = result.Transaction;
Console.WriteLine("Error processing transaction:");
Console.WriteLine(" Status: " + transaction.Status);
Console.WriteLine(" Code: " + transaction.ProcessorResponseCode);
Console.WriteLine(" Text: " + transaction.ProcessorResponseText);
}
else
{
foreach (ValidationError error in result.Errors.DeepAll())
{
Console.WriteLine("Attribute: " + error.Attribute);
Console.WriteLine(" Code: " + error.Code);
Console.WriteLine(" Message: " + error.Message);
}
}
}
}
}