Wednesday 17 June 2015

Braintree payment gateway integration

Braintree payment gateway integration


Braintree is an American company which helps online business by processing credit card for merchants. They have payment gateway which support normal payment, recurring billing and credit card storage. It is a Level 1 PCI-DSS(Payment Card Industry Data Security Standard) compliant service provider. Braintree was founded in 2007 by Bryan Johnson. Latter on it was acquired by eBay.

  Following are characteristics of Braintree.
01. Online payment with Web AND mobile application.
02. Streamlining the onboarding process for US merchants.
03. Venmo Touch which checkout with one touch across multiple mobile applications.
04. Marketplace product which manages the payouts, taxes, compliance and chargebacks.
05. Credit Card Data Portability.
06. Fast deposits to bank account.
07. Support over 40 countries and 130 currencies.
08. Sophisticated sales analytics.
09. No fees for failed transactions.
10. No inactivity fees.
11. Consistent pricing for all card brands.
12. 2.9% + $.30 per transaction.


What is Braintree Marketplace
Braintree Marketplace is part of Braintree that enable to split payment between seller and marketplace.

Following are characteristics of Braintree Marketplace.
01. Easy Compliance.
02. No Extra Fees.
03. Flexibility.
04. Splitting payments.
05. Works for both Web and Mobile.
06. No escrow is required, charge when you need.
07. Its free for merchants and charge only on transactions i.e (2.9% + $.30).
08. Braintree generate 1099-K tax forms required by the IRS.


How Braintree works? 
01. Your web requests a "client token" from your server in order to initialize the JS SDK.
02. Your server generates a token and sends back to your client.
03. Once the JS SDK is initialized, it communicates with Braintree, which returns a "payment method nonce" to your client code.
04. You then send the payment nonce to your server.
05. Your server code receives the "payment method nonce" from your client and then uses the PHP SDK to create a transaction.


Question: What are Payment Methods available in Braintree?
01. Paypal
02.Credit Cards
03. Venmo (With on touch)
04. Apple Pay


Question: What is Payment method nonce?
Payment method nonce: It is string returned by the client SDK (javascript) to represent a payment method.
It is reference to the customer payment method details that were provided in your payment form and used by PHP Server.
Note: Expired in 24 Hour


Question: How to get paymentMethodNonce?
1. Create an account in braintree.
2. Get the merchantId, PublicKey and private Key.
3. Update the merchantId, PublicKey and private Key in following code snippet.
4. Run the code.

A. First get the clientToken from your server
/** Include Library and set configuration**/
require_once '/braintree-php301/lib/Braintree.php';
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('xxxxxxxx');//update merchantId
Braintree_Configuration::publicKey('xxxxxxxxxx');//update public key
Braintree_Configuration::privateKey('xxxxxxxxxxxxxxxxxxxxxx'); //Private key

//Get the Client Token
$clientToken = Braintree_ClientToken::generate();

B. Add following following HTML Code.
<script src="https://js.braintreegateway.com/js/beta/braintree-hosted-fields-beta.17.js"></script>
<form action="/payment.php" id="my-sample-form" method="POST">
<label for="card-number">Card Number</label>
      <br />
<div id="card-number">
</div>
<label for="cvv">CVV</label>
      <br />
<div id="cvv">
</div>
<label for="expiration-date">Expiration Date</label>
      <br />
<div id="expiration-date">
</div>
<input type="submit" value="Pay" />
</form>


C. Update the clientToken in following javascript code.
braintree.setup(clientToken, "custom", {
        id: "my-sample-form",
        hostedFields: {
          number: {
            selector: "#card-number"
          },
          cvv: {
            selector: "#cvv"
          },
          expirationDate: {
            selector: "#expiration-date"
          }
        }
      });


OR - Custom Form with Custom URL to get payments
braintree.setup(clientToken, "custom", {
        id: "my-sample-form",
        hostedFields: {
          number: {
            selector: "#card-number",
            placeholder: "Card Number"
          },
          cvv: {
            selector: "#cvv",
            placeholder: "CVV"
          },
          expirationMonth: {
            selector: "#expiration-month",
            placeholder: "Expiration Month"
          },
          expirationYear: {
            selector: "#expiration-year",
            placeholder: "Expiration Year"
          }
        },onPaymentMethodReceived:function(response){
             $.ajax({
                url:'/ajax/braintree-nonce',
                data:'payment_method_nonce='+response.nonce+'&card_digits='+response.details.lastTwo+'&card_type='+response.details.cardType+'&user_id=',
                type:'POST',
                dataType:'json',
                success: function(response) {
                    
                    if(response.success == 1){
                        //write here Code
                    }else{
                       $('#mainSubmitBtn-help').html('Some payment method input fields are invalid. Please try again.').show();
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    //Error Handling
                }
            });
            return false;
            
        },onError:function(response){
              //Error Handling
            
        }
        }); 



Collect above code (A,B and C), In single page and click on "Pay" after filling the cc details

When customer add the credit card detail and submit the form, First request goes to braintree server they do the process and return an unique string with name "payment_method_nonce" to payment.php.
Once get the "payment_method_nonce" from payment.php. Use this token to charge the customer. It is valid upto 24 Hour


Question: How to charge the customer with use of payment_method_nonce token?
/** Include Library and set configuration**/
require_once '/braintree-php301/lib/Braintree.php';
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('xxxxxxxxxxxxxxxx');
Braintree_Configuration::publicKey('xxxxxxxxxxxxxxxxx');
Braintree_Configuration::privateKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxx');
/** Include Library and set configuration**/


$paymentMethodNonce ='699dc252-6388-464a-9712-5dd8fa2bb656';
try{ 
          $result = Braintree_Transaction::sale(array(
               'amount' => '1.00',
               'paymentMethodNonce' => paymentMethodNonce,
               'options' => array(
                 'submitForSettlement' => True
               )
             ));
          $transactionId = $result->transaction->id;
          echo "Transaction Id".$transactionId;die;

       }  catch (Exception $e){
           echo $e->getMessage();die;

       }