Inheritance: extends PHPUnit_Util_Printer, implements PHPUnit_Framework_TestListener, use trait Bartlett\LoggerTestListenerTrait, use trait Psr\Log\LoggerAwareTrait, use trait GetOpt
Esempio n. 1
0
 /**
  * Register the search and page state of this collection so that the
  * next time that we return to it, we will get the same view.
  * 
  * @return void
  * @access public
  * @since 5/11/06
  */
 function registerState()
 {
     $this->_state = $this->getState($this->getAssetId());
     // unset our starting number if we have the new search terms
     if (RequestContext::value('form_submitted') || isset($_REQUEST[ResultPrinter::startingNumberParam()]) || !isset($this->_state['numPerPage']) || $this->_state['numPerPage'] != $_SESSION['assets_per_page']) {
         $this->_state['startingNumber'] = ResultPrinter::startingNumberParam();
         $this->_state['numPerPage'] = $_SESSION['assets_per_page'];
     } else {
         if (!isset($this->_state['startingNumber'])) {
             $this->_state['startingNumber'] = 1;
             $this->_state['numPerPage'] = $_SESSION['assets_per_page'];
         }
     }
 }
Esempio n. 2
0
function getInvoiceDetails($invoiceNumber, $apiContext, $paypal)
{
    try {
        $invoice = Invoice::get($invoiceNumber, $apiContext);
    } catch (Exception $ex) {
        ResultPrinter::printError("Get Invoice", "Invoice", $invoice->getId(), $invoiceId, $ex);
        exit(1);
    }
    $taxSum = 0;
    foreach ($invoice->getItems() as $item) {
        if ($item->getTax()) {
            $taxSum += $item->getTax()->getAmount()->getValue();
        }
    }
    $tID = 0;
    //This is the key value to hook up with the classis paypal API
    $tID = $paypal->request($invoice->getPayments()['0']->getTransactionId())['L_TRANSACTIONID0'];
    return array('date' => $invoice->getPayments()['0']->getDate(), 'memo' => $invoice->getMerchantMemo(), 'number' => $invoice->getNumber(), 'tax' => $taxSum, 'tID' => $tID);
}
Esempio n. 3
0
<?php

// # Get WebHook
// This sample code demonstrate how you can get a webhook, as documented here at:
// <a href="http://dev.blockcypher.com/#webhooks">Using webhooks</a>
//
// API used: GET /v1/btc/main/hooks/WebHook-Id
// ## Create Sample WebHook
// In samples we are using CreateWebHook.php sample to get the created instance of webhook.
// However, in real case scenario, we could use just the ID.
/** @var \BlockCypher\Api\WebHook $webHook */
$webHook = (require 'CreateWebHook.php');
$webHookId = $webHook->getId();
$webHookClient = new \BlockCypher\Client\WebHookClient($apiContexts['BTC.main']);
// ## Get WebHook by Id
try {
    /// Get WebHook by Id
    $output = $webHookClient->get($webHookId);
} catch (Exception $ex) {
    ResultPrinter::printError("Get a WebHook", "WebHook", null, $webHookId, $ex);
    exit(1);
}
ResultPrinter::printResult("Get a WebHook", "WebHook", $output->getId(), null, $output);
return $output;
// Please note that the plan Id should be only set in this case.
$plan = new Plan();
$plan->setId($createdPlan->getId());
$agreement->setPlan($plan);
// Add Payer
$payer = new Payer();
$payer->setPaymentMethod('credit_card')->setPayerInfo(new PayerInfo(array('email' => '*****@*****.**')));
// Add Credit Card to Funding Instruments
$creditCard = new CreditCard();
$creditCard->setType('visa')->setNumber('4491759698858890')->setExpireMonth('12')->setExpireYear('2017')->setCvv2('128');
$fundingInstrument = new FundingInstrument();
$fundingInstrument->setCreditCard($creditCard);
$payer->setFundingInstruments(array($fundingInstrument));
//Add Payer to Agreement
$agreement->setPayer($payer);
// Add Shipping Address
$shippingAddress = new ShippingAddress();
$shippingAddress->setLine1('111 First Street')->setCity('Saratoga')->setState('CA')->setPostalCode('95070')->setCountryCode('US');
$agreement->setShippingAddress($shippingAddress);
// For Sample Purposes Only.
$request = clone $agreement;
// ### Create Agreement
try {
    // Please note that as the agreement has not yet activated, we wont be receiving the ID just yet.
    $agreement = $agreement->create($apiContext);
} catch (Exception $ex) {
    ResultPrinter::printError("Created Billing Agreement.", "Agreement", $agreement->getId(), $request, $ex);
    exit(1);
}
ResultPrinter::printResult("Created Billing Agreement.", "Agreement", $agreement->getId(), $request, $agreement);
return $agreement;
<?php

// # Remove Addresses from Wallet
//
// This sample code demonstrate how you can removes addresses from a wallet, as documented here at:
// <a href="http://dev.blockcypher.com/#wallets">http://dev.blockcypher.com/#wallets</a>
//
// API used: DELETE /v1/btc/main/wallets/Wallet-Name/addresses?address=13cj1Qtf...gQiRM6j
// In samples we are using CreateWallet.php sample to get the created instance of wallet
// and AddAddressesToWallet to add the address which is going to be removed.
// You have to run that sample before running this one.
require __DIR__ . '/../bootstrap.php';
if (isset($_GET['wallet_name'])) {
    $walletName = filter_input(INPUT_GET, 'wallet_name', FILTER_SANITIZE_SPECIAL_CHARS);
} else {
    $walletName = 'alice';
    // Default wallet name for samples
}
$walletClient = new \BlockCypher\Client\WalletClient($apiContexts['BTC.main']);
/// List of addresses to be removed from the wallet
$addressList = \BlockCypher\Api\AddressList::fromAddressesArray(array("13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j"));
try {
    /// Remove addresses from wallet
    $output = $walletClient->removeAddresses($walletName, $addressList);
} catch (Exception $ex) {
    ResultPrinter::printError("Remove Addresses from a Wallet", "Wallet", $walletName, $addressList, $ex);
    exit(1);
}
ResultPrinter::printResult("Remove Addresses from a Wallet", "Wallet", $walletName, $addressList, $output);
return $output;
Esempio n. 6
0
function execute_payment_test()
{
    $apiContext = $GLOBALS['PAYPAL']['api_context'];
    // ### Approval Status
    // Determine if the user approved the payment or not
    if (isset($_GET['success']) && $_GET['success'] == 'true') {
        // Get the payment Object by passing paymentId
        // payment id was previously stored in session in
        // CreatePaymentUsingPayPal.php
        $paymentId = $_GET['paymentId'];
        $payment = Payment::get($paymentId, $apiContext);
        // ### Payment Execute
        // PaymentExecution object includes information necessary
        // to execute a PayPal account payment.
        // The payer_id is added to the request query parameters
        // when the user is redirected from paypal back to your site
        $execution = new PaymentExecution();
        $execution->setPayerId($_GET['PayerID']);
        // ### Optional Changes to Amount
        // If you wish to update the amount that you wish to charge the customer,
        // based on the shipping address or any other reason, you could
        // do that by passing the transaction object with just `amount` field in it.
        // Here is the example on how we changed the shipping to $1 more than before.
        // $transaction = new Transaction();
        // $amount = new Amount();
        // $details = new Details();
        // $details->setShipping(2.2)
        //     ->setTax(1.3)
        //     ->setSubtotal(17.50);
        // $amount->setCurrency('USD');
        // $amount->setTotal(21);
        // $amount->setDetails($details);
        // $transaction->setAmount($amount);
        // Add the above transaction object inside our Execution object.
        // $execution->addTransaction($transaction);
        try {
            // Execute the payment
            // (See bootstrap.php for more on `ApiContext`)
            $result = $payment->execute($execution, $apiContext);
            // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
            ResultPrinter::printResult("Executed Payment", "Payment", $payment->getId(), $execution, $result);
            try {
                $payment = Payment::get($paymentId, $apiContext);
            } catch (Exception $ex) {
                // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
                ResultPrinter::printError("Get Payment", "Payment", null, null, $ex);
                exit(1);
            }
        } catch (Exception $ex) {
            // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
            ResultPrinter::printError("Executed Payment", "Payment", null, null, $ex);
            exit(1);
        }
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printResult("Get Payment", "Payment", $payment->getId(), null, $payment);
        return $payment;
    } else {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printResult("User Cancelled the Approval", null);
        exit;
    }
}
<?php

// # Get Billing Agreement Sample
//
// This sample code demonstrate how you can get a billing agreement, as documented here at:
// https://developer.paypal.com/webapps/developer/docs/api/#retrieve-an-agreement
// API used: /v1/payments/billing-agreements/<Agreement-Id>
// Retrieving the Agreement object from Create Agreement From Credit Card Sample
/** @var Agreement $createdAgreement */
$createdAgreement = (require 'CreateBillingAgreementWithCreditCard.php');
use PayPal\Api\Agreement;
try {
    $agreement = Agreement::get($createdAgreement->getId(), $apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Retrieved an Agreement", "Agreement", $agreement->getId(), $createdAgreement->getId(), $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Retrieved an Agreement", "Agreement", $agreement->getId(), $createdAgreement->getId(), $agreement);
return $agreement;
Esempio n. 8
0
$billingInfo = $invoice->getBillingInfo()[0];
$billingInfo->setAddress(null);
$invoice->getPaymentTerm()->setDueDate(null);
try {
    // ### Update Invoice
    // Update an invoice by calling the invoice->update() method
    // with a valid ApiContext (See bootstrap.php for more on `ApiContext`)
    $invoice->update($apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Invoice Updated", "Invoice", null, $request, $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Invoice Updated", "Invoice", $invoice->getId(), $request, $invoice);
// ### Retrieve Invoice
// Retrieve the invoice object by calling the
// static `get` method
// on the Invoice class by passing a valid
// Invoice ID
// (See bootstrap.php for more on `ApiContext`)
try {
    $invoice = Invoice::get($invoice->getId(), $apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Get Invoice (Not Required - For Sample Only)", "Invoice", $invoice->getId(), $invoice->getId(), $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Get Invoice (Not Required - For Sample Only)", "Invoice", $invoice->getId(), $invoice->getId(), $invoice);
return $invoice;
// # Update a plan
//
// This sample code demonstrate how you can update a billing plan, as documented here at:
// https://developer.paypal.com/webapps/developer/docs/api/#update-a-plan
// API used:  /v1/payments/billing-plans/<Plan-Id>
// ### Making Plan Active
// This example demonstrate how you could activate the Plan.
// Retrieving the Plan object from Create Plan Sample to demonstrate the List
/** @var Plan $createdPlan */
$createdPlan = (require 'CreatePlan.php');
use PayPal\Api\Plan;
use PayPal\Api\PatchRequest;
use PayPal\Api\Patch;
use PayPal\Common\PayPalModel;
try {
    $patch = new Patch();
    $value = new PayPalModel('{
	       "state":"ACTIVE"
	     }');
    $patch->setOp('replace')->setPath('/')->setValue($value);
    $patchRequest = new PatchRequest();
    $patchRequest->addPatch($patch);
    $createdPlan->update($patchRequest, $apiContext);
    $plan = Plan::get($createdPlan->getId(), $apiContext);
} catch (Exception $ex) {
    ResultPrinter::printError("Updated the Plan to Active State", "Plan", null, $patchRequest, $ex);
    exit(1);
}
ResultPrinter::printResult("Updated the Plan to Active State", "Plan", $plan->getId(), $patchRequest, $plan);
return $plan;
<?php

// Run on console:
// php -f .\sample\transaction-api\PushRawTransactionEndpoint.php
require __DIR__ . '/../bootstrap.php';
use BlockCypher\Auth\SimpleTokenCredential;
use BlockCypher\Client\TXClient;
use BlockCypher\Rest\ApiContext;
$apiContext = ApiContext::create('test3', 'btc', 'v1', new SimpleTokenCredential('c0afcccdde5081d6429de37d16166ead'), array('mode' => 'sandbox', 'log.LogEnabled' => true, 'log.FileName' => 'BlockCypher.log', 'log.LogLevel' => 'DEBUG'));
$txClient = new TXClient($apiContext);
$hexRawTx = "01000000011935b41d12936df99d322ac8972b74ecff7b79408bbccaf1b2eb8015228beac8000000006b483045022100921fc36b911094280f07d8504a80fbab9b823a25f102e2bc69b14bcd369dfc7902200d07067d47f040e724b556e5bc3061af132d5a47bd96e901429d53c41e0f8cca012102152e2bb5b273561ece7bbe8b1df51a4c44f5ab0bc940c105045e2cc77e618044ffffffff0240420f00000000001976a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac20da3c00000000001976a914efec6de6c253e657a9d5506a78ee48d89762fb3188ac00000000";
$tx = $txClient->push($hexRawTx);
// For Sample Purposes Only.
$txHex = new \BlockCypher\Api\TXHex();
$txHex->setTx($hexRawTx);
ResultPrinter::printResult("Push Raw Transaction", "TX", null, $txHex, $tx);
Esempio n. 11
0
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("{$baseUrl}/ExecutePayment.php?success=true")->setCancelUrl("{$baseUrl}/ExecutePayment.php?success=false");
// ### Payment
// A Payment Resource; create one using
// the above types and intent set to 'sale'
$payment = new Payment();
$payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction));
// For Sample Purposes Only.
$request = clone $payment;
// ### Create Payment
// Create a payment by calling the 'create' method
// passing it a valid apiContext.
// (See bootstrap.php for more on `ApiContext`)
// The return object contains the state and the
// url to which the buyer must be redirected to
// for payment approval
try {
    $payment->create($apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);
    exit(1);
}
// ### Get redirect url
// The API response provides the url that you must redirect
// the buyer to. Retrieve the url from the $payment->getApprovalLink()
// method
$approvalUrl = $payment->getApprovalLink();
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='{$approvalUrl}' >{$approvalUrl}</a>", $request, $payment);
return $payment;
<?php

$apiContext = (require __DIR__ . '/../bootstrap.php');
// ### Retrieve List of All Web Profiles
// Documentation available at https://developer.paypal.com/webapps/developer/docs/api/#list-web-experience-profiles
// Retrieve the list of all web profiles by calling the
// static `get_list` method on the WebProfile class.
// (See bootstrap.php for more on `ApiContext`)
try {
    $list = \PayPal\Api\WebProfile::get_list($apiContext);
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
    ResultPrinter::printError("Get List of All Web Profiles", "Web Profiles", null, null, $ex);
    exit(1);
}
$result = '';
foreach ($list as $object) {
    $result .= $object->toJSON(128) . PHP_EOL;
}
ResultPrinter::printResult("Get List of All Web Profiles", "Web Profiles", null, null, $result);
return $list;
// Add Shipping Address
//$shippingAddress = new ShippingAddress();
//$shippingAddress->setLine1('111 First Street')
//    ->setCity('Saratoga')
//    ->setState('CA')
//    ->setPostalCode('95070')
//    ->setCountryCode('US');
//$agreement->setShippingAddress($shippingAddress);
//$merchant_override_pref = new \PayPal\Api\MerchantPreferences();
//$merchant_override_pref->setReturnUrl(getBaseUrl(). "pp/billing/UpdateBillingAgreement.php?user_id=$user_id");
//$agreement->setOverrideMerchantPreferences($merchant_override_pref);
// For Sample Purposes Only.
$request = clone $agreement;
// ### Create Agreement
try {
    // Please note that as the agreement has not yet activated, we wont be receiving the ID just yet.
    $agreement = $agreement->create($apiContext);
    // ### Get redirect url
    // The API response provides the url that you must redirect
    // the buyer to. Retrieve the url from the $agreement->getApprovalLink()
    // method
    $approvalUrl = $agreement->getApprovalLink();
    header('Content-Type: application/json');
    echo $agreement->toJSON(128);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Created Billing Agreement.", "Agreement", null, $request, $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
// ResultPrinter::printResult("Created Billing Agreement. Please visit the URL to Approve.", "Agreement", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $agreement);
<?php

// # Create, Sign and Send MicroTX
// This sample code demonstrate how you can create, sign and send a new microtransaction, as documented here at:
// <a href="http://dev.blockcypher.com/#microtransaction-endpoint">http://dev.blockcypher.com/#microtransaction-endpoint</a>
//
// API used: POST /v1/btc/main/txs/micro
require __DIR__ . '/../bootstrap.php';
/// New MicroTX
$microTX = new \BlockCypher\Api\MicroTX();
$microTX->setFromPubkey("02d4e3404e175923adf89c932fab96758716f6a0a896890f2494c5d9141eb3f543")->setToAddress("C4MYFr4EAdqEeUKxTnPUF3d3whWcPMz1Fi")->setValueSatoshis(10000);
$microTXClient = new \BlockCypher\Client\MicroTXClient($apiContexts['BCY.test']);
try {
    /// Create
    $microTXToSign = $microTXClient->create($microTX);
    ResultPrinter::printResult("Created MicroTX", "MicroTX", $microTXToSign->getHash(), $microTX, $microTXToSign);
    /// Sign
    $microTXSigned = $microTXToSign->sign("2c2cc015519b79782bd9c5af66f442e808f573714e3c4dc6df7d79c183963cff");
    // Hex private key
    /// Send
    $microTXSent = $microTXClient->send($microTXSigned);
    ResultPrinter::printResult("Send MicroTX", "MicroTX", $microTXSent->getHash(), $microTXSigned, $microTXSent);
} catch (Exception $ex) {
    ResultPrinter::printError("Created, Sign and Send MicroTX", "MicroTX", null, null, $ex);
    exit(1);
}
Esempio n. 15
0
<?php

// # Create Wallet
// This sample code demonstrate how you can create a wallet, as documented here at:
// <a href="http://dev.blockcypher.com/#wallet_api">http://dev.blockcypher.com/#wallet_api</a>
//
// API used: POST /v1/btc/main/wallets
require __DIR__ . '/../bootstrap.php';
if (isset($_GET['wallet_name'])) {
    $walletName = filter_input(INPUT_GET, 'wallet_name', FILTER_SANITIZE_SPECIAL_CHARS);
} else {
    $walletName = 'alice';
    // Default wallet name for samples
}
$wallet = new \BlockCypher\Api\Wallet();
$wallet->setName($walletName);
$wallet->setAddresses(array("1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"));
/// For Sample Purposes Only.
$request = clone $wallet;
$walletClient = new \BlockCypher\Client\WalletClient($apiContexts['BTC.main']);
try {
    $output = $walletClient->create($wallet);
} catch (Exception $ex) {
    ResultPrinter::printError("Created Wallet", "Wallet", null, $request, $ex);
    exit(1);
}
ResultPrinter::printResult("Created Wallet", "Wallet", $output->getName(), $request, $output);
return $output;
Esempio n. 16
0
    $output = $webhook->create($apiContext);
} catch (Exception $ex) {
    // ^ Ignore workflow code segment
    if ($ex instanceof \PayPal\Exception\PayPalConnectionException) {
        $data = $ex->getData();
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printError("Created Webhook Failed. Checking if it is Webhook Number Limit Exceeded. Trying to delete all existing webhooks", "Webhook", "Please Use <a style='color: red;' href='DeleteAllWebhooks.php' >Delete All Webhooks</a> Sample to delete all existing webhooks in sample", $request, $ex);
        if (strpos($data, 'WEBHOOK_NUMBER_LIMIT_EXCEEDED') !== false) {
            require 'DeleteAllWebhooks.php';
            try {
                $output = $webhook->create($apiContext);
            } catch (Exception $ex) {
                // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
                ResultPrinter::printError("Created Webhook", "Webhook", null, $request, $ex);
                exit(1);
            }
        } else {
            // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
            ResultPrinter::printError("Created Webhook", "Webhook", null, $request, $ex);
            exit(1);
        }
    } else {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printError("Created Webhook", "Webhook", null, $request, $ex);
        exit(1);
    }
    // Print Success Result
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Created Webhook", "Webhook", $output->getId(), $request, $output);
return $output;
<?php

// ##Reauthorization Sample
// This sample code demonstrates how you can reauthorize a PayPal
// account payment.
// API used: v1/payments/authorization/{authorization_id}/reauthorize
/** @var Authorization $authorization */
$authorization = (require 'AuthorizePayment.php');
use PayPal\Api\Authorization;
use PayPal\Api\Amount;
// ### Reauthorization
// Reauthorization is available only for PayPal account payments
// and not for credit card payments.
// You can reauthorize a payment only once 4 to 29
// days after the 3-day honor period for the original authorization
// has expired.
try {
    $amount = new Amount();
    $amount->setCurrency("USD");
    $amount->setTotal(1);
    // ### Reauthorize with amount being reauthorized
    $authorization->setAmount($amount);
    $reAuthorization = $authorization->reauthorize($apiContext);
} catch (Exception $ex) {
    ResultPrinter::printError("Reauthorize Payment", "Payment", null, null, $ex);
    exit(1);
}
ResultPrinter::printResult("Reauthorize Payment", "Payment", $authorization->getId(), null, $reAuthorization);
Esempio n. 18
0
<?php

// # Cancel Invoice Sample
// This sample code demonstrate how you can cancel
// an invoice.
/** @var Invoice $invoice */
$invoice = (require 'SendInvoice.php');
use PayPal\Api\CancelNotification;
use PayPal\Api\Invoice;
try {
    // ### Cancel Notification Object
    // This would send a notification to both merchant as well
    // the payer about the cancellation. The information of
    // merchant and payer is retrieved from the invoice details
    $notify = new CancelNotification();
    $notify->setSubject("Past due")->setNote("Canceling invoice")->setSendToMerchant(true)->setSendToPayer(true);
    // ### Cancel Invoice
    // Cancel invoice object by calling the
    // static `cancel` method
    // on the Invoice class by passing a valid
    // notification object
    // (See bootstrap.php for more on `ApiContext`)
    $cancelStatus = $invoice->cancel($notify, $apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Cancel Invoice", "Invoice", null, $notify, $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Cancel Invoice", "Invoice", $invoice->getId(), $notify, null);
<?php

// # Generate New Address for a Wallet
//
// This sample code demonstrate how you can generate new addresses and associate them to a wallet,
// as documented here at: <a href="http://dev.blockcypher.com/#wallets">http://dev.blockcypher.com/#wallets</a>
//
// API used: GET /v1/btc/main/wallets/Wallet-Name/addresses/generate
// In samples we are using CreateWallet.php sample to get the created instance of wallet.
// You have to run that sample before running this one or there will be no wallets
require __DIR__ . '/../bootstrap.php';
if (isset($_GET['wallet_name'])) {
    $walletName = filter_input(INPUT_GET, 'wallet_name', FILTER_SANITIZE_SPECIAL_CHARS);
} else {
    $walletName = 'alice';
    // Default wallet name for samples
}
$walletClient = new \BlockCypher\Client\WalletClient($apiContexts['BTC.main']);
try {
    /// Generate address in Wallet
    $output = $walletClient->generateAddress($walletName);
} catch (Exception $ex) {
    ResultPrinter::printError("Add Addresses to a Wallet", "WalletGenerateAddressResponse", $walletName, null, $ex);
    exit(1);
}
ResultPrinter::printResult("Add Addresses to a Wallet", "WalletGenerateAddressResponse", $walletName, null, $output);
return $output;
    // CreatePaymentUsingPayPal.php
    $paymentId = $_GET['paymentId'];
    $payment = Payment::get($paymentId, $apiContext);
    // ### Payment Execute
    // PaymentExecution object includes information necessary
    // to execute a PayPal account payment.
    // The payer_id is added to the request query parameters
    // when the user is redirected from paypal back to your site
    $execution = new PaymentExecution();
    $execution->setPayerId($_GET['PayerID']);
    try {
        // Execute the payment
        // (See bootstrap.php for more on `ApiContext`)
        $result = $payment->execute($execution, $apiContext);
        ResultPrinter::printResult("Executed Payment", "Payment", $payment->getId(), $execution, $result);
        try {
            $payment = Payment::get($paymentId, $apiContext);
        } catch (Exception $ex) {
            ResultPrinter::printError("Get Payment", "Payment", null, null, $ex);
            exit(1);
        }
    } catch (Exception $ex) {
        ResultPrinter::printError("Executed Payment", "Payment", null, null, $ex);
        exit(1);
    }
    ResultPrinter::printResult("Get Payment", "Payment", $payment->getId(), null, $payment);
    return $payment;
} else {
    ResultPrinter::printResult("User Cancelled the Approval", null);
    exit;
}
<?php

// # Cancel Payout Item Status Sample
//
// Use this call to cancel an existing, unclaimed transaction. If an unclaimed item is not claimed within 30 days, the funds will be automatically returned to the sender. This call can be used to cancel the unclaimed item prior to the automatic 30-day return.
// https://developer.paypal.com/docs/api/#cancel-an-unclaimed-payout-item
// API used: POST /v1/payments/payouts-item/<Payout-Item-Id>/cancel
/** @var \PayPal\Api\PayoutBatch $payoutBatch */
$payoutBatch = (require 'CreateSinglePayout.php');
// ## Payout Item ID
// You can replace this with your Payout Batch Id on already created Payout.
$payoutItems = $payoutBatch->getItems();
$payoutItem = $payoutItems[0];
$payoutItemId = $payoutItem->getPayoutItemId();
$output = null;
// ### Cancel Payout Item
// Check if Payout Item is UNCLAIMED, and if so, cancel it.
try {
    if ($payoutItem->getTransactionStatus() == 'UNCLAIMED') {
        // Cancel the Payout Item
        $output = \PayPal\Api\PayoutItem::cancel($payoutItemId, $apiContext);
        ResultPrinter::printResult("Cancel Unclaimed Payout Item", "PayoutItem", $output->getPayoutItemId(), null, $output);
    } else {
        // The item transaction status is not unclaimed. You can only cancel an unclaimed transaction.
        ResultPrinter::printError("Cancel Unclaimed Payout Item", "PayoutItem", null, $payoutItemId, new Exception("Payout Item Status is not UNCLAIMED"));
    }
} catch (Exception $ex) {
    ResultPrinter::printError("Cancel Unclaimed Payout Item", "PayoutItem", null, $payoutItemId, $ex);
    exit(1);
}
return $output;
// You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk.
// authorization code from mobile sdk
$authorizationCode = 'EJfRuAqXEE95pdVMmOym_mftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY';
// Client Metadata id from mobile sdk
// For more information look for PayPal-Client-Metadata-Id in https://developer.paypal.com/docs/api/#authentication--headers
$clientMetadataId = '123123456';
try {
    // Exchange authorization_code for long living refresh token. You should store
    // it in a database for later use
    $refreshToken = FuturePayment::getRefreshToken($authorizationCode, $apiContext);
    // Update the access token in apiContext
    $payment->updateAccessToken($refreshToken, $apiContext);
    // For Sample Purposes Only.
    $request = clone $payment;
    // ### Create Future Payment
    // Create a payment by calling the 'create' method
    // passing it a valid apiContext.
    // (See bootstrap.php for more on `ApiContext`)
    // The return object contains the state and the
    // url to which the buyer must be redirected to
    // for payment approval
    // Please note that currently future payments works only with PayPal as a funding instrument.
    $payment->create($apiContext, $clientMetadataId);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Future Payment", "Payment", null, $request, $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Future Payment", "Payment", $payment->getId(), $request, $payment);
return $payment;
Esempio n. 23
0
<?php

// # Suspend an agreement
//
// This sample code demonstrate how you can suspend a billing agreement, as documented here at:
// https://developer.paypal.com/webapps/developer/docs/api/#suspend-an-agreement
// API used: /v1/payments/billing-agreements/<Agreement-Id>/suspend
// Retrieving the Agreement object from Create Agreement Sample to demonstrate the List
/** @var Agreement $createdAgreement */
$createdAgreement = (require 'CreateBillingAgreementWithCreditCard.php');
use PayPal\Api\Agreement;
use PayPal\Api\AgreementStateDescriptor;
//Create an Agreement State Descriptor, explaining the reason to suspend.
$agreementStateDescriptor = new AgreementStateDescriptor();
$agreementStateDescriptor->setNote("Suspending the agreement");
try {
    $createdAgreement->suspend($agreementStateDescriptor, $apiContext);
    // Lets get the updated Agreement Object
    $agreement = Agreement::get($createdAgreement->getId(), $apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Suspended the Agreement", "Agreement", null, $agreementStateDescriptor, $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Suspended the Agreement", "Agreement", $agreement->getId(), $agreementStateDescriptor, $agreement);
return $agreement;
// # AuthorizationCapture
// This sample code demonstrates how you can capture
// a previously authorized payment.
// API used: /v1/payments/payment
// https://developer.paypal.com/webapps/developer/docs/api/#capture-an-authorization
/** @var Authorization $authorization */
$authorization = (require 'GetAuthorization.php');
use PayPal\Api\Amount;
use PayPal\Api\Capture;
use PayPal\Api\Authorization;
// ### Capture Payment
// You can capture and process a previously created authorization
// by invoking the $authorization->capture method
// with a valid ApiContext (See bootstrap.php for more on `ApiContext`)
try {
    $authId = $authorization->getId();
    $amt = new Amount();
    $amt->setCurrency("USD")->setTotal(1);
    ### Capture
    $capture = new Capture();
    $capture->setAmount($amt);
    // Perform a capture
    $getCapture = $authorization->capture($capture, $apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Capture Payment", "Authorization", null, $capture, $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Capture Payment", "Authorization", $getCapture->getId(), $capture, $getCapture);
return $getCapture;
Esempio n. 25
0
// # Retrieve QR Code for Invoice Sample
// Specify an invoice ID to get a QR code (image) that corresponds to the invoice ID. A QR code for an invoice can be added to a paper or PDF invoice. When a customer uses their mobile device to scan the QR code, the customer is redirected to the PayPal mobile payment flow, where they can pay online with PayPal or a credit card.
/** @var Invoice $invoice */
$invoice = (require 'SendInvoice.php');
use PayPal\Api\Invoice;
try {
    // ### Retrieve QR Code of Sent Invoice
    // Retrieve QR Code of Sent Invoice by calling the
    // `qrCode` method
    // on the Invoice class by passing a valid
    // notification object
    // (See bootstrap.php for more on `ApiContext`)
    $image = Invoice::qrCode($invoice->getId(), array('height' => '300', 'width' => '300'), $apiContext);
    // ### Optionally Save to File
    // This is not a required step. However, if you want to store this image as a file, you can use
    // 'saveToFile' method with proper file name.
    // This will save the image as /samples/invoice/images/sample.png
    $path = $image->saveToFile("images/sample.png");
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Retrieved QR Code for Invoice", "Invoice", $invoice->getId(), null, $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Retrieved QR Code for Invoice", "Invoice", $invoice->getId(), null, $image);
// ### Show the Image
// In PHP, there are many ways to present an images.
// One of the ways, you could directly inject the base64-encoded string
// with proper image information in front of it.
echo '<img src="data:image/png;base64,' . $image->getImage() . '" alt="Invoice QR Code" />';
<?php

// Run on console:
// php -f .\sample\wallet-api\GenerateAddressInHDWalletEndpoint.php
require __DIR__ . '/../bootstrap.php';
use BlockCypher\Auth\SimpleTokenCredential;
use BlockCypher\Client\HDWalletClient;
use BlockCypher\Rest\ApiContext;
$apiContext = ApiContext::create('main', 'btc', 'v1', new SimpleTokenCredential('c0afcccdde5081d6429de37d16166ead'), array('mode' => 'sandbox', 'log.LogEnabled' => true, 'log.FileName' => 'BlockCypher.log', 'log.LogLevel' => 'DEBUG'));
$walletClient = new HDWalletClient($apiContext);
$hdWalletGenerateAddressResponse = $walletClient->generateAddress('bob');
ResultPrinter::printResult("Generate Address in a HDWallet", "HDWalletGenerateAddressResponse", $walletName, null, $hdWalletGenerateAddressResponse);
Esempio n. 27
0
<?php

// # List Invoices Sample
// This sample code demonstrate how you can get
// all invoice from history.
/** @var Invoice $invoice */
$invoice = (require 'CreateInvoice.php');
use PayPal\Api\Invoice;
try {
    // ### Retrieve Invoices
    // Retrieve the Invoice History object by calling the
    // static `get_all` method on the Invoice class.
    // Refer the method doc for valid values for keys
    // (See bootstrap.php for more on `ApiContext`)
    $invoices = Invoice::getAll(array('page' => 0, 'page_size' => 4, 'total_count_required' => "true"), $apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Lookup Invoice History", "Invoice", null, null, $ex);
    exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Lookup Invoice History", "Invoice", null, null, $invoices);
Esempio n. 28
-1
 public function order()
 {
     $paypalConf = $this->config->item('paypal');
     $clientId = $paypalConf['clientId'];
     $clientSecret = $paypalConf['clientSecret'];
     $appName = $paypalConf['appName'];
     $price = $paypalConf['price'];
     $shiping = 0;
     $tax = 0;
     $mode = "sandbox";
     //or live
     $apiContext = new ApiContext(new OAuthTokenCredential($clientId, $clientSecret));
     $apiContext->setConfig(array('mode' => $mode, 'log.LogEnabled' => false));
     $payer = new Payer();
     $payer->setPaymentMethod("paypal");
     $item1 = new Item();
     $item1->setName($appName)->setCurrency('USD')->setQuantity(1)->setPrice($price);
     $itemList = new ItemList();
     $itemList->setItems(array($item1));
     $details = new Details();
     $details->setShipping($shiping)->setTax($tax)->setSubtotal($price);
     $amount = new Amount();
     $amount->setCurrency("USD")->setTotal($price + $shiping + $tax)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid());
     $token = $this->createToken();
     $baseUrl = getBaseUrl();
     $redirectUrls = new RedirectUrls();
     $redirectUrls->setReturnUrl("{$baseUrl}/paypal/ordersucess?success=true&tk1=" . $token[0] . "&tk2=" . $token[1])->setCancelUrl("{$baseUrl}/paypal/orderfailed?success=false");
     $payment = new Payment();
     $payment->setIntent("order")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction));
     // For Sample Purposes Only.
     $request = clone $payment;
     try {
         $payment->create($apiContext);
     } catch (Exception $ex) {
         // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
         ResultPrinter::printError("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);
         exit(1);
     }
     $approvalUrl = $payment->getApprovalLink();
     header("Location: " . $approvalUrl . "");
     die;
 }
Esempio n. 29
-3
 public function credit_card()
 {
     return "Hello?";
     $card = new CreditCard();
     $card->setType("visa")->setNumber("4148529247832259")->setExpireMonth("11")->setExpireYear("2019")->setCvv2("012")->setFirstName("Joe")->setLastName("Shopper");
     $fi = new FundingInstrument();
     $fi->setCreditCard($card);
     $payer = new Payer();
     $payer->setPaymentMethod("credit_card")->setFundingInstruments(array($fi));
     $item1 = new Item();
     $item1->setName('Ground Coffee 40 oz')->setDescription('Ground Coffee 40 oz')->setCurrency('USD')->setQuantity(1)->setTax(0.3)->setPrice(7.5);
     $item2 = new Item();
     $item2->setName('Granola bars')->setDescription('Granola Bars with Peanuts')->setCurrency('USD')->setQuantity(5)->setTax(0.2)->setPrice(2);
     $itemList = new ItemList();
     $itemList->setItems(array($item1, $item2));
     $details = new Details();
     $details->setShipping(1.2)->setTax(1.3)->setSubtotal(17.5);
     $amount = new Amount();
     $amount->setCurrency("USD")->setTotal(20)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid());
     $payment = new Payment();
     $payment->setIntent("sale")->setPayer($payer)->setTransactions(array($transaction));
     $request = clone $payment;
     try {
         $payment->create($apiContext);
     } catch (Exception $ex) {
         ResultPrinter::printError('Create Payment Using Credit Card. If 500 Exception, try creating a new Credit Card using <a href="https://ppmts.custhelp.com/app/answers/detail/a_id/750">Step 4, on this link</a>, and using it.', 'Payment', null, $request, $ex);
         exit(1);
     }
     ResultPrinter::printResult('Create Payment Using Credit Card', 'Payment', $payment->getId(), $request, $payment);
     return $payment;
 }
<?php

// # Get Payout Batch Status Sample
//
// This sample code demonstrate how you can get the batch payout status of a created batch payout, as documented here at:
// https://developer.paypal.com/docs/api/#get-the-status-of-a-batch-payout
// API used: GET /v1/payments/payouts/<Payout-Batch-Id>
/** @var \PayPal\Api\PayoutBatch $payoutBatch */
$payoutBatch = (require 'CreateBatchPayout.php');
// ## Payout Batch ID
// You can replace this with your Payout Batch Id on already created Payout.
$payoutBatchId = $payoutBatch->getBatchHeader()->getPayoutBatchId();
// ### Get Payout Batch Status
try {
    $output = \PayPal\Api\Payout::get($payoutBatchId, $apiContext);
} catch (Exception $ex) {
    ResultPrinter::printError("Get Payout Batch Status", "PayoutBatch", null, $payoutBatchId, $ex);
    exit(1);
}
ResultPrinter::printResult("Get Payout Batch Status", "PayoutBatch", $output->getBatchHeader()->getPayoutBatchId(), null, $output);
return $output;