PHP code example of msen / coinbase-commerce-symfony-bundle

1. Go to this page and download the library: Download msen/coinbase-commerce-symfony-bundle 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/ */

    

msen / coinbase-commerce-symfony-bundle example snippets


/**
* get the coinbase handler
* @var CoinbaseHandler $coinbaseHandler
*/
$coinbaseHandler = $this->container->get('coinbase.commerce');

   /**
    * @Route("/acceptcrypto/", name="acceptcrypto")
    */
    public function acceptDonation(){
        $amount = 3.6;//$3.6 dollars
        $json =  [
           "name" => "Cancer Donation Box",
           "description" => "Donate to Children",
           "local_price" => array("amount" => $amount, "currency" => "USD"),
           "pricing_type" => "fixed_price",
           "metadata" => array("id" => "1234", "firstname" => "John", "lastname" => "Doe", "email" => "[email protected]")
        ];
        
        /**
        * @var CoinbaseHandler $coinbaseHandler
        */
        $coinbaseHandler = $this->container->get('coinbase.commerce');
        
        /**
        * @var Charge $charge
        */
        $charge = $coinbaseHandler->createNewCharge($json);//get the charge object

        $this->redirect($charge->getHostedUrl());//it will redirect you to the coinbase crypto box to be paid in 15 minutes
    }

$code = "2G3GM4X9";
/**
* get a single charge
* @var Charge $charge
*/
$charge = $coinbaseHandler->showCharge($code);
$hosted_url = $charge->getHostedUrl();

/**
* list charges
* @var Charges $charges
*/
$charges = $this->_coinbaseHandler->listCharges();

//iterate through the charges
foreach ($charges->getData() as $charge){
    print_r($charge);
}



namespace App\Tests\Controller;


use App\Coinbase\Commerce\Handler\CoinbaseHandler;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\DependencyInjection\Container;

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

class TestCoinbaseCommerceSymfonySDK extends KernelTestCase
{
    /**
     * @var Container
     */
    protected $_container;

    /**
     * @var EntityManager
     */
    protected $_entityManager;

    /**
     * @var CoinbaseHandler
     */
    protected $_coinbaseHandler;

    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        try {
            $kernel = self::bootKernel();
            $this->_container = $kernel->getContainer();

            /** @var EntityManager entityManager */
            $this->_entityManager = $this->_container
                ->get("doctrine")->getManager();

            /**
             * @var CoinbaseHandler
             */
            try {
                $this->_coinbaseHandler = $this->_container->get('coinbase.commerce');
            } catch (\Exception $e) {
                echo $e->getMessage(), EOL;
            }


        } catch (\Exception $e) {
            echo $e->getMessage(), EOL;
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function tearDown(){
        parent::tearDown();
        $this->_entityManager->close();
        $this->_entityManager = null; // avoid memory leaks
    }

    public function ignore_testServices()
    {
        $this->assertNotNull($this->_entityManager, "Entity Manager is null!!!");
        $this->assertNotNull($this->_container, "Container is null!!!");
        $this->assertNotNull($this->_coinbaseHandler, "Coinbase Handler is null!!!");
    }
    
    public function ignore_testCreateNewChargeWithJsonArray(){
    
        $amount = 3.6;//$3.6 dollars
        $json =  [
            "name" => "Cancer Donation Form",
             "description" => "Donation to Children",
             "local_price" => array("amount" => $amount, "currency" => "USD"),
             "pricing_type" => "fixed_price",
             "metadata" => array("id" => "123456", "firstname" => "John", "lastname" => "Doe", "email" => "[email protected]")
        ];
    
        /**
        * @var Charge $charge
        */
        try {
            $charge = $this->_coinbaseHandler->createNewCharge($json);
        } catch (\Exception $e) {
            echo $e->getMessage(), EOL;
        }
        echo "code: " . $charge->getCode(), EOL;
        echo "name: " . $charge->getName(), EOL;
        $this->assertNotNull($charge);
        $this->assertEquals("Cancer Donation Form", $charge->getName());
    }
    
    public function ignore_testCreateNewChargeWithObject(){
    
        /**
        * @var Charge $charge
        */
        $charge = new Charge();
        $charge->setName("Cancer Donation Form");
        $charge->setDescription("Donation to Children");
        $charge->setPricingType("fixed_price");
    
        $localPrice = new Money();
        $localPrice->setAmount(2.6);
        $localPrice->setCurrency("USD");
        $charge->setLocalPrice($localPrice);
    
        //Whatever object fields you wanna put
        $metadata = new Metadata();
        $metadata->id = "1234";
        $metadata->firstname = "Melisa";
        $metadata->lastname = "Doe";
        $metadata->email = "[email protected]";
        $charge->setMetadata($metadata);
    
        /**
        * @var Charge $charge
        */
        try {
            $charge = $this->_coinbaseHandler->createNewCharge($charge);
        } catch (\Exception $e) {
            echo $e->getMessage(), EOL;
        }
        $this->assertNotNull($charge);
        print_r($charge);
    }
    
    public function ignore_testCreateNewChargeWithJsonString(){
        
        $json_string = "{\"name\":\"Cancer Donation Form\",\"description\":\"Donation to Children\",\"pricing_type\":\"fixed_price\",\"local_price\":{\"amount\":\"2.7\",\"currency\":\"USD\"},\"meta_data\":{\"id\":\"12345\",\"firstname\":\"Victor\",\"lastname\":\"Doe\",\"email\":\"[email protected]\"}}";
    
        /**
        * @var Charge $charge
        */
        try {
            $charge = $this->_coinbaseHandler->createNewCharge($json_string);
        } catch (\Exception $e) {
            echo $e->getMessage(), EOL;
        }
        $this->assertNotNull($charge);
        print_r($charge);
    }
    
    public function ignore_testShowACharge(){
        $code = "2G3GM4X9";
        /**
        * @var Charge $charge
        */
        $charge = $this->_coinbaseHandler->showCharge($code);
        print_r($charge);
        $this->assertNotNull($charge);
    }
    
    public function ignore_testListCharges(){
        /**
        * @var Charges $charges
        */
        $charges = $this->_coinbaseHandler->listCharges();
        print_r($charges);
        $this->assertNotNull($charges);
        foreach ($charges->getData() as $charge){
           print_r($charge);
        }
    }
}

/** @var Webhook $webhook */
$webhook = $this->_coinbaseHandler->parseWebhook($jsonString);

