Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Blockchain Bundle Laravel Package

aminin/blockchain-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require aminin/blockchain-bundle
    

    For Symfony 4+, the bundle auto-registers via Flex.

  2. Configure API Credentials Add to config/packages/ami_blockchain.yaml (Symfony 4+) or config.yml (Symfony 2/3):

    ami_blockchain:
        api_key: '%env(BLOCKCHAIN_API_KEY)%'  # Use .env for security
        service_url: 'https://blockchain.info/api/v2'  # Default Blockchain.info API URL
    
  3. First Use Case: Fetch Bitcoin Price Inject the service in a controller or command:

    use Ami\BlockchainBundle\Service\BlockchainService;
    
    class CryptoController extends AbstractController
    {
        public function showPrice(BlockchainService $blockchain)
        {
            $price = $blockchain->getTicker();
            return $this->json($price);
        }
    }
    

Implementation Patterns

Core Workflows

  1. API Service Integration Use the BlockchainService to interact with Blockchain.info endpoints:

    // Fetch raw transaction data
    $tx = $blockchain->getRawTransaction('tx_hash_here');
    
    // Get wallet balance
    $balance = $blockchain->getBalance('wallet_address');
    
  2. Event-Driven Notifications Poll for new transactions periodically (e.g., via a Symfony command):

    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class CheckTransactionsCommand extends Command
    {
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $transactions = $this->blockchain->getTransactions('wallet_address');
            foreach ($transactions as $tx) {
                if ($tx['confirmations'] > 0) {
                    $this->notifyUser($tx);
                }
            }
        }
    }
    
  3. Dependency Injection Prefer constructor injection for testability:

    class PaymentService
    {
        public function __construct(private BlockchainService $blockchain) {}
    
        public function verifyPayment(string $txId): bool
        {
            return $this->blockchain->getTransaction($txId)['confirmations'] >= 6;
        }
    }
    
  4. Caching Responses Cache API responses to reduce rate limits (e.g., using Symfony Cache component):

    $cache = $this->container->get('cache.app');
    $key = 'blockchain_ticker';
    $ticker = $cache->get($key, function() use ($blockchain) {
        return $blockchain->getTicker();
    });
    

Gotchas and Tips

Common Pitfalls

  1. API Rate Limits

    • Blockchain.info enforces rate limits. Cache responses aggressively.
    • Example: Cache ticker data for 5 minutes:
      $cache->set('ticker', $ticker, 300); // 5 minutes
      
  2. Deprecated API Endpoints

    • The underlying blockchain/blockchain PHP client may lag behind Blockchain.info’s API updates. Check the client’s GitHub for deprecations.
    • Workaround: Extend the service to wrap raw HTTP calls if needed:
      $client = new \GuzzleHttp\Client();
      $response = $client->get('https://blockchain.info/rawtx/...');
      
  3. Environment Variables

    • Never hardcode API keys in config.yml. Use .env:
      ami_blockchain:
          api_key: '%env(BLOCKCHAIN_API_KEY)%'
      
    • Validate the key exists in config/packages/ami_blockchain.yaml:
      imports:
          - { resource: '.env' }
      
  4. Error Handling

    • The bundle throws exceptions for API errors. Catch them gracefully:
      try {
          $blockchain->getTransaction($txId);
      } catch (\Ami\BlockchainBundle\Exception\BlockchainException $e) {
          $this->addFlash('error', 'Blockchain API error: ' . $e->getMessage());
      }
      

Extension Points

  1. Custom API Endpoints Extend the service to add unsupported endpoints:

    // src/Service/ExtendedBlockchainService.php
    class ExtendedBlockchainService extends BlockchainService
    {
        public function getUnspentOutputs(string $address): array
        {
            $url = $this->serviceUrl . '/unspent?active=' . $address;
            return $this->httpClient->get($url)->json();
        }
    }
    

    Register as a service in config/services.yaml:

    services:
        App\Service\ExtendedBlockchainService:
            decorates: ami_blockchain.blockchain
            arguments: ['@ami_blockchain.blockchain']
    
  2. Webhook Integration Use the bundle to verify incoming webhook signatures (e.g., for payment notifications):

    public function verifyWebhook(Request $request): bool
    {
        $payload = json_decode($request->getContent(), true);
        $signature = $request->headers->get('X-Blockchain-Signature');
        return $this->blockchain->verifyWebhook($payload, $signature);
    }
    
  3. Testing Mock the BlockchainService in tests:

    $mock = $this->createMock(BlockchainService::class);
    $mock->method('getBalance')->willReturn(['balance' => 1.0]);
    $this->container->set('ami_blockchain.blockchain', $mock);
    

Debugging Tips

  • Enable API Logging Add to config/packages/monolog.yaml:

    handlers:
        blockchain:
            type: stream
            path: '%kernel.logs_dir%/blockchain.log'
            level: debug
            channels: ['blockchain']
    

    Then log requests in a custom service decorator.

  • Check HTTP Headers Use stderr to log raw API responses during development:

    $response = $this->httpClient->get($url);
    error_log($response->getBody()->getContents());
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky