Is there a way to fetch Paypal's vaulted credit card information from Braintree?

247 views Asked by At

In my project, I am using scheduler cron job to do monthly subscription with a trail period of 2 months. So, if there is any service that expires in current date, a particular amount will be payed to admin, thus enabling monthly subscription process. Being said that, I have stored the credit card reference ID from Paypal vault in my DB. Now, I want to use this reference ID for payment via Braintree. Is there any way to get the details from Paypal vault or use the card-reference ID to directly do the payment. Please help!

I tried the below code. But not sure how to fetch the credit card details from Paypal vault or the card-ref ID from DB and add it here.

public class BrainTreeImplementation {

    private static Logger logger = Logger.getLogger(BrainTreeImplementation.class.getName());

// Below are the Braintree sandbox credentials
    private static BraintreeGateway gateway = null;
    private static String publicKey = "YOUR_PUBLIC_KEY";
    private static String privateKey = "YOUR_PRIVATE_KEY";
    private static String merchantId = "YOUR_MERCHANT_ID";

    public static void main(String[] args) {
        // Initialize Braintree Connection
        gateway = connectBraintreeGateway();
         braintreeProcessing();
    }

    public static void braintreeProcessing() {

        System.out.println(" ----- BrainTree Implementation Starts --- ");

        // Generate client Token
        String clientToken = generateClientToken();
        System.out.println(" Client Token : " + clientToken);

        // Receive payment method nonce
        String nonceFromTheClient = receivePaymentMethodNonce();

        // Do payment transactions
        BigDecimal amount = new BigDecimal("5.10");
         doPaymentTransaction(nonceFromTheClient, amount);
     }

// Connect to Braintree Gateway.
    public static BraintreeGateway connectBraintreeGateway() {
        BraintreeGateway braintreeGateway = new BraintreeGateway(Environment.SANDBOX, merchantId, publicKey,
                privateKey);
         return braintreeGateway;
    }

// Make an endpoint which return client token.
    public static String generateClientToken() {
        // client token will be generated at server side and return to client
        String clientToken = gateway.clientToken().generate();
        return clientToken;
    }

 // Make an endpoint which receive payment method nonce from client and do payment.
     public static String receivePaymentMethodNonce() {
        String nonceFromTheClient = "fake-valid-mastercard-nonce";
        return nonceFromTheClient;
    }

 // Make payment 
 public void String

    doPaymentTransaction(String paymentMethodNonce, BigDecimal amount) {

     TransactionRequest request = new TransactionRequest();
     request.amount(amount);
     request.paymentMethodNonce(paymentMethodNonce);

     CustomerRequest customerRequest = request.customer();
     customerRequest.email("[email protected]");
     customerRequest.firstName("Chirag");
     customerRequest.lastName("Patel");

     TransactionOptionsRequest options = request.options();
     options.submitForSettlement(true);

     // Done the transaction request
     options.done();

     // Create transaction ...
     Result<Transaction> result = gateway.transaction().sale(request);
     boolean isSuccess = result.isSuccess();

     if (isSuccess) {
         Transaction transaction = result.getTarget();
         displayTransactionInfo(transaction);
     } else {
         ValidationErrors errors = result.getErrors();
         validationError(errors);
     }
 }

    private static void displayTransactionInfo(Transaction transaction) {
        System.out.println(" ------ Transaction Info ------ ");
        System.out.println(" Transaction Id  : " + transaction.getId());
        System.out.println(" Processor Response Text : " +        transaction.getProcessorResponseText());
    }

private static void validationError(ValidationErrors errors) {
    List<ValidationError> error = errors.getAllDeepValidationErrors();
    for (ValidationError er : error) {
        System.out.println(" error code : " + er.getCode());
        System.out.println(" error message  : " + er.getMessage());
     }
 }
 }
1

There are 1 answers