    /**
    * @Route("/webhooks/", name="webhooks")
    * @throws \Exception
    */
    public function webHook(Request $request){

        if ($request->getMethod() != 'POST') {
            return new Response( 'Only post requests accepted!',  400);
        }

        $jsonString = $request->getContent();//get the json string from the request

        /**
         * @var CoinbaseHandler $coinbaseHandler
         */
        $coinbaseHandler = $this->container->get('coinbase.commerce');

        // This header contains the SHA256 HMAC signature of the raw request payload
        $cc_signagure = isset($_SERVER["HTTP_X_CC_WEBHOOK_SIGNATURE"]) ? $_SERVER["HTTP_X_CC_WEBHOOK_SIGNATURE"] : '';
        if(!$coinbaseHandler->validateWebhookSignature($cc_signagure, $request)){
                throw new \Exception("Request could not be validated");
        }
        
        /** @var Webhook $webhook */
        $webhook = $coinbaseHandler->parseWebhook($jsonString);
        //You have your webhook object. Do Something... save webhook data to database or email people or anything useful

        if($webhook->getEvent()->getType() == Event::TYPE_CHARGE_CREATED){
            //Do Something
        }

        return new Response('',Response::HTTP_OK, array('Content-Type' => 'text/html'));//make sure you respond with status 200 (OK) at the end
    }


public function testParseWebhook(){

        $jsonString = "{
             \"id\": 1,
             \"scheduled_for\": \"2017-01-31T20:50:02Z\",
             \"event\": {
                    \"id\": \"24934862-d980-46cb-9402-43c81b0cdba6\",
                    \"type\": \"charge:created\",
                    \"api_version\": \"2018-03-22\",
                    \"created_at\": \"2017-01-31T20:49:02Z\",
                    \"data\": {
                    \"code\": \"66BEOV2A\",
                    \"name\": \"The Sovereign Individual\",
                    \"description\": \"Mastering the Transition to the Information Age\",
                    \"hosted_url\": \"https://commerce.coinbase.com/charges/66BEOV2A\",
                    \"created_at\": \"2017-01-31T20:49:02Z\",
                    \"expires_at\": \"2017-01-31T21:04:02Z\",
                    \"timeline\": [
                       {
                          \"time\": \"2017-01-31T20:49:02Z\",
                                \"status\": \"NEW\"
                       }
                    ],
                    \"metadata\": {},
                        \"pricing_type\": \"no_price\",
                        \"payments\": [],
                        \"addresses\": {
                            \"bitcoin\": \"mymZkiXhQNd6VWWG7VGSVdDX9bKmviti3U\",
                            \"ethereum\": \"0x419f91df39951fd4e8acc8f1874b01c0c78ceba6\"
                        }
                    }
                  }
               }";


        /** @var Webhook $webhook */
        $webhook = $this->_coinbaseHandler->parseWebhook($jsonString);
        $this->assertNotNull($webhook);
        print_r($webhook);
    }

public function testWebhookController(){


        $jsonString = "{
                    \"id\": 1,
                    \"scheduled_for\": \"2017-01-31T20:50:02Z\",
                    \"event\": {
                        \"id\": \"24934862-d980-46cb-9402-43c81b0cdba6\",
                        \"type\": \"charge:created\",
                        \"api_version\": \"2018-03-22\",
                        \"created_at\": \"2017-01-31T20:49:02Z\",
                        \"data\": {
                        \"code\": \"66BEOV2A\",
                        \"name\": \"The Sovereign Individual\",
                        \"description\": \"Mastering the Transition to the Information Age\",
                        \"hosted_url\": \"https://commerce.coinbase.com/charges/66BEOV2A\",
                        \"created_at\": \"2017-01-31T20:49:02Z\",
                        \"expires_at\": \"2017-01-31T21:04:02Z\",
                        \"timeline\": [
                            {
                                \"time\": \"2017-01-31T20:49:02Z\",
                                \"status\": \"NEW\"
                            }
                         ],
                        \"metadata\": {},
                        \"pricing_type\": \"no_price\",
                        \"payments\": [],
                        \"addresses\": {
                            \"bitcoin\": \"mymZkiXhQNd6VWWG7VGSVdDX9bKmviti3U\",
                            \"ethereum\": \"0x419f91df39951fd4e8acc8f1874b01c0c78ceba6\"
                        }
                    }
                   }
               }";

        $json_array = json_decode($jsonString, true);


        $client = static::createClient();
        $client->request('POST', '/webhooks/',
            $json_array, //parameters
            array(), //files
            array( //server
                'CONTENT_TYPE' => 'application/json'
            ),
            $jsonString
        );

        $content = $client->getResponse();
        print_r($content);
        $json = json_decode($content);
        print_r($json);
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }


/**
 * Created by PhpStorm.
 * User: msen
 * Date: 7/8/18
 * Time: 3:17 PM
 */

namespace App\Coinbase\Commerce\Tests;

use App\Coinbase\Commerce\Handler\CoinbaseHandler;
use App\Coinbase\Commerce\Model\Webhook;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\Container;

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

class TestWebHook extends WebTestCase
{
    /**
     * @var Container
     */
    protected $_container;

    /**
     * @var EntityManager
     */
    protected $_entityManager;

