Saturday, July 15, 2017

BrainTree Payment API | Create Refund | Refund Payment

For merchant ID, public key and private key you can have a look at below link:

http://pritomkumar.blogspot.com/2017/07/braintree-create-payment-token-store.html


Below is full example given:


<?php
require_once "CurlExecutor.php";
require_once "BrainTreeUtils.php";
define("MERCHANT_ID", "k9y......xj6"); define("PUBLIC_KEY", "85....hh7"); define("PRIVATE_KEY", "510d5......................a00"); $array = array( "transaction" => array( 'amount' => "1.00", 'orderId' => htmlentities("REFUND_ID_" . time()) ) ); $base = "/transactions/6wex6xr6/refund"; $test = "https://api.sandbox.braintreegateway.com:443/merchants/" . MERCHANT_ID . $base; $live = "https://api.braintreegateway.com:443/merchants/" . MERCHANT_ID . $base; $headers[] = "Accept: application/xml"; $headers[] = "Content-Type: application/xml"; $headers[] = "X-ApiVersion: 4"; $closure = function(&$curl) { curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_USERPWD, PUBLIC_KEY . ':' . PRIVATE_KEY); }; $result = CurlExecutor::execute( $test, "POST", BrainTreeUtils::arrayToXml($array), null, $headers, $closure ); CurlExecutor::prettyPrint(BrainTreeUtils::arrayFromXml($result["response"]));

Response from BrainTree Payment Gateway:




Array
(
    [transaction] => Array
        (
            [id] => ka3reng4
            [status] => submitted_for_settlement
            [type] => credit
            [currencyIsoCode] => USD
            [amount] => 1.00
            [merchantAccountId] => fj3...........z2
            [subMerchantAccountId] => 
            [masterMerchantAccountId] => 
            [orderId] => REFUND_ID_1500098068
            [createdAt] => DateTime Object
                (
                    [date] => 2017-07-15 05:54:24.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [updatedAt] => DateTime Object
                (
                    [date] => 2017-07-15 05:54:24.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [customer] => Array
                (
                    [id] => 608968099
                    [firstName] => Pritom
                    [lastName] => Kumar
                    [company] => My Company
                    [email] => pritomkucse@gmail.com
                    [website] => 
                    [phone] => 33303030
                    [fax] => 
                )

            [billing] => Array
                (
                    [id] => vt
                    [firstName] => Pritom
                    [lastName] => Kumar
                    [company] => 
                    [streetAddress] => 
                    [extendedAddress] => 
                    [locality] => 
                    [region] => 
                    [postalCode] => 
                    [countryName] => 
                    [countryCodeAlpha2] => 
                    [countryCodeAlpha3] => 
                    [countryCodeNumeric] => 
                )

            [refundId] => 
            [refundIds] => Array
                (
                )

            [refundedTransactionId] => 6wex6xr6
            [partialSettlementTransactionIds] => Array
                (
                )

            [authorizedTransactionId] => 
            [settlementBatchId] => 
            [shipping] => Array
                (
                    [id] => 
                    [firstName] => 
                    [lastName] => 
                    [company] => 
                    [streetAddress] => 
                    [extendedAddress] => 
                    [locality] => 
                    [region] => 
                    [postalCode] => 
                    [countryName] => 
                    [countryCodeAlpha2] => 
                    [countryCodeAlpha3] => 
                    [countryCodeNumeric] => 
                )

            [customFields] => 
            [avsErrorResponseCode] => 
            [avsPostalCodeResponseCode] => A
            [avsStreetAddressResponseCode] => A
            [cvvResponseCode] => A
            [gatewayRejectionReason] => 
            [processorAuthorizationCode] => 
            [processorResponseCode] => 1002
            [processorResponseText] => Processed
            [additionalProcessorResponse] => 
            [voiceReferralNumber] => 
            [purchaseOrderNumber] => 
            [taxAmount] => 
            [taxExempt] => 
            [creditCard] => Array
                (
                    [token] => 6m76wy
                    [bin] => 444433
                    [last4] => 1111
                    [cardType] => Visa
                    [expirationMonth] => 12
                    [expirationYear] => 2018
                    [customerLocation] => US
                    [cardholderName] => Test
                    [imageUrl] => https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox
                    [prepaid] => Unknown
                    [healthcare] => Unknown
                    [debit] => Unknown
                    [durbinRegulated] => Unknown
                    [commercial] => Unknown
                    [payroll] => Unknown
                    [issuingBank] => Unknown
                    [countryOfIssuance] => Unknown
                    [productId] => Unknown
                    [uniqueNumberIdentifier] => 8a0a2661613868d36fbfde247bfaf06f
                    [venmoSdk] => 
                )

            [statusHistory] => Array
                (
                    [0] => Array
                        (
                            [timestamp] => DateTime Object
                                (
                                    [date] => 2017-07-15 05:54:24.000000
                                    [timezone_type] => 3
                                    [timezone] => UTC
                                )

                            [status] => submitted_for_settlement
                            [amount] => 1.00
                            [user] => j234lk2342342j3l4
                            [transactionSource] => api
                        )

                )

            [planId] => 
            [subscriptionId] => 
            [subscription] => Array
                (
                    [billingPeriodEndDate] => 
                    [billingPeriodStartDate] => 
                )

            [addOns] => Array
                (
                )

            [discounts] => Array
                (
                )

            [descriptor] => Array
                (
                    [name] => 
                    [phone] => 
                    [url] => 
                )

            [recurring] => 
            [channel] => 
            [serviceFeeAmount] => 
            [escrowStatus] => 
            [disbursementDetails] => Array
                (
                    [disbursementDate] => 
                    [settlementAmount] => 
                    [settlementCurrencyIsoCode] => 
                    [settlementCurrencyExchangeRate] => 
                    [fundsHeld] => 
                    [success] => 
                )

            [disputes] => Array
                (
                )

            [authorizationAdjustments] => Array
                (
                )

            [paymentInstrumentType] => credit_card
            [processorSettlementResponseCode] => 
            [processorSettlementResponseText] => 
            [threeDSecureInfo] => 
        )

)





BrainTree API | Create Payment | Create Payment Using Credit Card | Credit Card Payment

For merchant ID, public key and private key you can have a look at below link:

http://pritomkumar.blogspot.com/2017/07/braintree-create-payment-token-store.html

Below is a full PHP script:

'submitForSettlement' => true|false

The option that determines whether an authorized transaction is submitted for settlement.


<?php
require_once('CurlExecutor.php');
require_once "BrainTreeUtils.php";

define("MERCHANT_ID", "k......8xj6");
define("PUBLIC_KEY", "85......brhh7");
define("PRIVATE_KEY", "510d.............8a00");

$array = array(
    "transaction" => array(
        "type" => "sale",
        'amount' => "1.00",
        'orderId' => htmlentities("ORDER_ID_" . time()),
        'creditCard' => array(
            'cardholderName' => htmlentities("Test"),
            'number' => htmlentities("4444333322221111"),
            'expirationMonth' => htmlentities("12"),
            'expirationYear' => htmlentities("18")
        ),
        'options' => array(
            'submitForSettlement' => true
        )
) ); $test = "https://api.sandbox.braintreegateway.com:443/merchants/" . MERCHANT_ID . "/transactions"; $live = "https://api.braintreegateway.com:443/merchants/" . MERCHANT_ID . "/transactions"; $headers[] = "Accept: application/xml"; $headers[] = "Content-Type: application/xml"; $headers[] = "X-ApiVersion: 4"; $closure = function(&$curl) { curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_USERPWD, PUBLIC_KEY . ':' . PRIVATE_KEY); }; $result = CurlExecutor::execute( $test, "POST", BrainTreeUtils::arrayToXml($array), null, $headers, $closure ); CurlExecutor::prettyPrint(BrainTreeUtils::arrayFromXml($result["response"]));

And output/response from BrainTree API is below:

Screenshot:







Array
(
    [transaction] => Array
        (
            [id] => 1689k3ra
            [status] => authorized
            [type] => sale
            [currencyIsoCode] => USD
            [amount] => 1.00
            [merchantAccountId] => f........w8z2
            [subMerchantAccountId] => 
            [masterMerchantAccountId] => 
            [orderId] => ORDER_ID_1500093236
            [createdAt] => DateTime Object
                (
                    [date] => 2017-07-15 04:33:54.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [updatedAt] => DateTime Object
                (
                    [date] => 2017-07-15 04:33:54.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [customer] => Array
                (
                    [id] => 
                    [firstName] => 
                    [lastName] => 
                    [company] => 
                    [email] => 
                    [website] => 
                    [phone] => 
                    [fax] => 
                )

            [billing] => Array
                (
                    [id] => 
                    [firstName] => 
                    [lastName] => 
                    [company] => 
                    [streetAddress] => 
                    [extendedAddress] => 
                    [locality] => 
                    [region] => 
                    [postalCode] => 
                    [countryName] => 
                    [countryCodeAlpha2] => 
                    [countryCodeAlpha3] => 
                    [countryCodeNumeric] => 
                )

            [refundId] => 
            [refundIds] => Array
                (
                )

            [refundedTransactionId] => 
            [partialSettlementTransactionIds] => Array
                (
                )

            [authorizedTransactionId] => 
            [settlementBatchId] => 
            [shipping] => Array
                (
                    [id] => 
                    [firstName] => 
                    [lastName] => 
                    [company] => 
                    [streetAddress] => 
                    [extendedAddress] => 
                    [locality] => 
                    [region] => 
                    [postalCode] => 
                    [countryName] => 
                    [countryCodeAlpha2] => 
                    [countryCodeAlpha3] => 
                    [countryCodeNumeric] => 
                )

            [customFields] => 
            [avsErrorResponseCode] => 
            [avsPostalCodeResponseCode] => I
            [avsStreetAddressResponseCode] => I
            [cvvResponseCode] => I
            [gatewayRejectionReason] => 
            [processorAuthorizationCode] => 7NZ9S2
            [processorResponseCode] => 1000
            [processorResponseText] => Approved
            [additionalProcessorResponse] => 
            [voiceReferralNumber] => 
            [purchaseOrderNumber] => 
            [taxAmount] => 
            [taxExempt] => 
            [creditCard] => Array
                (
                    [token] => 
                    [bin] => 444433
                    [last4] => 1111
                    [cardType] => Visa
                    [expirationMonth] => 12
                    [expirationYear] => 2018
                    [customerLocation] => US
                    [cardholderName] => Test
                    [imageUrl] => https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox
                    [prepaid] => Unknown
                    [healthcare] => Unknown
                    [debit] => Unknown
                    [durbinRegulated] => Unknown
                    [commercial] => Unknown
                    [payroll] => Unknown
                    [issuingBank] => Unknown
                    [countryOfIssuance] => Unknown
                    [productId] => Unknown
                    [uniqueNumberIdentifier] => 
                    [venmoSdk] => 
                )

            [statusHistory] => Array
                (
                    [0] => Array
                        (
                            [timestamp] => DateTime Object
                                (
                                    [date] => 2017-07-15 04:33:54.000000
                                    [timezone_type] => 3
                                    [timezone] => UTC
                                )

                            [status] => authorized
                            [amount] => 1.00
                            [user] => j234lk2342342j3l4
                            [transactionSource] => api
                        )

                )

            [planId] => 
            [subscriptionId] => 
            [subscription] => Array
                (
                    [billingPeriodEndDate] => 
                    [billingPeriodStartDate] => 
                )

            [addOns] => Array
                (
                )

            [discounts] => Array
                (
                )

            [descriptor] => Array
                (
                    [name] => 
                    [phone] => 
                    [url] => 
                )

            [recurring] => 
            [channel] => 
            [serviceFeeAmount] => 
            [escrowStatus] => 
            [disbursementDetails] => Array
                (
                    [disbursementDate] => 
                    [settlementAmount] => 
                    [settlementCurrencyIsoCode] => 
                    [settlementCurrencyExchangeRate] => 
                    [fundsHeld] => 
                    [success] => 
                )

            [disputes] => Array
                (
                )

            [authorizationAdjustments] => Array
                (
                )

            [paymentInstrumentType] => credit_card
            [processorSettlementResponseCode] => 
            [processorSettlementResponseText] => 
            [threeDSecureInfo] => 
        )

)




BrainTree API | Create Payment | Create Payment Using Stored Token | Token Payment

For merchant ID, public key and private key you can have a look at below link:

http://pritomkumar.blogspot.com/2017/07/braintree-create-payment-token-store.html

Below is a full PHP script:

You can also specify "customerId" instead of "paymentMethodToken" in the below variable $array (filled red color) as:

"customerId" => "brain_tree_customer_id" and then default payment method of the selected customer will be used.

'submitForSettlement' => true|false

The option that determines whether an authorized transaction is submitted for settlement.


<?php
require_once('CurlExecutor.php');
require_once "BrainTreeUtils.php";

define("MERCHANT_ID", "k9yxxxxxxj6");
define("PUBLIC_KEY", "85xxxxxxrhh7");
define("PRIVATE_KEY", "510xxxxxxxxxxxxxxxxxxxx8a00");

$array = array(
    "transaction" => array(
        "type" => "sale",
        'amount' => "1.00",
        'paymentMethodToken' => "6m76wy",
        'orderId' => htmlentities("ORDER_ID_" . time()),
        'options' => array(
            'submitForSettlement' => true
        )
) ); $test = "https://api.sandbox.braintreegateway.com:443/merchants/" . MERCHANT_ID . "/transactions"; $live = "https://api.braintreegateway.com:443/merchants/" . MERCHANT_ID . "/transactions";
$headers[] = "Accept: application/xml";
$headers[] = "Content-Type: application/xml";
$headers[] = "X-ApiVersion: 4";
$closure = function(&$curl) {
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, PUBLIC_KEY . ':' . PRIVATE_KEY);
};
$result = CurlExecutor::execute(
    $test, "POST", BrainTreeUtils::arrayToXml($array),
    null, $headers, $closure
);
CurlExecutor::prettyPrint(BrainTreeUtils::arrayFromXml($result["response"]));

And output/response from BrainTree API is below:

Screenshot:







Array
(
    [transaction] => Array
        (
            [id] => jztnv4pr
            [status] => Submitted For Settlement
            [type] => sale
            [currencyIsoCode] => USD
            [amount] => 1.00
            [merchantAccountId] => fj3............z2
            [subMerchantAccountId] => 
            [masterMerchantAccountId] => 
            [orderId] => ORDER_ID_1500087430
            [createdAt] => DateTime Object
                (
                    [date] => 2017-07-15 02:57:06.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [updatedAt] => DateTime Object
                (
                    [date] => 2017-07-15 02:57:06.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [customer] => Array
                (
                    [id] => 608968099
                    [firstName] => Pritom
                    [lastName] => Kumar
                    [company] => My Company
                    [email] => pritomkucse@gmail.com
                    [website] => 
                    [phone] => 33303030
                    [fax] => 
                )

            [billing] => Array
                (
                    [id] => vt
                    [firstName] => Pritom
                    [lastName] => Kumar
                    [company] => 
                    [streetAddress] => 
                    [extendedAddress] => 
                    [locality] => 
                    [region] => 
                    [postalCode] => 
                    [countryName] => 
                    [countryCodeAlpha2] => 
                    [countryCodeAlpha3] => 
                    [countryCodeNumeric] => 
                )

            [refundId] => 
            [refundIds] => Array
                (
                )

            [refundedTransactionId] => 
            [partialSettlementTransactionIds] => Array
                (
                )

            [authorizedTransactionId] => 
            [settlementBatchId] => 
            [shipping] => Array
                (
                    [id] => 
                    [firstName] => 
                    [lastName] => 
                    [company] => 
                    [streetAddress] => 
                    [extendedAddress] => 
                    [locality] => 
                    [region] => 
                    [postalCode] => 
                    [countryName] => 
                    [countryCodeAlpha2] => 
                    [countryCodeAlpha3] => 
                    [countryCodeNumeric] => 
                )

            [customFields] => 
            [avsErrorResponseCode] => 
            [avsPostalCodeResponseCode] => I
            [avsStreetAddressResponseCode] => I
            [cvvResponseCode] => I
            [gatewayRejectionReason] => 
            [processorAuthorizationCode] => 6CWKNZ
            [processorResponseCode] => 1000
            [processorResponseText] => Approved
            [additionalProcessorResponse] => 
            [voiceReferralNumber] => 
            [purchaseOrderNumber] => 
            [taxAmount] => 
            [taxExempt] => 
            [creditCard] => Array
                (
                    [token] => 6m76wy
                    [bin] => 444433
                    [last4] => 1111
                    [cardType] => Visa
                    [expirationMonth] => 12
                    [expirationYear] => 2018
                    [customerLocation] => US
                    [cardholderName] => Test
                    [imageUrl] => https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox
                    [prepaid] => Unknown
                    [healthcare] => Unknown
                    [debit] => Unknown
                    [durbinRegulated] => Unknown
                    [commercial] => Unknown
                    [payroll] => Unknown
                    [issuingBank] => Unknown
                    [countryOfIssuance] => Unknown
                    [productId] => Unknown
                    [uniqueNumberIdentifier] => 8a0a266..............faf06f
                    [venmoSdk] => 
                )

            [statusHistory] => Array
                (
                    [0] => Array
                        (
                            [timestamp] => DateTime Object
                                (
                                    [date] => 2017-07-15 02:57:06.000000
                                    [timezone_type] => 3
                                    [timezone] => UTC
                                )

                            [status] => authorized
                            [amount] => 1.00
                            [user] => j234lk2342342j3l4
                            [transactionSource] => api
                        )

                )

            [planId] => 
            [subscriptionId] => 
            [subscription] => Array
                (
                    [billingPeriodEndDate] => 
                    [billingPeriodStartDate] => 
                )

            [addOns] => Array
                (
                )

            [discounts] => Array
                (
                )

            [descriptor] => Array
                (
                    [name] => 
                    [phone] => 
                    [url] => 
                )

            [recurring] => 
            [channel] => 
            [serviceFeeAmount] => 
            [escrowStatus] => 
            [disbursementDetails] => Array
                (
                    [disbursementDate] => 
                    [settlementAmount] => 
                    [settlementCurrencyIsoCode] => 
                    [settlementCurrencyExchangeRate] => 
                    [fundsHeld] => 
                    [success] => 
                )

            [disputes] => Array
                (
                )

            [authorizationAdjustments] => Array
                (
                )

            [paymentInstrumentType] => credit_card
            [processorSettlementResponseCode] => 
            [processorSettlementResponseText] => 
            [threeDSecureInfo] => 
        )

)




Friday, July 14, 2017

BrainTree: Create Payment Token | Store Credit Card Details | Create Customer | Create Credit Card Token | Create Payment Method

The very step to create an account in BrainTree. And then need to create an user and then application. 

1. Visit https://sandbox.braintreegateway.com
2. Click on "Settings" -> "Users and roles" and then click "New User" to create a new user.



3. Now click "Account" -> "My User" and then "View Authorizations".



4. Now click on "Generate New API Key" to create an API key. Copy "Public Key" and "Private Key".



5. What we need to communicate with BrainTree API in our hand now. Now its time to communicate with BrainTree API.

Below is a screenshot to show how you can collect your Merchant ID:




And below PHP script is full example how to create token in BrainTree portal:


<?php
require_once('CurlExecutor.php');
require_once "BrainTreeUtils.php";
define("MERCHANT_ID", "kxxxxnxxxxxxxx");
define("PUBLIC_KEY", "85dspxxxxxxxxxx");
define("PRIVATE_KEY", "510d5b5b672xxxxxxxxxxxxxxxxxxx");

$array = array(
    "customer" => array(
        'firstName' => htmlentities("Pritom"),
        'lastName' => htmlentities("Kumar"),
        'company' => htmlentities("My Company"),
        'email' => htmlentities("pritomkucse@gmail.com"),
        'phone' => htmlentities("33303030"),

        'creditCard' => array(
            'cardholderName' => htmlentities("Test"),
            'number' => htmlentities("4444333322221111"),
            'expirationMonth' => htmlentities("12"),
            'expirationYear' => htmlentities("18"),
            'cvv' => htmlentities("354"),
            'billingAddress' => array(
                'firstName' => htmlentities("Pritom"),
                'lastName' => htmlentities("Kumar")
            )
        )
    )
);

$test = "https://api.sandbox.braintreegateway.com:443/merchants/" . MERCHANT_ID . "/customers";
$live = "https://api.braintreegateway.com:443/merchants/" . MERCHANT_ID . "/customers";
$headers[] = "Accept: application/xml";
$headers[] = "Content-Type: application/xml";
$headers[] = "X-ApiVersion: 4";
$closure = function(&$curl) {
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, PUBLIC_KEY . ':' . PRIVATE_KEY);
};
$result = CurlExecutor::execute(
    $test, "POST", BrainTreeUtils::arrayToXml($array),
    null, $headers, $closure
);
CurlExecutor::prettyPrint(BrainTreeUtils::arrayFromXml($result["response"]));

And successful output of above script is below. From the response below you have to store customer id and token for further use of customer to update, add new payment method, create payment etc...


Array
(
    [customer] => Array
        (
            [id] => 608968099
            [merchantId] => k9yxxxxxxxxxxxx6
            [firstName] => Pritom
            [lastName] => Kumar
            [company] => My Company
            [email] => pritomkucse@gmail.com
            [phone] => 33303030
            [fax] => 
            [website] => 
            [createdAt] => DateTime Object
                (
                    [date] => 2017-07-14 16:44:33.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [updatedAt] => DateTime Object
                (
                    [date] => 2017-07-14 16:44:33.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [customFields] => 
            [creditCards] => Array
                (
                    [0] => Array
                        (
                            [billingAddress] => Array
                                (
                                    [id] => vt
                                    [customerId] => 608968099
                                    [firstName] => Pritom
                                    [lastName] => Kumar
                                    [company] => 
                                    [streetAddress] => 
                                    [extendedAddress] => 
                                    [locality] => 
                                    [region] => 
                                    [postalCode] => 
                                    [countryCodeAlpha2] => 
                                    [countryCodeAlpha3] => 
                                    [countryCodeNumeric] => 
                                    [countryName] => 
                                    [createdAt] => DateTime Object
                                        (
                                            [date] => 2017-07-14 16:44:33.000000
                                            [timezone_type] => 3
                                            [timezone] => UTC
                                        )

                                    [updatedAt] => DateTime Object
                                        (
                                            [date] => 2017-07-14 16:44:33.000000
                                            [timezone_type] => 3
                                            [timezone] => UTC
                                        )

                                )

                            [bin] => 444433
                            [cardType] => Visa
                            [cardholderName] => Test
                            [commercial] => Unknown
                            [countryOfIssuance] => Unknown
                            [createdAt] => DateTime Object
                                (
                                    [date] => 2017-07-14 16:44:33.000000
                                    [timezone_type] => 3
                                    [timezone] => UTC
                                )

                            [customerId] => 608968099
                            [customerLocation] => US
                            [debit] => Unknown
                            [default] => 1
                            [durbinRegulated] => Unknown
                            [expirationMonth] => 12
                            [expirationYear] => 2018
                            [expired] => 
                            [healthcare] => Unknown
                            [imageUrl] => https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox
                            [issuingBank] => Unknown
                            [last4] => 1111
                            [payroll] => Unknown
                            [prepaid] => Unknown
                            [productId] => Unknown
                            [subscriptions] => Array
                                (
                                )

                            [token] => 6m76wy
                            [uniqueNumberIdentifier] => 8a0xxxxxxxxxxxxxxxxxxxxxxf06f
                            [updatedAt] => DateTime Object
                                (
                                    [date] => 2017-07-14 16:44:33.000000
                                    [timezone_type] => 3
                                    [timezone] => UTC
                                )

                            [venmoSdk] => 
                            [verifications] => Array
                                (
                                )

                        )

                )

            [addresses] => Array
                (
                    [0] => Array
                        (
                            [id] => vt
                            [customerId] => 608968099
                            [firstName] => Pritom
                            [lastName] => Kumar
                            [company] => 
                            [streetAddress] => 
                            [extendedAddress] => 
                            [locality] => 
                            [region] => 
                            [postalCode] => 
                            [countryCodeAlpha2] => 
                            [countryCodeAlpha3] => 
                            [countryCodeNumeric] => 
                            [countryName] => 
                            [createdAt] => DateTime Object
                                (
                                    [date] => 2017-07-14 16:44:33.000000
                                    [timezone_type] => 3
                                    [timezone] => UTC
                                )

                            [updatedAt] => DateTime Object
                                (
                                    [date] => 2017-07-14 16:44:33.000000
                                    [timezone_type] => 3
                                    [timezone] => UTC
                                )

                        )

                )

        )

)

And below is screenshot to show that token created on BrainTree end:





Strip HTML Entities | Remove HTML Tags From String | Stripping HTML Tags in Java | Remove Html Tags From String Using Java | Java: RegEx To Remove HTML Tags

I am writing one program which reads text contents from file. Now I am reading it using bufferedreader class of java. I am able to remove any unwanted characters like '(' or '.' etc, using replaceAll() method. But I want to remove html tags too like "div", "span", "p" and many others like this, including &amp. How to achieve this? Is there a good way to remove HTML from a Java string? Yes, we can using regex. Below is full example written in Java to strip html entities from text.

Full java code example is below:


package com.pkm;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author PRITOM K MONDAL
 */
public class StripHtmlTags {
    private static final String emptyTag = "<[a-zA-Z0-9]+[^>]+>|</[a-zA-Z0-9]+>";
    private static final String commentTag = "<!--(.*?)-->";
    private static final String docTypeTag = "<![a-zA-Z0-9]+(.*?)>";

    public static void main(String[] args) throws Exception {
        File source = new File("html.txt");
        String text = new String(readObjectFromFile(source), "UTF-8");
        //text = "<p-if case='n=1'>TESTED_N_EQ_1</p-if>";
        text = parse(text);
        println("-------------------------------");
        println(text);
        println("-------------------------------");
    }

    private static String parse(String text) throws Exception {
        text = text.replace("\r\n", "").replace("\n", "").replace("&nbsp;", " ");
        text = replaceDocTypeTags(text);
        text = replaceCommentTags(text);
        text = replaceScriptTags(text);
        text = replaceContentTags(text);  
        text = replaceEmptyTags(text);      
        return text.replaceAll("\\s+", " ").trim();
    }
    
    private static String replaceScriptTags(String text) {
        Pattern p = Pattern.compile("(<(?<tag>(script|style))[^>]*>(?>[^<])*<\\/\\k<tag>\\s*>)", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(text);
        StringBuffer output = new StringBuffer();
        boolean trigger = false;
        while(m.find()){
            String find = m.group(0), tag = m.group(2);
            m.appendReplacement(output, " ");
            trigger = true;
        }
        m.appendTail(output);
        if (trigger) {
            return replaceScriptTags(output.toString());
        }
        return output.toString().replaceAll("\\s+", " ").trim();
    }

    private static String replaceDocTypeTags(String text) {
        try {
            StringBuffer output = new StringBuffer();
            Pattern pattern = Pattern.compile(docTypeTag, Pattern.MULTILINE);
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                matcher.appendReplacement(output, " ");
            }
            matcher.appendTail(output);
            return output.toString().trim();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return text;
    }

    private static String replaceCommentTags(String text) {
        try {
            StringBuffer output = new StringBuffer();
            Pattern pattern = Pattern.compile(commentTag, Pattern.MULTILINE);
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                matcher.appendReplacement(output, " ");
            }
            matcher.appendTail(output);
            return output.toString().trim();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return text;
    }

    private static String replaceContentTags(String text) {
        Pattern p = Pattern.compile("(<(?<tag>\\w+)[^>]*>(?>[^<])*<\\/\\k<tag>\\s*>)", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(text);
        StringBuffer output = new StringBuffer();
        boolean trigger = false;
        while(m.find()){
            String find = m.group(0), tag = m.group(2);
            if (tag != null) {
                find = find.substring(find.indexOf(">") + 1, find.length() - tag.length() - 3);
                m.appendReplacement(output, " " + Matcher.quoteReplacement(find) + " ");
            }
            else {
                m.appendReplacement(output, " ");
            }
            trigger = true;
        }
        m.appendTail(output);
        if (trigger) {
            return replaceContentTags(output.toString());
        }
        return output.toString();
    }

    private static String replaceEmptyTags(String text) {
        try {
            StringBuffer output = new StringBuffer();
            Pattern pattern = Pattern.compile(emptyTag, Pattern.MULTILINE);
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                matcher.appendReplacement(output, " ");
            }
            matcher.appendTail(output);
            return output.toString().trim();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return text;
    }

    private static byte[] readObjectFromFile(File source) throws Exception {
        int size = (int) source.length();
        byte[] bytes = new byte[size];
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(source));
        inputStream.read(bytes, 0, bytes.length);
        inputStream.close();
        return bytes;
    }
    
    private static void println(Object o) {
        System.out.println("" + o);
    }
}

I used below html as example:


<div class="m_2691871633108987921InfoContent"><div style="margin:auto;max-width:48em" class="m_2691871633108987921box m_2691871633108987921dark">Pritom you are getting this message as free service for being a user of the PHP Classes site to which you registered voluntarily using the email address <a href="mailto:pritomkucse@gmail.com" target="_blank">pritomkucse@gmail.com</a>. If you wish to unsubscribe go to the <a href="https://www.phpclasses.org/unsub/n/pritomkumarm/u/newclasses/cc/8d4da9/" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;q=https://www.phpclasses.org/unsub/n/pritomkumarm/u/newclasses/cc/8d4da9/&amp;source=gmail&amp;ust=1500128983383000&amp;usg=AFQjCNHdGC4JMTFZL4gunLN5iEeeo-H7fA">unsubscribe page</a>.</div>
<ul>
<table cellpadding="0" cellspacing="0">
<tbody><tr>
<td valign="top" style="padding:0"><h2>Class:</h2>
<div><b><a href="https://www.phpclasses.org/package/10378.html" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;q=https://www.phpclasses.org/package/10378.html&amp;source=gmail&amp;ust=1500128983383000&amp;usg=AFQjCNGoRBbTEuOrPMzCnTA8hSMocBh0bA">AJAX Form Validate</a></b><br><a href="https://www.phpclasses.org/discuss/package/10378/" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;q=https://www.phpclasses.org/discuss/package/10378/&amp;source=gmail&amp;ust=1500128983383000&amp;usg=AFQjCNF-oSc-24S0hUUr873Yu-o0afYlMg">This class support forum</a></div>
<h2>Short description:</h2>
<div>
Render and validate forms submitted via AJAX</div>
<h2>Groups:</h2>
<div>
PHP 5, Validation, AJAX</div>
</td>
<td valign="top" width="1%"></td>
</tr>
</tbody></table>
<h2>Supplied by:</h2><div>Vishv Sahdev</div>
<h2>Detailed description:</h2>
<div>This class can render and validate forms submitted via AJAX.<br>
<br>
It can render HTML forms using templates that take assigned variable values passed to the class as an array.<br>
<br>
The class can also validate a submitted form inputs according to many possible validation rules.<br>
<br>
If there are validation errors, the class will generate a JSON response to the AJAX request to display</div>
</ul>
<ul>
<h2>PHP Classes site tip of the day:</h2>
<div><p><b><big><a href="https://www.phpclasses.org/tips.html?tip=submit-your-components" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;q=https://www.phpclasses.org/tips.html?tip%3Dsubmit-your-components&amp;source=gmail&amp;ust=1500128983383000&amp;usg=AFQjCNGyBzcYnZHB_Trk3N_EycwWu5PS3g">Get feedback and recognition submitting your PHP components</a></big></b></p>
</div>
</ul>
<div style="margin:auto;max-width:48em" class="m_2691871633108987921box m_2691871633108987921dark">Pritom if you are not interested in receiving any more messages like this one, go to the <a href="https://www.phpclasses.org/unsub/n/pritomkumarm/u/newclasses/cc/8d4da9/" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;q=https://www.phpclasses.org/unsub/n/pritomkumarm/u/newclasses/cc/8d4da9/&amp;source=gmail&amp;ust=1500128983383000&amp;usg=AFQjCNHdGC4JMTFZL4gunLN5iEeeo-H7fA">unsubscribe page</a> .</div>

</div>


And my java code parse as below string:

Pritom you are getting this message as free service for being a user of the PHP Classes site to which you registered voluntarily using the email address pritomkucse@gmail.com . If you wish to unsubscribe go to the unsubscribe page . Class: AJAX Form Validate This class support forum Short description: Render and validate forms submitted via AJAX Groups: PHP 5, Validation, AJAX Supplied by: Vishv Sahdev Detailed description: This class can render and validate forms submitted via AJAX. It can render HTML forms using templates that take assigned variable values passed to the class as an array. The class can also validate a submitted form inputs according to many possible validation rules. If there are validation errors, the class will generate a JSON response to the AJAX request to display PHP Classes site tip of the day: Get feedback and recognition submitting your PHP components Pritom if you are not interested in receiving any more messages like this one, go to the unsubscribe page .

Tuesday, July 11, 2017

Laravel 5: Get Controller Name in View | Route Details | Controller & Action Name | Route Parameters

You can create a view composer that injects those variables into your view file. In "app/Providers/AppServiceProvider.php" add something like this:

public function boot()
{
    //app('view')->composer("folder.specific_view_name", function ($view) {
    app('view')->composer("*", function ($view) {
        $action = app("request")->route()->getAction();

        $controller = class_basename($action["controller"]);

        list($controller_name, $action_name) = explode("@", $controller);

        $view->with(compact("controller_name", "action_name"));
    });
}

You also can parameters from current request as below:

app('request')->route()->parameters()

Array
(
    [middleware] => web
    [as] => folder.view_name
    [uses] => App\Http\Controllers\UserController@show
    [controller] => App\Http\Controllers\UserController@show
    [namespace] => App\Http\Controllers
    [prefix] => 
    [where] => Array
        (
        )


)


Thursday, July 6, 2017

Laravel 5: Logging All DB Query | Log Queries | Listen Query Events | Query Logging | Sql Logging | Log SQL | DB Connection Class | Laravel Database Connection | Laravel DB Connection Query Run Method

Laravel 5: Logging All DB Query | Log Queries | Listen Query Events | Query Logging | Sql Logging | Log SQL | DB Connection Class | Laravel Database Connection | Laravel DB Connection Query Run Method.

Logging query in Laravel is easy. You can then register event listener for DB. At first you need to create an service provider in directory ("project/app/Providers" ) named QueryLogProvider with following contents:


<?php
namespace App\Providers;

use Monolog\Logger;
use Illuminate\Support\Facades\DB;
use Monolog\Handler\StreamHandler;
use Illuminate\Support\ServiceProvider;

class QueryLogProvider extends ServiceProvider
{
    public function register()
    {
        DB::listen(function ($query) {
            $logFile = storage_path('logs/query-log-'.date("Y-m-d").'.log');
            $stream = new Logger('log');
            $stream->pushHandler(new StreamHandler($logFile));
            $bindings = $query->bindings;
            $time = $query->time;
            $stream->info($query->sql, compact('bindings', 'time'));
        });
    }
}

You are done with creating provider. Now you have to register in file "project/config/app.php" in section 


'providers' => [
    .....,
    App\Providers\QueryLogProvider::class
],

All your queries will be stored on the location "project/storage/logs" with prefix file name "query-log".

But you can do some wired things, editing source code. To do so first need to open your connection class:

Illuminate\Database\Connection

and navigate to function:

protected function run($query, $bindings, Closure $callback)

actually all query in Laravel passed through this method.

So you can do whatever you wish to do here.