PHP Venmo Integration with Braintree

In this article, we learn about Venmo Integration with Braintree using PHP for server-side implementation.

Introduction

Venmo is a payment method for mobile devices supported by Android and iPhone devices. But you can integrate Venmo on the web app which is only working when the website is open on mobile devices.

PHP Venmo Integration with Braintree

This guide is about how Venmo payment works with Websites or web apps with Braintree API using PHP.

Here are 3 important steps to integrate Venmo on the website using Braintree API.

3 Important Steps to Venmo Integration with Braintree

  • API configuration on the Braintree portal.
  • Client-side Implementation using JS
  • Server-side Implementation using PHP

Step-1: API Configuration on Braintree

For getting sandbox API keys first we have to create a sandbox account on Braintree Portal.

4 Simple Steps To Braintree Account Setup with API

Here the complete guide how to setup Braintree Account for getting API Key

Barintree Sandbox Register: https://www.braintreepayments.com/sandbox

After login to the portal Click below gear icon and go to the processing option.

Venmo Integration with Braintree

On the processing page you see the page like below go to the option and enable the venmo.

Venmo Integration with Braintree

After enabling the Venmo, go to the API option on top menu.

You can see this page, on this copy the Tokenization Keys

Venmo Integration with Braintree

Step-2: Client-side Implementation using JS

For implementing the client-side of the web App we use Braintree JavaScript V3 SDK, which supports Venmo as a payment option if the user has a mobile website.

Installation

To setup JavaScript SDK we use the CDN link of SDK which has version 3.

After the client JS, we load the Venmo and their data collector JS SDK. Here we how to include those JS SDK using the CDN link.

<script src="https://js.braintreegateway.com/web/3.57.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.57.0/js/venmo.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.57.0/js/data-collector.min.js"></script>

On very top you have to create an HTML button for JS Event click.

<button type="button" id="venmo-button" style="background:white;border-bottom: none;"><img style="border-radius: 20px;" src="https://s2.r29static.com/bin/entry/1f8/0,0,2000,1050/x,80/1986150/image.jpg" height="50px" width="100px"></button>

Client Initialization

To initialize the client we use Tokenization key which we take from above process.

Using that creating a Venmo component.

// Create a client.
braintree.client.create({
  authorization: 'sandbox_s9hw272b_dgg5x66vptdfnbtb'
}, function (clientErr, clientInstance) {
  // Stop if there was a problem creating the client.
  // This could happen if there is a network error or if the authorization
  // is invalid.
  console.log("clientInstance:",clientInstance);
  if (clientErr) {
    console.error('Error creating client:', clientErr);
    return;
  }

Collect Device Data

Device data is important and must have for complete the transaction.

braintree.dataCollector.create({
        client: clientInstance,
        paypal: true
      }, function (dataCollectorErr, dataCollectorInstance) {
        if (dataCollectorErr) {
          // Handle error in creation of data collector.
          console.log(dataCollectorErr);
          return;
        }
    
        // At this point, you should access the deviceData value and provide it
        // to your server, e.g. by injecting it into your form as a hidden input.
        console.log('dataCollectorInstance:', dataCollectorInstance);
        console.log('Got device data:', dataCollectorInstance.deviceData);
       
      });

After that we creating the Venmo button onClick functionality.

function displayVenmoButton(venmoInstance) {
      // Assumes that venmoButton is initially display: none.
      venmoButton.style.display = 'block';
      venmoButton.addEventListener('click', function () {
        venmoButton.disabled = true;
        
        venmoInstance.tokenize(function (tokenizeErr, payload) {
          venmoButton.removeAttribute('disabled');
    
          if (tokenizeErr) {
            handleVenmoError(tokenizeErr);
          } else {
            handleVenmoSuccess(payload);
          }
        });
      });
    }
    
    function handleVenmoError(err) {
      if (err.code === 'VENMO_CANCELED') {
        console.log('App is not available or user aborted payment flow');
      } else if (err.code === 'VENMO_APP_CANCELED') {
        console.log('User canceled payment flow');
      } else {
        console.error('An error occurred:', err.message);
      }
    }
      braintree.venmo.create({
        client: clientInstance,
        // Add allowNewBrowserTab: false if your checkout page does not support
        // relaunching in a new tab when returning from the Venmo app. This can
        // be omitted otherwise.
        allowNewBrowserTab: false
      }, function (venmoErr, venmoInstance) {
        if (venmoErr) {
          console.error('Error creating Venmo:', venmoErr);
          return;
        }
        console.log("venmoInstance:",venmoInstance);
        // Verify browser support before proceeding.
        if (!venmoInstance.isBrowserSupported()) {
          console.log('Browser does not support Venmo');
          return;
        }
        displayVenmoButton(venmoInstance);
    
        // Check if tokenization results already exist. This occurs when your
        // checkout page is relaunched in a new tab. This step can be omitted
        // if allowNewBrowserTab is false.
        if (venmoInstance.hasTokenizationResult()) {
          venmoInstance.tokenize(function (tokenizeErr, payload) {
            if (err) {
              handleVenmoError(tokenizeErr);
            } else {
              handleVenmoSuccess(payload);
            }
          });
          return;
        }
      });
    });
    
    
    function handleVenmoSuccess(payload) {
      // Send the payment method nonce to your server, e.g. by injecting
      // it into your form as a hidden input.
      console.log('Got a payment method nonce:', payload.nonce);

      // Display the Venmo username in your checkout UI.
      console.log('Venmo user:', payload.details.username);
        var amount = 1;

        //test nonce for venmo
        payload_nonce = "fake-venmo-account-nonce";

        //uncomment this for live integration
        var payerID = payload_nonce;//payload.nonce;
        var deviceDataToken = '{"correlation_id":"bc850bc0840ab2d9e1d34842d0e3ffa5"}';
        var deviceData = encodeURI(deviceDataToken);
        
        window.location = "/Directory_name/venmo_server.php/?payerID=" + payerID + "&deviceData=" + deviceData+ "&amount=" + amount;
    }

