PHP code example of vgspedro / vivaapi

1. Go to this page and download the library: Download vgspedro/vivaapi library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

vgspedro / vivaapi example snippets


namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

use App\Service\VivaWallet;

class PaymentController extends AbstractController
{
    private $environment;
    private $amount = 36812;

    public function __construct(ParameterBagInterface $environment)
    {
        $this->environment = $environment;
        $this->amount = 36812;
    }

    public function index(VivaWallet $viva)
    {

        return $this->render('admin/payment/native.html', [
            'amount' => $this->amount,
            'viva_token' => $viva->getCardChargeToken(),
            'sf_v' => \Symfony\Component\HttpKernel\Kernel::VERSION,
            'payment_url' => $this->environment->get("kernel.environment") == 'prod' ? 'https://www.vivapayments.com' : 'https://demo-api.vivapayments.com',
        ]);
    }


    /**
    * Make some transations accordind the "action" value from the form
    **/
    public function submit(Request $request, VivaWallet $viva)
    {       
        $pre_auth = $request->request->get('action') == 'authorization' ? false : true;

        $client = [
            'email' => $request->request->get('email'),
            'phone' => $request->request->get('phone'),
            'full_name' => $request->request->get('name'),
            'request_lang' => 'pt',
            'country_code' => 'PT'
        ];

        $transaction = [
            'amount' => $this->amount,
            'installments' => 1,
            'charge_token' => $request->request->get('token'),
            'merchant_trans' => 'Information to the Merchant',
            'customer_trans' => 'Information to the Client ' .$request->request->get('action'),
            'tip_amount' => 0,
            'pre_auth' => $pre_auth,
            'currency_code' => 978// https://pt.iban.com/currency-codes
        ];

        if($request->request->get('action') == 'charge'){
            $charge = $viva->setCharge($client, $transaction);
            //Something went wrong send info to user
            if ($charge['status'] == 0)
                return new JsonResponse([
                    'status' => 0,
                    'message' => $charge['data'],
                    'data' => $charge
                ]);

            return new JsonResponse([
                'status' => 1,
                'message' => $charge['data'],
                'data' => $trans
            ]);

        }
        
        else if($request->request->get('action') == 'authorization'){    
            $charge = $viva->setAutorization($client, $transaction);
            //Something went wrong send info to user
            if ($charge['status'] == 0)
                return new JsonResponse([
                    'status' => 0,
                    'message' => $charge['data'],
                    'data' => $charge
                ]);
            
            return new JsonResponse([
                'status' => 1,
                'message' => $charge['data'],
                'data' => $charge
            ]);

        }

        else if($request->request->get('action') == 'charge_capture'){
            $charge = $viva->setCharge($client, $transaction);
            //Something went wrong send info to user
            if ($charge['status'] == 0)
                return new JsonResponse([
                    'status' => 0,
                    'message' => $charge['data'],
                    'data' => $charge
                ]);
            
            $capture = $viva->setCapture($charge['data']->transactionId, $transaction['amount']);
            
            return new JsonResponse([
                'status' => 1,
                'message' => $capture['data'],
                'data' => $capture
            ]);
        }

        else if($request->request->get('action') == 'charge_cancel'){
            $charge = $viva->setCharge($client, $transaction);

            //Something went wrong send info to user
            if ($charge['status'] == 0)
                return new JsonResponse([
                    'status' => 0,
                    'message' => $charge['data'],
                    'data' => $charge
                ]);
            
            //
            $cancel = $viva->setCancel($charge['data']->transactionId, $transaction['amount']);
            
            return new JsonResponse([
                'status' => 1,
                'message' => $cancel['data'],
                'data' => $cancel
            ]);

        }

        //Something went wrong send info to user
            return new JsonResponse([
                'status' => 0,
                'message' => 'Not Processed',
                'data' => null
            ]);
    }

}



namespace App\Service;

use \VgsPedro\VivaApi\Transaction\Authorization;
use \VgsPedro\VivaApi\Transaction\Url;
use \VgsPedro\VivaApi\Transaction\Customer;
use \VgsPedro\VivaApi\Transaction\Charge;
use \VgsPedro\VivaApi\Transaction\Capture;
use \VgsPedro\VivaApi\Transaction\Cancel;
use \VgsPedro\VivaApi\Transaction\ChargeToken;
use \VgsPedro\VivaApi\Transaction\Installments;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class VivaWallet
{

	private $test_mode; // Boolean 
 	private $client_id; // Client ID, Provided by wallet
 	private $client_secret; // Client Secret, Provided by wallet
    private $url; // Url to make request, sandbox or live (sandbox APP_ENV=dev or test) (live APP_ENV=prod)
    private $merchant_id; //Merchant ID , Provided by wallet
    private $api_key; //Api Key, Provided by wallet
	private $headers; //Set the authorization to curl

    public function __construct(ParameterBagInterface $environment){
		$this->test_mode = true;
 		$this->client_id = 'ef7ee87mrt0grg62dbmwms0xzvu29owz5202f9b03ceo7.apps.vivapayments.com';
		$this->client_secret = '4M7ug3jfUh1wZ2Q442Y0L3MDxHz35E';
		$this->api_key = '71-}w%';
        $this->url = $environment->get("kernel.environment") == 'prod' ? 'https://www.vivapayments.com' : 'https://demo-api.vivapayments.com';
    }

	/**
	* Create an authentication Token to pass to client side js  
	* @return string $accessToken 
	**/
	public function getCardChargeToken(){

		$baseUrl = Url::getUrl($this->test_mode); //Test mode, default is false
		$accessToken = (new Authorization())
		->setClientId($this->client_id) // Client ID, Provided by wallet
		->setClientSecret($this->client_secret) // Client Secret, Provided by wallet
		->setTestMode($this->test_mode) // Test mode, default is false, can be skipped
		->getAccessToken();
		return $accessToken;
	}

	/**
	* Create a charge transaction
	*@param $client // Information of the user 
	*@param $trans // Information of the charge transaction 
	**/	
	public function setCharge(array $client, array $trans){

		$customer = (new Customer())
			->setEmail($client['email'])
			->setPhone($client['phone'])
			->setFullName($client['full_name'])
	      	->setRequestLang($client['request_lang'])
      		->setCountryCode($client['country_code']);

		$transaction = (new Charge())
			->setClientId($this->client_id) // Client ID, Provided by wallet
			->setClientSecret($this->client_secret) // Client Secret, Provided by wallet
			->setTestMode($this->test_mode) // Test mode, default is false, can be skipped
			->setSourceCode('') // Source code, provided by wallet
			->setAmount($trans['amount']) // The amount to charge in currency's smallest denomination (e.g amount in pounds x 100)
			->setInstallments($trans['installments']) // Installments, can be skipped if not used
			->setChargeToken($trans['charge_token']) // Charge token obtained at front end
 			->setMerchantTrns( $trans['merchant_trans'])
 			->setCustomerTrns($trans['customer_trans'])
			->setTipAmount($trans['tip_amount'])
			->setCustomer($customer)
			->setPreAuth($trans['pre_auth']); //If true, a PreAuth transaction will be performed. This will hold the selected amount as unavailable (without the customer being charged) for a period of time.

		$result = $transaction->send();

		if (!empty($transaction->getError()))
			return [
				'status' => 0,
				'data' => $transaction->getError()
			];
			
		return [
			'status' => 1,
			'data' => $result
		];
	}

	/**
	* Create a charge transaction, the amount is captured and charged. 
	*@param $client // Information of the user 
	*@param $trans // Information of the charge transaction 
	**/	
	public function setAutorization(array $client, array $trans){

		$customer = (new Customer())
			->setEmail($client['email'])
			->setPhone($client['phone'])
			->setFullName($client['full_name'])
	      	->setRequestLang($client['request_lang'])
      		->setCountryCode($client['country_code']);

		$transaction = (new Authorization())
			->setClientId($this->client_id) // Client ID, Provided by wallet
			->setClientSecret($this->client_secret) // Client Secret, Provided by wallet
			->setTestMode($this->test_mode) // Test mode, default is false, can be skipped
			->setSourceCode('') // Source code, provided by wallet
			->setAmount($trans['amount']) // The amount to pre-auth in currency's smallest denomination (e.g amount in pounds x 100)
			->setInstallments($trans['installments']) // Installments, can be skipped if not used
			->setChargeToken($trans['charge_token']) // Charge token obtained at front end
			->setCustomer($customer)
			->setPreAuth($trans['pre_auth']);//If true, a PreAuth transaction will be performed. This will hold the selected amount as unavailable (without the customer being charged) for a period of time.

		$result = $transaction->send();

		if (!empty($transaction->getError()))
			return [
				'status' => 0,
				'data' => $transaction->getError()
			];
			
		return [
			'status' => 1,
			'data' => $result
		];
	}


	/**
	* Capture a charge transaction
	*@param $t_i // Transaction id of authorization transaction
	*@param $amount // The amount to capture in currency's smallest denomination (e.g amount in pounds x 100)
	**/
	public function setCapture(string $t_i, int $amount){

		$transaction = (new Capture())
			->setClientId($this->client_id) // Client ID, Provided by wallet
			->setClientSecret($this->client_secret) // Client Secret, Provided by wallet
			->setTestMode($this->test_mode) // Test mode, default is false, can be skipped
			->setTransactionId($t_i) // Transaction id of authorization transaction
			->setAmount($amount); // The amount to capture in currency's smallest denomination (e.g amount in pounds x 100)

		$result = $transaction->send();

		if (!empty($transaction->getError()))
			return [
				'status' => 0,
				'data' => $transaction->getError()
			];
			
		return [
			'status' => 1,
			'data' => $result
		];
	}


	/**
	* Cancel a charge transaction
	*@param  $t_i // Transaction id of authorization transaction
	*@param $amount // The amount to capture in currency's smallest denomination (e.g amount in pounds x 100)
	**/
	public function setCancel(string $t_i, int $amount){

		$transaction = (new Cancel())
			->setClientId($this->client_id) // Client ID, Provided by wallet
			->setClientSecret($this->client_secret) // Client Secret, Provided by wallet
			->setTestMode($this->test_mode) // Test mode, default is false, can be skipped
			->setTransactionId($t_i) // Transaction id of authorization transaction
			->setAmount($amount)// The amount to capture in currency's smallest denomination (e.g amount in pounds x 100)
			->setSourceCode(''); // Source code, provided by wallet

		$result = $transaction->send();

		if (!empty($transaction->getError()))
			return [
				'status' => 0,
				'data' => $transaction->getError()
			];
			
		return [
			'status' => 1,
			'data' => $result
		];
	}



	/**
	* Is possible to get charge token at backend.
	* It may be