πŸ“œ ⬆️ ⬇️

My experience with BrainTree

image
So, it all started with the fact that at work it was necessary to fasten the BrainTree payment system to the project. Looking for instructions on how to do this on Russian-language sites, I realized that I would have to figure it out for myself.
First in brief about BrainTree. The system is designed for electronic payments using credit cards.
One-time payments are supported, as well as recurring payments (subscriptions).
The site BrainTree has a section Developers. There it’s quite clear how to set up and launch a payment on your site using various programming languages:

Also, developers are provided with a convenient sandbox in which you can see all possible system settings.

Security


On the client side, a JavaScript library is used to encrypt the card number and CVV on the client side. Further, the data from the form is transmitted to your server, which is connected by the BrainTree server for the operation. In response, BrainTree sends the result of the action, which can be processed differently: give an error, make a subscription, and so on.
image
I will consider an example of using this system on the MVC 4 site.
First, create a new project with a default template. (It is assumed that you have already registered, it is not so hard).

One-time payments


To start using BrainTree, you need to download the library and connect it to the project.
Then go to BrainTree under your login and copy the configuration using your language (we have .Net).
image
')
Inside the controller we create a static variable.
public static BraintreeGateway Gateway = new BraintreeGateway { Environment = Braintree.Environment.SANDBOX, PublicKey = "your_public_key", PrivateKey = "your_private_key", MerchantId = "your_merchant_id" }; 

In this case, do not forget to connect the library BrainTree.
 using Braintree; 

Now you need to create a page and place the form.
 <h1>Braintree Credit Card Transaction Form</h1> <div> <form action="@Url.Action("CreateTransaction")" method="POST" id="braintree-payment-form"> <p> <label>Card Number</label> <input type="text" size="20" autocomplete="off" data-encrypted-name="number" /> </p> <p> <label>CVV</label> <input type="text" size="4" autocomplete="off" data-encrypted-name="cvv" /> </p> <p> <label>Expiration (MM/YYYY)</label> <input type="text" size="2" name="month" /> / <input type="text" size="4" name="year" /> </p> <input type="submit" id="submit" /> </form> </div> 

Also, in order to encrypt the card number and cvv you need to use the Braintree.js library. The public key can be obtained in the BrainTree control panel.
 <script type="text/javascript" src="https://js.braintreegateway.com/v1/braintree.js"></script> <script type="text/javascript"> var braintree = Braintree.create("YourClientSideEncryptionKey"); braintree.onSubmitEncryptForm('braintree-payment-form'); </script> 

Now on the server you need to take this form.
 [HttpPost] public ActionResult CreateTransaction(FormCollection collection) { TransactionRequest request = new TransactionRequest { Amount = 1000.0M, //     USD CreditCard = new TransactionCreditCardRequest { Number = collection["number"], CVV = collection["cvv"], ExpirationMonth = collection["month"], ExpirationYear = collection["year"] }, Options = new TransactionOptionsRequest { SubmitForSettlement = true } }; Result<Transaction> result = Gateway.Transaction.Sale(request); if (result.IsSuccess()) { Transaction transaction = result.Target; ViewData["TransactionId"] = transaction.Id; } else { ViewData["Message"] = result.Message; } return View(); } 

And also create a page to display the results of the transaction.
 @if (ViewData.ContainsKey("TransactionId")) { <h2>Success! Transaction ID: @ViewData["TransactionId"]</h2> } else { <h2>Error: @ViewData["Message"]</h2> } 

After that, you can start testing our system. For verification, we use the card number β€œ4111111111111111” and cvv β€œ111”, since other system does not accept. As a date card, you can use any valid date.

Recurring payments


First you need to create a subscription plan (or maybe not one, if different subscription options are assumed) in the BrainTree control panel. To do this, in the left pane, select Recurring Billing> Plans. Next, create a new plan:
image
If necessary, add a trial period to it:
image
And also set the duration of the payment cycle and the duration of the subscription: image
Now we create a page with a form for entering data about the card and the subscriber. So we create a customer. Do not forget to add encryption of the card number and cvv before sending the form.
  <h1>Braintreegateway recurring billing</h1> <div id="braintreegateway-div-net"> <h3>Braintree Credit Card Transaction Form</h3> <div> <form action="@Url.Action("CreateCustomer")" method="POST" id="braintree-payment-form1"> <p> <label>First name</label> <input type="text" data-encrypted-name="first_name" /> </p> <p> <label>Last name</label> <input type="text" data-encrypted-name="last_name" /> </p> <p> <label>Postal code</label> <input type="text" data-encrypted-name="postal_code" /> </p> <p> <label>Card Number</label> <input type="text" size="20" autocomplete="off" data-encrypted-name="number" /> </p> <p> <label>CVV</label> <input type="text" size="4" autocomplete="off" data-encrypted-name="cvv" /> </p> <p> <label>Expiration (MM/YYYY)</label> <input type="text" size="2" name="month" /> / <input type="text" size="4" name="year" /> </p> <table> </table> <input type="submit" id="submit" value="Create account"/> </form> </div> <script type="text/javascript" src="https://js.braintreegateway.com/v1/braintree.js"></script> <script type="text/javascript"> var braintree = Braintree.create("YourClientSideEncryptionKey"); braintree.onSubmitEncryptForm('braintree-payment-form1'); </script> </div> 

We process the form transfer on the server:
 [HttpPost] public ActionResult CreateCustomer(FormCollection collection) { CustomerRequest request = new CustomerRequest { FirstName = collection["first_name"], LastName = collection["last_name"], CreditCard = new CreditCardRequest { BillingAddress = new CreditCardAddressRequest { PostalCode = collection["postal_code"] }, Number = collection["number"], ExpirationMonth = collection["month"], ExpirationYear = collection["year"], CVV = collection["cvv"] } }; Result<Customer> result = Constants.Gateway.Customer.Create(request); if (result.IsSuccess()) { Customer customer = result.Target; ViewData["CustomerName"] = customer.FirstName + " " + customer.LastName; ViewData["CustomerId"] = customer.Id; } else { ViewData["Message"] = result.Message; } return View(); } 

We return a page with information about the error, or with the button "Subscribe".
 @if (ViewData.ContainsKey("CustomerId")) { <h2>Customer created with name: @ViewData["CustomerName"]</h2> @Html.ActionLink("Click here to sign this Customer up for a recurring payment", "CreateSubscription", "Home", new { id = ViewData["CustomerId"] }, null) } else { <h2>Error: @ViewData["Message"]</h2> } 

And handle the create subscription button
 public ActionResult CreateSubscription(string id) { try { Customer customer = Constants.Gateway.Customer.Find(id); string paymentMethodToken = customer.CreditCards[0].Token; SubscriptionRequest request = new SubscriptionRequest { PaymentMethodToken = paymentMethodToken, PlanId = "test_plan_1" }; Result<Subscription> result = Constants.Gateway.Subscription.Create(request); return Content("Subscription Status " + result.Target.Status); } catch (Braintree.Exceptions.NotFoundException e) { return Content("No customer found for id: " + id); } } 

After completing these actions, customers will be able to pay a subscription to your product.

In the next article, those interested can tell you more about how everything happens on the battle server, as well as about the possibilities of using discounts, surcharges, viewing transactions and other delights of this system.

Source: https://habr.com/ru/post/196244/


All Articles