Complete Source code of Client-side Venmo Implementation

venmo_pay.php

<button type="button" id="venmo-button" style="background:white;border-bottom: none;"><img style="border-radius: 20px;" src="https://s2.r29static.com/bin/entry/1f8/0,0,2000,1050/x,80/1986150/image.jpg" height="50px" width="100px"></button>
<script src="https://js.braintreegateway.com/web/3.57.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.57.0/js/venmo.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.57.0/js/data-collector.min.js"></script>
<script>
var venmoButton = document.querySelector('#venmo-button');
    // Create a client.
    braintree.client.create({
      authorization: 'sandbox_s9hw272b_dgg5x66vptdfnbtb'
    }, function (clientErr, clientInstance) {
      // Stop if there was a problem creating the client.
      // This could happen if there is a network error or if the authorization
      // is invalid.
      console.log("clientInstance:",clientInstance);
      if (clientErr) {
        console.error('Error creating client:', clientErr);
        return;
      }
    
      braintree.dataCollector.create({
        client: clientInstance,
        paypal: true
      }, function (dataCollectorErr, dataCollectorInstance) {
        if (dataCollectorErr) {
          // Handle error in creation of data collector.
          console.log(dataCollectorErr);
          return;
        }
    
        // At this point, you should access the deviceData value and provide it
        // to your server, e.g. by injecting it into your form as a hidden input.
        console.log('dataCollectorInstance:', dataCollectorInstance);
        console.log('Got device data:', dataCollectorInstance.deviceData);
       
      });
    
        
      function displayVenmoButton(venmoInstance) {
      // Assumes that venmoButton is initially display: none.
      venmoButton.style.display = 'block';
      venmoButton.addEventListener('click', function () {
        venmoButton.disabled = true;
        
        venmoInstance.tokenize(function (tokenizeErr, payload) {
          venmoButton.removeAttribute('disabled');
    
          if (tokenizeErr) {
            handleVenmoError(tokenizeErr);
          } else {
            handleVenmoSuccess(payload);
          }
        });
      });
    }
    
    function handleVenmoError(err) {
      if (err.code === 'VENMO_CANCELED') {
        console.log('App is not available or user aborted payment flow');
      } else if (err.code === 'VENMO_APP_CANCELED') {
        console.log('User canceled payment flow');
      } else {
        console.error('An error occurred:', err.message);
      }
    }
      braintree.venmo.create({
        client: clientInstance,
        // Add allowNewBrowserTab: false if your checkout page does not support
        // relaunching in a new tab when returning from the Venmo app. This can
        // be omitted otherwise.
        allowNewBrowserTab: false
      }, function (venmoErr, venmoInstance) {
        if (venmoErr) {
          console.error('Error creating Venmo:', venmoErr);
          return;
        }
        console.log("venmoInstance:",venmoInstance);
        // Verify browser support before proceeding.
        if (!venmoInstance.isBrowserSupported()) {
          console.log('Browser does not support Venmo');
          return;
        }
        displayVenmoButton(venmoInstance);
    
        // Check if tokenization results already exist. This occurs when your
        // checkout page is relaunched in a new tab. This step can be omitted
        // if allowNewBrowserTab is false.
        if (venmoInstance.hasTokenizationResult()) {
          venmoInstance.tokenize(function (tokenizeErr, payload) {
            if (err) {
              handleVenmoError(tokenizeErr);
            } else {
              handleVenmoSuccess(payload);
            }
          });
          return;
        }
      });
    });
    
    
    function handleVenmoSuccess(payload) {
      // Send the payment method nonce to your server, e.g. by injecting
      // it into your form as a hidden input.
      console.log('Got a payment method nonce:', payload.nonce);

      // Display the Venmo username in your checkout UI.
      console.log('Venmo user:', payload.details.username);
        var amount = 1;

        //test nonce for venmo
        payload_nonce = "fake-venmo-account-nonce";

        //uncomment this for live integration
        var payerID = payload_nonce;//payload.nonce;
        var deviceDataToken = '{"correlation_id":"bc850bc0840ab2d9e1d34842d0e3ffa5"}';
        var deviceData = encodeURI(deviceDataToken);
        
        window.location = "/Directory_name/venmo_server.php/?payerID=" + payerID + "&deviceData=" + deviceData+ "&amount=" + amount;
    }
    
