Braintree .NET SDK

repository·master·Indexed 41 days ago

https://github.com/braintree/braintree_dotnet

A .NET library for integrating with the Braintree Gateway to process payments, manage transactions, and handle credit card information. Supports .NET Framework 4.5.2 and .NET Standard 2.0. Features include the BraintreeGateway for sales and the DisputeGateway for managing dispute lifecycles, evidence submission, and searching. Version 5.x.x is currently active.

Tokens
3.3K
Snippets
9
Records
12
Agent score
49%

What's inside Braintree

  1. Maintain cross-compatibility between .NET Framework and .NET Standard

    master

    The library supports .NET Framework 4.5.2+ and .NET Standard 2.0. All new code and tests must compile against both targets.

    If you need to use methods that are available in one framework but not the other, use C# preprocessor directives to handle the platform-specific logic.

    #if netcore
    NetCore.Method();
    #else
    NetFramework.Method();
    #end
  2. Add new libraries and dependencies

    master

    When adding dependencies to the project, you must target the correct framework group within the .csproj file:

    • For .NET Framework dependencies: Add them to the $(TargetFramework) == 'net452' ItemGroup.
    • For .NET Standard 2.0 dependencies: Add them to the $(TargetFramework) == 'netstandard2.0' ItemGroup.
  3. Quick Start: Create a transaction with Braintree .NET

    master

    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:

    1. Initialize the Gateway: Set the Environment (e.g., Braintree.Environment.SANDBOX), MerchantId, PublicKey, and PrivateKey.
    2. Construct the Request: Create a TransactionRequest specifying the Amount, the PaymentMethodNonce (received from the client), and optional TransactionOptionsRequest (like SubmitForSettlement).
    3. Execute the Sale: Call gateway.Transaction.Sale(request).
    4. 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);
                    }
                }
            }
        }
    }
  4. Braintree .NET Compatibility and Dependencies

    master

    The Braintree .NET library is compatible with the following frameworks:

    • Net Framework 4.5.2
    • Net Standard 2.0

    It has been tested against .NET Framework 4.5.2 (via Mono) and .NET Core 3.1.

    Security Requirement: All connections must use TLS 1.2 or higher and HTTP/1.1 as per PCI Council mandates.

  5. Run unit tests for Braintree .NET

    master

    Unit tests can be run using the dotnet CLI. Note that integration tests are intended for local development environments against a gateway server and are not recommended for general use as they will likely fail.

    To run unit tests on a Unix-like environment (Mac OS X) targeting .NET Core 3.1, restore dependencies and then run the test command specifying the framework. On Windows, perform a restore and build before running the test command.

    #### On Mac OS X or Unix-like environment
    For .NET Core 3.1:
    ```bash
    dotnet restore
    dotnet test . -f netcoreapp3.1

    On a Windows environment

    dotnet restore
    dotnet build
    dotnet test .
  6. Braintree SDK Version Status and Deprecation Policy

    master

    Braintree follows a deprecation policy for its SDKs.

    • Version 5.x.x: Currently Active.
    • Version 4.x.x: Currently Inactive (Deprecated in August 2022, Unsupported as of August 2023).

    If you are upgrading from an Inactive, Deprecated, or Unsupported version, refer to the official Migration Guide.

  7. Add text evidence to a dispute

    master

    You can add text-based evidence to a dispute using AddTextEvidence or AddTextEvidenceAsync. You can pass either a raw string or a TextEvidenceRequest object.

    Parameters:

    • disputeId: The unique identifier of the dispute.
    • content: The text content of the evidence.
    • TextEvidenceRequest.SequenceNumber (optional): An integer representing the sequence of the evidence.

    Exceptions:

    • Throws NotFoundException if the disputeId is invalid.
    • Throws ArgumentException if the content is null or empty, or if the SequenceNumber is not a valid integer.
    // Using raw string
    Result<DisputeEvidence> result = disputeGateway.AddTextEvidence("dispute_id", "Evidence content");
    
    // Using TextEvidenceRequest
    var request = new TextEvidenceRequest {
        Content = "Evidence content",
        SequenceNumber = "1"
    };
    Result<DisputeEvidence> resultAsync = await disputeGateway.AddTextEvidenceAsync("dispute_id", request);
  8. Manage disputes with DisputeGateway

    master

    The DisputeGateway class provides methods to manage the lifecycle of disputes, including finding, accepting, finalizing, and searching for disputes. It also allows you to submit evidence (text or files) to support a dispute or remove existing evidence.

    Key operations include:

    • Finding: Retrieve details for a specific dispute using Find or FindAsync.
    • Lifecycle: Use Accept to accept a dispute or Finalize to finalize it.
    • Evidence Management: Add text-based or file-based evidence, or remove existing evidence.
    • Searching: Use Search to perform advanced searches for disputes, which returns a PaginatedCollection<Dispute>.
    // Example: Finding a dispute and adding text evidence
    var result = disputeGateway.Find("dispute_id");
    if (result.IsSuccess) {
        var dispute = result.Value;
        disputeGateway.AddTextEvidence("dispute_id", "This is my evidence content.");
    }
  9. Add file evidence to a dispute

    master

    To add file-based evidence to a dispute, use AddFileEvidence or AddFileEvidenceAsync. This requires a documentUploadId which refers to a previously uploaded document.

    Methods:

    • AddFileEvidence(string disputeId, string documentUploadId): A convenience method using a document ID string.
    • AddFileEvidence(string disputeId, FileEvidenceRequest request): Uses a request object.

    Parameters:

    • disputeId: The unique identifier of the dispute.
    • documentUploadId / FileEvidenceRequest.DocumentId: The ID of the uploaded document.

    Exceptions:

    • Throws NotFoundException if the disputeId or documentUploadId is not found.
    // Using document upload ID directly
    Result<DisputeEvidence> result = disputeGateway.AddFileEvidence("dispute_id", "document_upload_id");
    
    // Using FileEvidenceRequest
    var request = new FileEvidenceRequest { DocumentId = "document_upload_id" };
    Result<DisputeEvidence> resultAsync = await disputeGateway.AddFileEvidenceAsync("dispute_id", request);
  10. Search for disputes

    master

    The Search method allows you to perform advanced searches for disputes using a DisputeSearchRequest. This method returns a PaginatedCollection<Dispute>, which handles pagination automatically when iterating through results.

    Usage:

    1. Create a DisputeSearchRequest with your desired filters.
    2. Call Search(request) on the DisputeGateway instance.
    3. Iterate through the returned PaginatedCollection.
    var searchRequest = new DisputeSearchRequest();
    // ... configure searchRequest ...
    
    PaginatedCollection<Dispute> disputes = disputeGateway.Search(searchRequest);
    foreach (var dispute in disputes) {
        // Process each dispute
    }
  11. Create a SettlementBatchSummaryRequest

    master

    Use SettlementBatchSummaryRequest to build requests for retrieving summaries of settlement batch results. You can specify the date of the settlement and optionally group the results by a custom field.

    Properties

    • SettlementDate (DateTime): The date of the settlement batch you wish to summarize.
    • GroupByCustomField (string): An optional field name used to group the summary results.
    SettlementBatchSummaryRequest request = new SettlementBatchSummaryRequest
    {
        SettlementDate = DateTime.Now,
        GroupByCustomField = "my_custom_field"
    };
  12. Remove evidence from a dispute

    master

    Use RemoveEvidence or RemoveEvidenceAsync to delete a specific piece of evidence from a dispute.

    Parameters:

    • disputeId: The unique identifier of the dispute.
    • evidenceId: The unique identifier of the evidence to be removed.

    Exceptions:

    • Throws NotFoundException if either the disputeId or the evidenceId is not found.
    // Synchronous removal
    Result<Dispute> result = disputeGateway.RemoveEvidence("dispute_id", "evidence_id");
    
    // Asynchronous removal
    Result<Dispute> resultAsync = await disputeGateway.RemoveEvidenceAsync("dispute_id", "evidence_id");