BTCPay Server intergration using Greenfield API / php

652 views Asked by At

So I am trying to integrate btcpayserver into my site. I am fairly new to php so bare with me but I have everything working until after the invoice is created. Whenever user clicks to pay with bitcoin, it successfully creates new invoice but doesn't redirect to the checkout link afterwards.

I should mention i am using the following to help with integration process https://github.com/btcpayserver/btcpayserver-greenfield-php

Here is my create_invoice.php

session_start();

// Include autoload file.
require __DIR__ . '/../vendor/autoload.php';

// Import Invoice client class.
use BTCPayServer\Client\Invoice;
use BTCPayServer\Client\InvoiceCheckoutOptions;
use BTCPayServer\Util\PreciseNumber;

// Fill in with your BTCPay Server data.
$apiKey = 'aaaaaaaaaa';
$host = 'https://aa.demo.btcpayserver.org/';
$storeId = 'aaaaaa';
$amount = $_POST['amount'];
$currency = 'USD';
$orderId = $_SESSION['name']."#" . mt_rand(0, 1000);
$buyerEmail = $_SESSION['name'];

try {
    $client = new Invoice($host, $apiKey);
    var_dump(
        $client->createInvoice(
            $storeId,
            $currency,
            PreciseNumber::parseString($amount),
            $orderId,
            $buyerEmail
        )
    );
} catch (\Throwable $e) {
    echo "Error: " . $e->getMessage();
}

Whenever the form is submitted the following is shown (i replaced the sensitive information)

object(BTCPayServer\Result\Invoice)#6 (1) 
{ 
  ["data":"BTCPayServer\Result\AbstractResult":private] => array(16) 
  { 
    ["id"]=> string(22) "aaaaaaaaaaa" 
    ["storeId"]=> string(44) "ssssssssssssssssssssssssssss" 
    ["amount"]=> string(4) "18.0" 
    ["checkoutLink"]=> string(62) "https://demo.aa.btcpayserver.org/i/aaaaaaaaaaaaaa" 
    ["status"]=> string(3) "New" 
    ["additionalStatus"]=> string(4) "None" 
    ["monitoringExpiration"]=> int(1669087659) 
    ["expirationTime"]=> int(1669080459) 
    ["createdTime"]=> int(1669078659) 
    ["availableStatusesForManualMarking"]=> array(2) 
    { 
      [0]=> string(7) "Settled" 
      [1]=> string(7) "Invalid" 
    } 
    ["archived"]=> bool(false) 
    ["type"]=> string(8) "Standard" 
    ["currency"]=> string(3) "USD" 
    ["metadata"]=> array(1) 
    { 
      ["orderId"]=> string(4) "#501" 
    } 
    ["checkout"]=> array(10) { 
      ["speedPolicy"]=> string(9) "HighSpeed" 
      ["paymentMethods"]=> array(1) 
      { 
        [0]=> string(3) "BTC" 
      } 
      ["defaultPaymentMethod"]=> NULL 
      ["expirationMinutes"]=> int(30) 
      ["monitoringMinutes"]=> int(120) 
      ["paymentTolerance"]=> float(0) 
      ["requiresRefundEmail"]=> NULL 
      ["defaultLanguage"]=> NULL 
    } 
    ["receipt"]=> array(3) 
    { 
      ["enabled"]=> NULL 
      ["showQR"]=> NULL 
      ["showPayments"]=> NULL 
    } 
  } 
} 

Now my issue is I need to redirect to "checkoutLink" after invoice is created.

UPDATE*

Following code displays error "Error: Cannot access offset of type string on string"

if ($response->getStatus() === 200) {
        $data1 = $response->getBody();
        $link1 = $data1["checkoutLink"];
        echo $link1;
        
    } else {
        throw $this->getExceptionByStatusCode($method, $url, $response);
    }
2

There are 2 answers

1
parth chavda On

$client = new Invoice($host, $apiKey);

$response = $client->createInvoice(
        $storeId,
        $currency,
        PreciseNumber::parseString($amount),
        $orderId,
        $buyerEmail
    );

return redirect($response->getCheckoutLink());

0
Samuel On

I apologize for the delay, but I hope you have already resolved your issue. Nonetheless, I believe the answer will not only help you but also prove beneficial to others facing a similar problem. The modification focuses on redirecting to the payment page after creating the invoice:

<?php
session_start();

// Include autoload file.
require __DIR__ . '/../vendor/autoload.php'; // Make sure this path is right

// Import Invoice client class.
use BTCPayServer\Client\Invoice;
use BTCPayServer\Util\PreciseNumber;

// Fill in with your BTCPay Server data.
$apiKey = 'aaaaaaaaaa';
$host = 'https://aa.demo.btcpayserver.org'; // The BtcPay Server host
$storeId = 'aaaaaa';
$amount = (float) strip_tags($_POST['amount']);
$currency = 'USD';
$orderId = strip_tags($_SESSION['name'])."#" . mt_rand(0, 1000);
$buyerEmail = strip_tags($_SESSION['email']); // The email is not required but make sure it is well formatted

try {
    $client = new Invoice($host, $apiKey);
    
    $invoice = $client->createInvoice(
        $storeId,
        $currency,
        PreciseNumber::parseString($amount),
        $orderId,
        $buyerEmail
    );

    // Save the data you need to in your db
    // Now redirect the user to the payment url
    header('Location: ' . $invoice->getCheckoutLink());
    exit(); // Make sure to exit after redirecting to prevent further execution.

} catch (\Throwable $e) {
    // Handle errors
    var_dump($e);
    die();
}

Please do make sure to properly sanitize users' data.