</script>

Step-3: Server-side Implementation using PHP

First we include the Braintree PHP library for implementing server-side transaction.

Here is the github link of complete code with the Braintree PHP library included.

https://github.com/bikashkrpanda/PHP-venmo-integration-with-braintree

Complete Source code of Server-side implementation

venmo_server.php

<?php
require_once ('braintree-php-3.30.0/lib/Braintree.php');

  $gateway = new Braintree_Gateway([
  'environment' => 'sandbox',
  'merchantId' => 'dgg5x66vptdfnbtb',
  'publicKey' => 'kqx2gkjpwj59gdqz',
  'privateKey' => '4ce889ab9cbd4e0f15b13fe6d22399f2'
  ]);
    
  $result_venmo = $gateway->transaction()->sale([
    'amount' => $_GET['amount'],
    'paymentMethodNonce' => $_GET['payerID'],
    'options' => [
        'submitForSettlement' => true,
        'venmo' => [
          'profileId' => ''
        ]
    ],
    'deviceData' => urldecode($_GET['deviceData'])
  ]);

echo "Transaction ID:".$paymentID = $result_venmo->transaction->id;

?>

Here the complete solution of the Venmo integration with PHP Braintree.

If you facing any issue, comment below I will try to resolve the issue.

Also check:

Happy Coding..!

Was this article helpful?
YesNo
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH, my native place in Odisha. I am a Web Programmer by profession and working on more than 50 projects to date. My passion is working on the web-based project using PHP and relate to all CMS and frameworks which is based on PHP.
Posts created 163

6 thoughts on “PHP Venmo Integration with Braintree

  1. hello,
    i applied your code on my website, but it show “Browser does not support Venmo”.
    i am getting stuck for last 4 hours.
    venmo is working on web application or not. please tell me.

    1. Hi,
      Venmo payment is only supported for mobile devices..
      One way to test it…Before redirection process put inputs statically after that open url on mobile view using inspect Developer tool than hit that URL you get your output

  2. Hi,

    I am getting an error VENMO_NOT_ENABLED when I run braintree.venmo.create in the frontend. I have enabled venmo in sandbox console processing menu.

    Here is the error I get:
    {
    code: “VENMO_NOT_ENABLED”
    details: undefined
    message: “Venmo is not enabled for this merchant.”
    name: “BraintreeError”
    type: “MERCHANT”
    }

    Have you encountered this error before?

    Thank you,
    Miguel

      1. On the processing options, I have enabled venmo and now I get an options button that leads me to a list of merchant profiles. I have one merchant profile, which came in as default.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
mariobet - supertotobet - escort -

takip7.com

We are now accepting Guest Posting and creation of Backlinks
This is default text for notification bar