4
Z Hu On BEST ANSWER
  1. Use PayPal Vault or PayPal Checkout with Vault to get the nonce and send it to the server. PayPal Vault

  2. The server use the nonce to create user. Create Customer

  3. The server use the user id or payment token to create a transaction. Sale

sample code

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

</head>
<body>
<div id="paypal-button" style="padding-top: 150px"></div>
</body>
<!-- Load the client component. -->
<script src="https://js.braintreegateway.com/web/3.88.2/js/client.min.js"></script>

<!-- Load the PayPal Checkout component. -->
<script src="https://js.braintreegateway.com/web/3.88.2/js/paypal-checkout.min.js"></script>

<script>
    // Create a PayPal Checkout component
    // Create a client.
    braintree.client.create({
        authorization: '' //tokenizationKey
    }, 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.
        if (clientErr) {
            console.error('Error creating client:', clientErr);
            return;
        }

        // Create a PayPal Checkout component.
        braintree.paypalCheckout.create({
            client: clientInstance
        }, function (paypalCheckoutErr, paypalCheckoutInstance) {
            paypalCheckoutInstance.loadPayPalSDK({
                vault: true
            }, function () {
                paypal.Buttons({
                    fundingSource: paypal.FUNDING.PAYPAL,

                    createBillingAgreement: function () {
                        return paypalCheckoutInstance.createPayment({
                            flow: 'vault', // Required
                            // The following are optional params
                            billingAgreementDescription: 'Your agreement description',
                            enableShippingAddress: false,
                            shippingAddressEditable: false,
                        });
                    },

                    onApprove: function (data, actions) {
                        return paypalCheckoutInstance.tokenizePayment(data, function (err, payload) {
                            // Submit `payload.nonce` to your server
                            console.log('nonce:',payload.nonce)
                        });
                    },

                    onCancel: function (data) {
                        console.log('PayPal payment canceled', JSON.stringify(data, 0, 2));
                    },

                    onError: function (err) {
                        console.error('PayPal error', err);
                    }
                }).render('#paypal-button').then(function () {
                    // The PayPal button will be rendered in an html element with the ID
                    // `paypal-button`. This function will be called when the PayPal button
                    // is set up and ready to be used
                });

            });

        });

    });
</script>
</html>
public class BraintreePayDemo {

    private static BraintreeGateway gateway = new BraintreeGateway(
            Environment.SANDBOX,
            "merchantId",
            "publicKey",
            "privateKey"
    );

    public static void customerCreate(){
        CustomerRequest request = new CustomerRequest()
                .id("test123")
                .firstName("Hu")
                .lastName("Z")
                .paymentMethodNonce("3614a3fe-7503-0d1a-cfea-cad702094cc2");
        Result<Customer> result = gateway.customer().create(request);

        if(result.isSuccess()){
            Customer customer = result.getTarget();
            System.out.println(customer.getId());
            System.out.println(customer.getPaymentMethods().get(0).getToken());
        }else{
            System.out.println(result.getMessage());
        }
    }

    public static void saleByCustomerId(){
        TransactionRequest request = new TransactionRequest()
                .customerId("204871267")
                .amount(new BigDecimal("1.00"))
                .options()
                .submitForSettlement(true)
                .done();;

        Result<Transaction> result = gateway.transaction().sale(request);
        if (result.isSuccess()) {
            Transaction transaction = result.getTarget();
            System.out.println("Success ID: " + transaction.getId());
        } else {
            System.out.println("Message: " + result.getMessage());
        }
    }

    public static void saleByPaymentMethodToken(){
        TransactionRequest request = new TransactionRequest()
                .paymentMethodToken("16mv5t7k")
                .amount(new BigDecimal("10.00"))
                .options()
                .submitForSettlement(true)
                .done();

        Result<Transaction> result = gateway.transaction().sale(request);
        if (result.isSuccess()) {
            Transaction transaction = result.getTarget();
            System.out.println("Success ID: " + transaction.getId());
        } else {
            System.out.println("Message: " + result.getMessage());
        }
    }
}