﻿#### 

The Sitecore Commerce 8.2.1 doesn’t support multi currency functionality in Braintree Payment Gateway, though **Braintree** supports multi currency itself . In my [previous post](https://www.brimit.com/blog/sitecore-commerce-8-multicurrency-support "Sitecore Braintree multi currency") I’ve described how to set up multi currency in Sitecore and now I want to describe how to enable multiple currencies featrue in the Plugin.Sample.Payments.Braintree plugin.

First of all, we need to define Merchant Accounts for each currency that you want to have. Go to your sandbox account or production account in Braintree, then **Account -&gt; Merchant Account Info -&gt; New Sandbox Merchant Account**.

![braintree merchant account](https://www.brimit.com/-/media/images/blog/multicurrency1jpeg.png?la=en&amp;hash=1C0C0A402A694A9BFF1BDB989682E06E)

After that, we need additional configuration in all CommerceAuthoring configs under CommerceAuthoring\wwwroot\data\Environments\

We need to update BraintreeClientPolicy and add Merchants property:

```
   
{
     "$type":  "Plugin.Sample.Payments.Braintree.BraintreeClientPolicy, Plugin.Sample.Payments.Braintree",
     "Environment":  "sandbox",
     "MerchantId":  "xxxxxxxx",
     "PublicKey":  "xxxxxxxxxxxxx",
     "PrivateKey":  "xxxxxxxxxxxxxxx",
     "Merchants": [
                      {
                          "CurrencyCode": "BRL",
                          "MerchantId": "{Merchant Account ID}"
                      },
                      {
                          "CurrencyCode": "EUR",
                          "MerchantId":  "{Merchant Account ID}"                                                              
                      },
                      {
                          "CurrencyCode": "GBP",
                          "MerchantId":  "{Merchant Account ID}"
                      }
                  ],
     "ConnectTimeout":  120000,
     "PolicyId":  "0af6253f42184fd8ae0a61085980c03c",
     "Models":  {
                    "$type":  "System.Collections.Generic.List`1[[Sitecore.Commerce.Core.Model, Sitecore.Commerce.Core]], mscorlib",
                    "$values":  [

                                ]
                }
 },
```

In the code above you should replace {Merchant Account ID} on your Merchant Account ID for each currency. Now CommersAuthoring knows about available Merchants Accounts.

Now we need to modify CreateFederatedPaymentBlock class in Plugin.Sample.Payments.Braintree project and add logic for Merchant Accounts:

```
    
