PHP code example of crypto-pay / binancepay

1. Go to this page and download the library: Download crypto-pay/binancepay 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/ */

    

crypto-pay / binancepay example snippets


    // payment controller
    
    use CryptoPay\Binancepay\BinancePay;
    
    public function initiateBinancePay(Request $request){
        
        // Other logics 
        
        $user = Auth::user();
        $product = Product::find(100); // Use your own product
         
        $data['order_amount'] =  25.17;
        $data['package_id'] = $product->id; // referenceGoodsId: id from the DB Table that user choose to purchase 
        $data['goods_name'] = $product->name;
        $data['goods_detail'] = null;
        $data['buyer'] = [
            "referenceBuyerId" => $user->id,
            "buyerEmail" => $user->email,
            "buyerName" => [
                "firstName" => $user->first_name,
                "lastName" => $user->last_name
            ]
        ];
        $data['trx_id'] = $transaction->id; // used to identify the transaction after payment has been processed
        $data['merchant_trade_no'] = '9825382937292' // Provide an unique code;
    
    
        $transaction = Transaction::create([
            'user_id' => $user->id, 
            'package_id' => $product->id,
            'merchant_trade_no' => $data['merchant_trade_no'],
            'currency' => "USDT",
            'amount' => $product->amount
            // others  
        ]);
        
        $binancePay = new BinancePay("binancepay/openapi/v2/order");
        $res = $binancePay->createOrder($data);
        
        if ($result['status'] === 'SUCCESS') {
          // DO YOUR MAGIC. ITS UPTO YOU 😎
        }
        
        // FAIL
        
        // Other logics 
    }

    use CryptoPay\Binancepay\BinancePay;

    // GET /binancepay/returnUrl
    public function returnCallback(Request $request)
    { 
        return $this->checkOrderStatus($request);
    }
    
    // GET /binancepay/cancelURL
    public function cancelCallback(Request $request)
    {
        return $this->checkOrderStatus($request);
    }
    
    private function checkOrderStatus(Request $request): RedirectResponse
    {  
        $transaction = Transaction::findOr($request->get('trx-id'), function () {
            // return redirect()->route('preferred-route')
            //                  ->with('warning', 'Something went wrong'); // show success invoice
        });

        $order_status = (new BinancePay("binancepay/openapi/v2/order/query"))
                            ->query(['merchantTradeNo' => $transaction->merchant_trade_no]);
           
        // Save transaction status or whatever you like according to the order status
        
        // $transaction->update(['status' => $order_status['data']['status']];
        // dd($order_status);
        
        // ITS UPTO YOU 😎
    }


$payload = $headers['Binancepay-Timestamp'] . "\n" . $headers['Binancepay-Nonce'] . "\n" .
$entityBody . "\n";

$decodedSignature = base64_decode ( $headers['Binancepay-Signature'] );

openssl_verify($payload, $decodedSignature, $publicKey, OPENSSL_ALGO_SHA256 );

    use CryptoPay\Binancepay\BinancePay;


    public function callback(Request $request): JsonResponse
    {
        $webhookResponse = $request->all();
        $publicKey = (new BinancePay("binancepay/openapi/certificates"))
                        ->query($webhookResponse);
        try {
            if ($publicKey['status'] === "SUCCESS") {
            
                $payload = $request->header('Binancepay-Timestamp') . "\n" . 
                            $request->header('Binancepay-Nonce') . "\n" . 
                            json_encode($webhookResponse, JSON_THROW_ON_ERROR) . "\n";
                            
                $decodedSignature = base64_decode($request->header('Binancepay-Signature'));
            
                if (openssl_verify($payload, $decodedSignature, $publicKey['data'][0]['certPublic'], OPENSSL_ALGO_SHA256)) {
                    $merchantTradeNo = json_decode($webhookResponse['data'], true, 512, JSON_THROW_ON_ERROR)['merchantTradeNo'];
                    
                    $transaction = Transaction::where('merchant_trade_no', $merchantTradeNo)->firstOr(
                                    function () use ($merchantTradeNo) {
                                        throw new \RuntimeException("Order could not be found!: " . $merchantTradeNo);
                                    });
                                    
                    switch ($webhookResponse['bizStatus']) {
                        case "PAY_SUCCESS":
                            
                            // $order_status = (new BinancePay("binancepay/openapi/v2/order/query"))->query(compact('merchantTradeNo'));
                            
                            // DO YOUR MAGIC HERE PAYMENT IS SUCCESS 😎
                            break;
                        case "PAY_CLOSED":
                            // OHH... PAYMENT IS FAILED πŸ™
                            break;
                    }
                    
                } else {
                    throw new \RuntimeException("Signature verification failedπŸ˜’πŸ€¨");
                }
            } else {
                throw new \RuntimeException($publicKey["errorMessage"]);
            }
        }catch (Exception $e) {
            return response()->json(['returnCode' => 'FAIL', 'returnMessage' => $e->getMessage()], 200);
        }
        return response()->json(['returnCode' => 'SUCCESS', 'returnMessage' => null], 200);
    }