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

Purchasecredits Bundle Laravel Package

c975l/purchasecredits-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies

    composer require c975l/purchasecredits-bundle c975l/payment-bundle stripe/stripe-php
    

    Ensure you have a Stripe account and configure c975LPaymentBundle first (see its docs).

  2. Enable Bundles Add to config/bundles.php:

    return [
        // ...
        C975L\PurchaseCreditsBundle\PurchaseCreditsBundle::class => ['all' => true],
        C975L\PaymentBundle\PaymentBundle::class => ['all' => true],
    ];
    
  3. Configure Stripe & Terms of Sale Update .env with Stripe keys:

    STRIPE_SECRET_KEY=your_secret_key
    STRIPE_PUBLISHABLE_KEY=your_publishable_key
    

    Define a PDF route for Terms of Sale (e.g., /terms-of-sale.pdf). Use c975LSiteBundle if needed.

  4. First Use Case: Credit Purchase Form Create a form in a controller:

    use C975L\PurchaseCreditsBundle\Form\CreditPurchaseType;
    
    public function purchaseAction(Request $request)
    {
        $form = $this->createForm(CreditPurchaseType::class);
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
            $creditPurchase = $form->getData();
            $this->get('c975l_purchase_credits.manager')->purchase($creditPurchase);
            // Redirect to success page
        }
        return $this->render('purchase_credits/index.html.twig', ['form' => $form->createView()]);
    }
    

Implementation Patterns

Core Workflows

  1. Credit Purchase Flow

    • Use CreditPurchaseType form to collect:
      • User email (or ID).
      • Credit amount (e.g., 100 for 100 credits).
      • Payment method (handled by c975LPaymentBundle).
    • Trigger purchase via:
      $manager = $this->get('c975l_purchase_credits.manager');
      $manager->purchase($creditPurchase);
      
    • Post-Purchase: The bundle auto-sends an email with:
      • Receipt.
      • Terms of Sale (PDF attachment).
  2. Toolbar Integration

    • Use c975LToolbarBundle to display credit balance:
      {{ toolbar_item('credits', user.credits) }}
      
    • Extend the toolbar via events (see ToolbarBundle docs).
  3. Credit Consumption

    • Deduct credits in services/controllers:
      $this->get('c975l_purchase_credits.manager')->consume($user, 10);
      
    • Validate balance before consumption:
      if (!$manager->hasSufficientCredits($user, 10)) {
          throw new \RuntimeException('Insufficient credits');
      }
      

Integration Tips

  • User Model Extend your User entity to include:

    /**
     * @ORM\Column(type="integer")
     */
    private $credits = 0;
    

    Sync with the bundle’s Credit entity via listeners or services.

  • Custom Emails Override email templates in: templates/C975LPurchaseCreditsBundle/Email/. Extend the PurchaseCreditsEvents to modify email logic.

  • Webhooks Listen for Stripe webhooks to update credits on payment success/failure:

    $this->get('c975l_payment.webhook_handler')->handle(
        $request->getContent(),
        'credit_payment_success'
    );
    
  • Admin Panel Use the bundle’s CRUD for managing credits manually:

    $this->get('c975l_purchase_credits.manager')->adminAddCredits($user, 50);
    

Gotchas and Tips

Pitfalls

  1. Stripe Dependency

    • Error: Class 'Stripe\Stripe' not found.
    • Fix: Ensure stripe/stripe-php is installed and keys are set in .env.
    • Tip: Test Stripe integration separately using c975LPaymentBundle first.
  2. Missing Terms of Sale PDF

    • Error: No route found for PDF attachment.
    • Fix: Define a route for your Terms of Sale PDF (e.g., /terms.pdf) or use c975LSiteBundle to generate it dynamically.
    • Tip: Cache the PDF to avoid regeneration on every purchase.
  3. Email Delivery Failures

    • Error: Emails not sent or bounced.
    • Fix:
      • Verify SMTP settings in config/packages/mailer.yaml.
      • Check PDF attachment size (Stripe may block large files).
    • Tip: Test email templates locally with swiftmailer in dev mode.
  4. Credit Double-Counting

    • Cause: Race conditions during concurrent purchases.
    • Fix: Use database transactions:
      $entityManager->beginTransaction();
      try {
          $manager->purchase($creditPurchase);
          $entityManager->commit();
      } catch (\Exception $e) {
          $entityManager->rollBack();
          throw $e;
      }
      

Debugging

  • Log Stripe Events Enable Stripe logging in .env:

    STRIPE_LOG_LEVEL=debug
    

    Check logs at var/log/stripe.log.

  • Symfony Profiler Use the profiler to inspect:

    • c975l_purchase_credits.manager service calls.
    • Email events (PurchaseCreditsEvents::CREDIT_PURCHASED).
  • Database Dumps Dump the credit table to verify transactions:

    php bin/console doctrine:schema:update --dump-sql
    

Extension Points

  1. Custom Credit Types Extend the Credit entity or create a new one:

    // config/packages/c975l_purchase_credits.yaml
    c975l_purchase_credits:
        credit_classes:
            - App\Entity\CustomCredit
    
  2. Validation Rules Override credit purchase validation:

    // src/EventListener/CreditPurchaseListener.php
    public function onCreditPurchase(PurchaseCreditsEvent $event)
    {
        if ($event->getCreditPurchase()->getAmount() > 1000) {
            throw new \RuntimeException('Max 1000 credits per purchase');
        }
    }
    

    Register the listener in services.yaml:

    services:
        App\EventListener\CreditPurchaseListener:
            tags:
                - { name: kernel.event_listener, event: c975l.purchase_credits.purchase, method: onCreditPurchase }
    
  3. Alternative Payment Gateways Decouple from Stripe by implementing PaymentGatewayInterface:

    class PaypalGateway implements PaymentGatewayInterface
    {
        public function createPaymentIntent($amount, $currency): array
        {
            // PayPal logic here
        }
    }
    

    Register it in services.yaml:

    c975l_purchase_credits.payment_gateway: '@App\Service\PaypalGateway'
    
  4. Multi-Currency Support Extend the CreditPurchase form to include currency:

    $builder->add('currency', ChoiceType::class, ['choices' => ['USD' => 'USD', 'EUR' => 'EUR']]);
    

    Update Stripe integration to handle currency conversion.

Configuration Quirks

  • Default Credit Value Set a default credit value in config/packages/c975l_purchase_credits.yaml:

    c975l_purchase_credits:
        default_credit_value: 10  # 10 credits per default purchase
    
  • Email Templates Override templates by copying from: vendor/c975l/purchasecredits-bundle/Resources/views/Email/ to: templates/C975LPurchaseCreditsBundle/Email/.

  • Toolbar Icons Customize toolbar icons by overriding Twig templates: templates/C975LToolbarBundle/Toolbar/credits.html.twig.

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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware