PHP code example of vrajroham / laravel-bitpay

1. Go to this page and download the library: Download vrajroham/laravel-bitpay 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/ */

    

vrajroham / laravel-bitpay example snippets


// ... your other 'web' routes

Route::bitPayWebhook(); // https://example.com/laravel-bitpay/webhook

// OR ...

Route::bitPayWebhook('receive/webhooks/here'); // https://example.com/receive/webhooks/here

/**
 * Handle the webhook event, keeping in mind that the server doesn't trust the client (us), so neither should
 * we trust the server. Well, trust, but verify.
 *
 * @param BitpayWebhookReceived $event
 * @return void
 */
public function handle(BitpayWebhookReceived $event)
{
    // Extract event payload
    $payload = $event->payload;

    // Verify that webhook is for a BitPay Invoice resource
    if (in_array($payload['event']['code'], array_keys(BitPayConstants::INVOICE_WEBHOOK_CODES))) {
        try {
            // Do not trust the webhook data. Pull the referenced Invoice from BitPay's server
            $invoice = LaravelBitpay::getInvoice($payload['data']['id']);

            // Now grab our internal Order instance for this supposed Invoice
            $order = Order::whereOrderId($invoice->getOrderId())->first();

            // Verify Invoice token, previously stored at time of creation
            // Learn more at: https://github.com/vrajroham/laravel-bitpay#create-an-invoice
            if ($invoice->getToken() !== $order->invoice_token) {
                return;
            }

            $invoice_status = $invoice->getStatus();

            // Do something about the new Invoice status
            if ($invoice_status === InvoiceStatus::Paid) {
                $order->update(['status' => $invoice_status]) && OrderStatusChanged::dispatch($order->refresh());
            }
        } catch (BitPayException $e) {
            Log::error($e);
        }
    }
}

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    // ... other event-listener mappings
    BitpayWebhookReceived::class => [
        BitPayWebhookListener::class,
    ],
]

// Create instance of Invoice
$invoice = LaravelBitpay::Invoice(449.99, Currency::USD); // Always use the BitPay Currency model to prevent typos

// Set item details (Only 1 item per Invoice)
$invoice->setItemDesc('You "Joe Goldberg" Life-Size Wax Figure');
$invoice->setItemCode('sku-1234');
$invoice->setPhysical(true); // Set to false for digital/virtual items

// Ensure you provide a unique OrderId for each Invoice
$invoice->setOrderId($order->order_id);

// Create Buyer Instance
$buyer = LaravelBitpay::Buyer();
$buyer->setName('John Doe');
$buyer->setEmail('[email protected]');
$buyer->setAddress1('2630 Hegal Place');
$buyer->setAddress2('Apt 42');
$buyer->setLocality('Alexandria');
$buyer->setRegion('VA');
$buyer->setPostalCode(23242);
$buyer->setCountry('US');
$buyer->setNotify(true); // Instructs BitPay to email Buyer about their Invoice

// Attach Buyer to Invoice
$invoice->setBuyer($buyer);

// Set URL that Buyer will be redirected to after completing the payment, via GET Request
$invoice->setRedirectURL(route('your-bitpay-success-url'));
// Set URL that Buyer will be redirected to after closing the invoice or after the invoice expires, via GET Request
$invoice->setCloseURL(route('your-bitpay-cancel-url'));
$invoice->setAutoRedirect(true);

// Optional. Learn more at: https://github.com/vrajroham/laravel-bitpay#1-setup-your-webhook-route
$invoice->setNotificationUrl('https://example.com/your-custom-webhook-url');

// This is the recommended IPN format that BitPay advises for all new implementations
$invoice->setExtendedNotifications(true);

// Create invoice on BitPay's server
$invoice = LaravelBitpay::createInvoice($invoice);

$invoiceId = $invoice->getId();
$invoiceToken = $invoice->getToken();

// You should save Invoice ID and Token, for your reference
$order->update(['invoice_id' => $invoiceId, 'invoice_token' => $invoiceToken]);

// Redirect user to the Invoice's hosted URL to complete payment
$paymentUrl = $invoice->getUrl();
return Redirect::to($paymentUrl);

$invoice = LaravelBitpay::getInvoice('invoiceId_sGsdVsgheF');

$startDate = date('Y-m-d', strtotime('first day of this month'));
$endDate = date('Y-m-d');

$invoices = LaravelBitpay::getInvoices($startDate, $endDate);

// True if the webhook has been resent for the current invoice status, false otherwise.
$webhookResent = LaravelBitpay::requestInvoiceWebhook('invoiceId_sGsdVsgheF');

$invoice = LaravelBitpay::getInvoice('invoiceId_sGsdVsgheF');

$refundRequested = LaravelBitpay::createRefund($invoice, '[email protected]', 0.016, 'ETH');

if ($refundRequested) {
    // Don't just sit there. Do something!
}

$invoice = LaravelBitpay::getInvoice('invoiceId_sGsdVsgheF');

$refund = LaravelBitpay::getRefund($invoice, 'refundId_pUdhjwGjsg');

$invoice = LaravelBitpay::getInvoice('invoiceId_sGsdVsgheF');

$refundRequests = LaravelBitpay::getRefunds($invoice);

$invoice = LaravelBitpay::getInvoice('invoiceId_sGsdVsgheF');

$refundRequestCancelled = LaravelBitpay::cancelRefund($invoice->getId(), 'refundId_pUdhjwGjsg');

// Initialize Bill
$billData = LaravelBitpay::Bill();
$billData->setNumber('bill1234-EFGH');
$billData->setCurrency(Currency::USD); // Always use the BitPay Currency model to prevent typos
$dueDate = date(BitPayConstants::DATETIME_FORMAT, strtotime('+10 days')); // ISO-8601 formatted date
$billData->setDueDate($dueDate);
$billData->setPassProcessingFee(true); // Let the recipient shoulder BitPay's processing fee

// Prepare Bill recipient's data
$billData->setName('John Doe');
$billData->setAddress1('2630 Hegal Place');
$billData->setAddress2('Apt 42');
$billData->setCity('Alexandria');
$billData->setState('VA');
$billData->setZip(23242);
$billData->setCountry('US');
$billData->setEmail('[email protected]');
$billData->setCc(['[email protected]']);
$billData->setPhone('555-123-456');

// Prepare Bill's line item(s)
$itemUno = LaravelBitpay::BillItem();
$itemUno->setDescription('Squid Game "Front Man" Costume');
$itemUno->setPrice(49.99);
$itemUno->setQuantity(2);

$itemDos = LaravelBitpay::BillItem();
$itemDos->setDescription('GOT "House Stark" Sterling Silver Pendant');
$itemDos->setPrice(35);
$itemDos->setQuantity(1);

$billData->setItems([$itemUno, $itemDos]);

// Create Bill
$bill = LaravelBitpay::createBill($billData);

// Store the Bill's BitPay ID and URL for future reference
$billId = $bill->getId();
$billPaymentUrl = $bill->getUrl();

// OR

// Redirect the recipient to BitPay's hosted Bill payment page
Redirect::to($billPaymentUrl);

$bill = LaravelBitpay::getBill('bill1234-EFGH');

$paidBills = LaravelBitpay::getBills(BillStatus::Paid);

$existingBill = LaravelBitpay::getBill('bill1234-EFGH');
$existingItems = $existingBill->getItems();

$billData = LaravelBitpay::Bill();
$billData->setId($existingBill->getId());

$itemTres = LaravelBitpay::BillItem();
$itemTres->setDescription('The Tomorrow War "White Spike" Life-Size Wax Figure');
$itemTres->setPrice(189.99);
$itemTres->setQuantity(1);

$billData->setItems(array_merge($existingItems, [$itemTres]));

// Update Bill
$updatedBill = LaravelBitpay::updateBill($billData, $billData->getId());

$bill = LaravelBitpay::getBill('bill1234-EFGH');

$billDelivered = LaravelBitpay::deliverBill($bill->getId(), $bill->getToken());

if ($billDelivered) {
    // Bill delivered successfully. Do something about that... or not.
}

// Initialize Subscription
$subscriptionData = LaravelBitpay::Subscription();
$subscriptionData->setSchedule(BitPayConstants::SUBSCRIPTION_SCHEDULE_MONTHLY);

// Optional recurring bill data
$billData = [
    'number'            => 'subscription1234-ABCD',
    'name'              => 'John Doe',
    'address1'          => '2630 Hegal Place',
    'address2'          => 'Apt 42',
    'city'              => 'Alexandria',
    'state'             => 'VA',
    'zip'               => 23242,
    'country'           => 'US',
    'cc'                => ['[email protected]'],
    'phone'             => '555-123-456',
    'passProcessingFee' => true,
];

$dueDate = date(BitPayConstants::DATETIME_FORMAT, strtotime('first day of next month 9 AM'));

$billItems = array(
    LaravelBitpay::SubscriptionItem(100.00, 1, 'Web Hosting - 4 CPUs | 16GB Memory | 400GB SSD'),
    LaravelBitpay::SubscriptionItem(80.00, 1, 'Basic Website Maintenance'),
);

// Autofill optional bill data
$mapper = new JsonMapper();
$billData = $mapper->map(
    $billData,
    LaravelBitpay::BillData(
        Currency::USD, // Always use the BitPay Currency model to prevent typos
        '[email protected]',
        $dueDate,
        $billItems
    )
);

$subscriptionData->setBillData($billData);

// A little wizardry to always get the 28th day of the current month (leap year safe)
$deliveryDate = strtotime('first day of this month 9 AM');
$deliveryDate = new \DateTime("@$deliveryDate");
$deliveryDate = $deliveryDate->modify('+27 days')->getTimestamp();
$deliveryDate = date(BitPayConstants::DATETIME_FORMAT, $deliveryDate);

$subscriptionData->setNextDelivery($deliveryDate);

// Create the Subscription on BitPay
$subscription = LaravelBitpay::createSubscription($subscriptionData);

// You may then store the Subscription ID for future reference
$subscriptionId = $subscription->getId();

$subscription = LaravelBitpay::getSubscription('6gqe8y5mkc5Qx2a9zmspgx');

$activeSubscriptions = LaravelBitpay::getSubscriptions(SubscriptionStatus::Active);

$subscriptionData = LaravelBitpay::Subscription();
$subscriptionData->setId('6gqe8y5mkc5Qx2a9zmspgx');
$subscriptionData->setStatus(SubscriptionStatus::Active);

$activatedSubscription = LaravelBitpay::updateSubscription($subscriptionData, $subscriptionData->getId());

$startDate = date('Y-m-d', strtotime('first day of this year'));
$endDate = date('Y-m-d');

$eurSettlements = LaravelBitpay::getSettlements(
        Currency::EUR,
        $startDate,
        $endDate,
        BitPayConstants::SETTLEMENT_STATUS_COMPLETED,
        100,
        4
    );

$settlement = LaravelBitpay::getSettlement('settlementId_uidwb3668');

$settlement = LaravelBitpay::getSettlement('settlementId_uidwb3668');

$settlementReport = LaravelBitpay::getSettlementReconciliationReport($settlement);

$accountBalances = LaravelBitpay::getLedgers();

$startDate = date('Y-m-d', strtotime('first day of this month'));
$endDate = date('Y-m-d');

$usdLedgerEntries = LaravelBitpay::getLedger(Currency::USD, $startDate, $endDate);

// Init individual recipients
$jane = LaravelBitpay::PayoutRecipient('[email protected]', 'Plain Jane');
$ada = LaravelBitpay::PayoutRecipient('[email protected]', 'Ada Lovelace');

// Optional. Learn more at https://github.com/vrajroham/laravel-bitpay#1-setup-your-webhook-route
$ada->setNotificationUrl('https://example.com/your-custom-webhook-url');

// Batch all individual recipients
$recipients = LaravelBitpay::PayoutRecipients([$jane, $ada]);

// Submit invites
$recipientsInvited = LaravelBitpay::invitePayoutRecipients($recipients);

// Do something with the returned invitees
foreach ($recipientsInvited as $recipient) {
    $recipientId = $recipient->getId();
    $recipientToken = $recipient->getToken();
    
    // ... store Recipient ID and Token somewhere persistent

    // Perform other desired actions
    \App\Events\LookOutForAnInviteEmail::dispatch($recipient->getEmail());
}

$recipient = LaravelBitpay::getPayoutRecipient('recipientId_adaLovelace')

$verifiedRecipients = LaravelBitpay::getPayoutRecipients(RecipientStatus::VERIFIED, 100, 49);

$recipient = LaravelBitpay::getPayoutRecipient('recipientId_adaLovelace');
$recipient->setLabel('Cardano To The Moon');

$updatedRecipient = LaravelBitpay::updatePayoutRecipient($recipient->getId(), $recipient);

$recipientRemoved = LaravelBitpay::removePayoutRecipient('recipientId_janeDoe');

// True if the webhook has been resent for the current recipient status, false otherwise.
$webhookResent = LaravelBitpay::requestPayoutRecipientWebhook('recipientId_adaLovelace');

// Initialize a Payout
// Pay Ada in USD and record it on the BTC ledger
$payoutData = LaravelBitpay::Payout(50.00, Currency::USD, Currency::BTC); 

// Set Payout details
$payoutData->setRecipientId('recipientId_adaLovelace'); // From previously invited Recipient
$payoutData->setReference('1234'); // Uniquely identifies an equivalent payout entry in your system
$payoutData->setLabel('5-Star Bonus Affiliate Payment #1234 for Dec 2021');
$payoutData->setEffectiveDate('2021-12-31');

// Optional. Learn more at https://github.com/vrajroham/laravel-bitpay#1-setup-your-webhook-route
$payoutData->setNotificationURL('https://example.com/your-custom-webhook-url');

// Create Payout on BitPay's server
$payout = LaravelBitpay::createPayout($payoutData);

$payoutId = $payout->getId();
$payoutToken = $payout->getToken();

// ... store Payout ID and Token somewhere persistent

// Initialize a Payout Batch
$payoutBatchData = LaravelBitpay::PayoutBatch(Currency::USD); // Pay recipients in USD
$payoutBatchData->setLedgerCurrency(Currency::ETH); // Record the payout batch on the ETH ledger
$payoutBatchData->setAmount(500.00);
$payoutBatchData->setReference('Aff_Jan-Feb_2022'); // Uniquely identifies an equivalent payout batch in your system
$payoutBatchData->setLabel('Affiliate Payments for Jan-Feb 2022');
$payoutBatchData->setEffectiveDate('2022-02-28');

// Optional. Learn more at https://github.com/vrajroham/laravel-bitpay#1-setup-your-webhook-route
$payoutBatchData->setNotificationURL('https://example.com/your-custom-webhook-url');

// Define Instruction(s)
$payJane = LaravelBitpay::PayoutInstruction(
    250.00,
    RecipientReferenceMethod::RECIPIENT_ID,
    'recipientId_janeDoe'
);
$payJane->setLabel('Affiliate Payment #1234 for Jan-Feb 2022');

$payAda = LaravelBitpay::PayoutInstruction(
    250.00,
    RecipientReferenceMethod::RECIPIENT_ID,
    'recipientId_adaLovelace'
);
$payAda->setLabel('Affiliate Payment #5678 for Jan-Feb 2022');

// Attach Instruction(s) to Payout Batch
$payoutBatchData->setInstructions([$payJane, $payAda]);

// Create Payout Batch on BitPay's server
$payoutBatch = LaravelBitpay::createPayoutBatch($payoutBatchData);

$payoutBatchId = $payoutBatch->getId();
$payoutBatchToken = $payoutBatch->getToken();

// ... store Payout Batch ID and Token somewhere persistent

$payout = LaravelBitpay::getPayout('payoutId_jws43dbnfpg');

$payoutBatch = LaravelBitpay::getPayoutBatch('payoutBatchId_jws43dbnfpg');

$startDate = date('Y-m-d', strtotime('first day of this year'));
$endDate   = date('Y-m-d');

$completedPayouts = LaravelBitpay::getPayouts($startDate, $endDate, PayoutStatus::Complete);

$startDate = date('Y-m-d', strtotime('first day of this year'));
$endDate   = date('Y-m-d');

$cancelledPayoutBatches = LaravelBitpay::getPayoutBatches($startDate, $endDate, PayoutStatus::Cancelled);

$payoutCancelled = LaravelBitpay::cancelPayout('payoutId_jws43dbnfpg');

$payoutBatchCancelled = LaravelBitpay::cancelPayoutBatch('payoutBatchId_jws43dbnfpg');

// True if the webhook has been resent for the current payout status, false otherwise.
$webhookResent = LaravelBitpay::requestPayoutWebhook('payoutId_jws43dbnfpg');

// True if the webhook has been resent for the current payout batch status, false otherwise.
$webhookResent = LaravelBitpay::requestPayoutBatchWebhook('payoutBatchId_jws43dbnfpg');

$supportedCurrencies = LaravelBitpay::getCurrencies();

$rates = LaravelBitpay::getRates();

$btcToUsdRate = $rates->getRate(Currency::USD); // Always use the BitPay Currency model to prevent typos

$ethRates = LaravelBitpay::getCurrencyRates(Currency::ETH);

$ethToUsdRate = $ethRates->getRate(Currency::USD);

$dogeToUsdRate = LaravelBitpay::getCurrencyPairRate(Currrency::DOGE, Currency::USD);
bash
php artisan vendor:publish --provider="Vrajroham\LaravelBitpay\LaravelBitpayServiceProvider"
bash
php artisan laravel-bitpay:createkeypair
bash
php artisan make:listener BitPayWebhookListener --event=\Vrajroham\LaravelBitpay\Events\BitpayWebhookReceived