    /**
     * @var CoinbaseHandler
     */
    protected $_coinbaseHandler;

    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        try {

            $kernel = self::bootKernel();
            $this->_container = $kernel->getContainer();

            /** @var EntityManager entityManager */
            $this->_entityManager = $this->_container
                ->get("doctrine")->getManager();

            /**
             * @var CoinbaseHandler
             */
            $this->_coinbaseHandler = $this->_container->get('coinbase.commerce');
            //print_r($this->_coinbaseHandler);

        } catch (\Exception $e) {
            echo $e->getMessage(), EOL;
        }
    }


    public function ignore_testParseWebhook(){

        $jsonString = "{
                    \"id\": 1,
                    \"scheduled_for\": \"2017-01-31T20:50:02Z\",
                    \"event\": {
                        \"id\": \"24934862-d980-46cb-9402-43c81b0cdba6\",
                        \"type\": \"charge:created\",
                        \"api_version\": \"2018-03-22\",
                        \"created_at\": \"2017-01-31T20:49:02Z\",
                        \"data\": {
                        \"code\": \"66BEOV2A\",
                        \"name\": \"The Sovereign Individual\",
                        \"description\": \"Mastering the Transition to the Information Age\",
                        \"hosted_url\": \"https://commerce.coinbase.com/charges/66BEOV2A\",
                        \"created_at\": \"2017-01-31T20:49:02Z\",
                        \"expires_at\": \"2017-01-31T21:04:02Z\",
                        \"timeline\": [
                            {
                                \"time\": \"2017-01-31T20:49:02Z\",
                                \"status\": \"NEW\"
                            }
                         ],
                        \"metadata\": {},
                        \"pricing_type\": \"no_price\",
                        \"payments\": [],
                        \"addresses\": {
                            \"bitcoin\": \"mymZkiXhQNd6VWWG7VGSVdDX9bKmviti3U\",
                            \"ethereum\": \"0x419f91df39951fd4e8acc8f1874b01c0c78ceba6\"
                        }
                    }
                   }
               }";


        /** @var Webhook $webhook */
        $webhook = $this->_coinbaseHandler->parseWebhook($jsonString);
        $this->assertNotNull($webhook);
        print_r($webhook);
    }

    public function ignore_testWebhookController(){


        $jsonString = "{
                    \"id\": 1,
                    \"scheduled_for\": \"2017-01-31T20:50:02Z\",
                    \"event\": {
                        \"id\": \"24934862-d980-46cb-9402-43c81b0cdba6\",
                        \"type\": \"charge:created\",
                        \"api_version\": \"2018-03-22\",
                        \"created_at\": \"2017-01-31T20:49:02Z\",
                        \"data\": {
                        \"code\": \"66BEOV2A\",
                        \"name\": \"The Sovereign Individual\",
                        \"description\": \"Mastering the Transition to the Information Age\",
                        \"hosted_url\": \"https://commerce.coinbase.com/charges/66BEOV2A\",
                        \"created_at\": \"2017-01-31T20:49:02Z\",
                        \"expires_at\": \"2017-01-31T21:04:02Z\",
                        \"timeline\": [
                            {
                                \"time\": \"2017-01-31T20:49:02Z\",
                                \"status\": \"NEW\"
                            }
                         ],
                        \"metadata\": {},
                        \"pricing_type\": \"no_price\",
                        \"payments\": [],
                        \"addresses\": {
                            \"bitcoin\": \"mymZkiXhQNd6VWWG7VGSVdDX9bKmviti3U\",
                            \"ethereum\": \"0x419f91df39951fd4e8acc8f1874b01c0c78ceba6\"
                        }
                    }
                   }
               }";

        $json_array = json_decode($jsonString, true);


        $client = static::createClient();
        $client->request('POST', '/webhooks/',
            $json_array, //parameters
            array(), //files
            array( //server
                'CONTENT_TYPE' => 'application/json'
            ),
            $jsonString
        );

        $content = $client->getResponse();
        print_r($content);
        $json = json_decode($content);
        print_r($json);
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }
}