[PipelineDisplayName(PaymentsBraintreeConstants.Pipelines.Blocks.CreateFederatedPaymentBlock)]
public class CreateFederatedPaymentBlock : PipelineBlock<CartEmailArgument, CartEmailArgument, CommercePipelineExecutionContext>
{
    /// <summary>
    /// Runs the specified argument.
    /// </summary>
    /// <param name="arg">The argument.</param>
    /// <param name="context">The context.</param>
    /// <returns>
    /// A cart with federate payment component
    /// </returns>
    public override Task<CartEmailArgument> Run(CartEmailArgument arg, CommercePipelineExecutionContext context)
    {
        Condition.Requires(arg).IsNotNull($"{this.Name}: The cart can not be null");

        var cart = arg.Cart;
        if (!cart.HasComponent<FederatedPaymentComponent>())
        {
            return Task.FromResult(arg);
        }

        var payment = cart.GetComponent<FederatedPaymentComponent>();

        if (string.IsNullOrEmpty(payment.PaymentMethodNonce))
        {
            context.Abort(context.CommerceContext.AddMessage(
                context.GetPolicy<KnownResultCodes>().Error,
                "InvalidOrMissingPropertyValue",
                new object[] { "PaymentMethodNonce" },
                $"Invalid or missing value for property 'PaymentMethodNonce'."), context);

            return Task.FromResult(arg);
        }

        var braintreeClientPolicy = context.GetPolicy<BraintreeClientPolicy>();
        if (string.IsNullOrEmpty(braintreeClientPolicy?.Environment) || string.IsNullOrEmpty(braintreeClientPolicy?.MerchantId)
            || string.IsNullOrEmpty(braintreeClientPolicy?.PublicKey) || string.IsNullOrEmpty(braintreeClientPolicy?.PrivateKey) || braintreeClientPolicy.Merchants == null || !braintreeClientPolicy.Merchants.Any())
        {
            context.CommerceContext.AddMessage(
               context.GetPolicy<KnownResultCodes>().Error,
               "InvalidClientPolicy",
               new object[] { "BraintreeClientPolicy" },
                $"{this.Name}. Invalid BraintreeClientPolicy");
            return Task.FromResult(arg);
        }

        try
        {
            var merchant = braintreeClientPolicy.Merchants.FirstOrDefault(x => x.CurrencyCode == cart.Totals.PaymentsTotal.CurrencyCode);
            var gateway = new BraintreeGateway(braintreeClientPolicy?.Environment, braintreeClientPolicy?.MerchantId, braintreeClientPolicy?.PublicKey, braintreeClientPolicy?.PrivateKey);

            var request = new TransactionRequest
            {
                Amount = payment.Amount.Amount,
                //fix
                MerchantAccountId = merchant?.MerchantId,
                PaymentMethodNonce = payment.PaymentMethodNonce,
                BillingAddress = ComponentsHelper.TranslatePartyToAddressRequest(payment.BillingParty, context),
                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true
                }
            };

            Result<Transaction> result = gateway.Transaction.Sale(request);

            if (result.IsSuccess())
            {
                Transaction transaction = result.Target;
                payment.TransactionId = transaction?.Id;
                payment.TransactionStatus = transaction?.Status?.ToString();
                payment.PaymentInstrumentType = transaction?.PaymentInstrumentType?.ToString();
                //fix
                payment.Amount.CurrencyCode = transaction?.CurrencyIsoCode;

                var cc = transaction?.CreditCard;
                payment.MaskedNumber = cc?.MaskedNumber;
                payment.CardType = cc?.CardType?.ToString();
                if (cc?.ExpirationMonth != null)
                {
                    payment.ExpiresMonth = int.Parse(cc.ExpirationMonth);
                }

                if (cc?.ExpirationYear != null)
                {
                    payment.ExpiresYear = int.Parse(cc.ExpirationYear);
                }
            }
            else
            {
                string errorMessages = result.Errors.DeepAll().Aggregate(string.Empty, (current, error) => current + ("Error: " + (int)error.Code + " - " + error.Message + "\n"));

                context.Abort(context.CommerceContext.AddMessage(
                   context.GetPolicy<KnownResultCodes>().Error,
                   "CreatePaymentFailed",
                   new object[] { "PaymentMethodNonce" },
                   $"{this.Name}. Create payment failed :{ errorMessages }"), context);
            }

            return Task.FromResult(arg);
        }
        catch (BraintreeException ex)
        {
            context.Abort(context.CommerceContext.AddMessage(
               context.GetPolicy<KnownResultCodes>().Error,
               "CreatePaymentFailed",
                new object[] { "PaymentMethodNonce", ex },
                $"{this.Name}. Create payment failed."), context);
            return Task.FromResult(arg);
        }
    }
}
```

After all these small changes you have a complete Braintree integration with multi currency support working. 

Find the plugin file [on GitHub](https://github.com/Frog911/Plugin.Sample.Payments.BraintreeWithMultiCurrencySupport/blob/master/Plugin.Sample.Payments.Braintree/Pipelines/Blocks/CreateFederatedPaymentBlock.cs "Sitecore Braintree multi currency")

Fly high with Sitecore Commerce!

###### Author

[!\[apaliakou\](https://www.brimit.com/-/jssmedia/feature/blogs/authors/apaliakou.jpg?h=216&amp;iar=0&amp;w=360&amp;hash=5BE96F17AE5B47F66D9F684B87773675)
Andrei Paliakou
Sitecore MVP/ Lead Developer](https://www.brimit.com/blog/author?authors=Andrei%20Paliakou)

#### More on Sitecore

[!\[How Vercel Will Help You Save Effort When Deploying Sophisticated Sitecore Projects\](https://www.brimit.com/-/jssmedia/project/brimit/blog/2024/vercel_cover-image.png)
#Guides#How-toDXPE-commerce
##### How Vercel Will Help You Save Effort When Deploying Sophisticated Sitecore Projects
Optimize and accelerate the development and deployment of complex multisite Sitecore projects.
Alexei Vershalovich on July 17, 2024](https://www.brimit.com/blog/how-vercel-will-help-you-save-effort-when-deploying-sophisticated-sitecore-projects)

[!\[Training Up Tomorrow's Sitecore MVPs: a Mentoring Success Story\](https://www.brimit.com/-/jssmedia/project/brimit/blog/2023/sitecore-mentoring---cover-image.png)
#How-toDXP
##### Training Up Tomorrow's Sitecore MVPs: a Mentoring Success Story
How to participate in the Sitecore Mentor program and help younger colleagues jump-start a career in Sitecore development.
Sergey Baranov on October 2, 2023](https://www.brimit.com/blog/training-up-tomorrows-sitecore-mvps)

[!\[Going Headless. Part 2: When a Headless CMS Is Your Best Bet (if you have Sitecore)\](https://www.brimit.com/-/jssmedia/project/brimit/blog/2022/headless/adobestock_456986731.jpg)
#How-toDXPE-commerce
##### Going Headless. Part 2: When a Headless CMS Is Your Best Bet (if you have Sitecore)
Discover how a headless CMS can benefit organizations that use Sitecore.
Daniil Raschupkin, Palina Trokhautsava on September 15, 2022](https://www.brimit.com/blog/going-headless-part-2-when-a-headless-cms-is-your-best-bet-if-you-have-sitecore)

![](https://bat.bing.net/action/0?ti=187017043&amp;tm=gtm002&amp;Ver=2&amp;mid=1b69db17-0358-4ca3-aa6b-278dde45161c&amp;bo=2&amp;gtm_tag_source=1&amp;pi=0&amp;lg=en-US&amp;sw=800&amp;sh=600&amp;sc=24&amp;nwd=1&amp;tl=Sitecore%20Commerce%208.2.1%20Multi%20Currency%20Support%20for%20Braintree%20integration&amp;kw=Sitecore,%20commerce,%208.2.1,%20multi,%20currency,%20cart,%20Braintree,%20integration,%20Sitecore%20Commerce&amp;p=https%3A%2F%2Fwww.brimit.com%2Fblog%2Fsitecore-commerce-8-multi-currency-support-braintree2&amp;r=&amp;lt=269&amp;evt=pageLoad&amp;sv=2&amp;asc=D&amp;cdb=AQAY&amp;rn=564331)