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

Mentor Pay Bundle Laravel Package

bledniy/mentor-pay-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bledniy/mentor-payment
    

    Publish the bundle’s configuration:

    php artisan vendor:publish --provider="MentorPay\Bundle\MentorPayBundle" --tag="config"
    
  2. Environment Configuration Add to .env:

    MENTOR_PAY_API_KEY=your_api_key_here
    MENTOR_PAY_SECRET_KEY=your_secret_key_here
    MENTOR_PAY_BASE_URL=https://api.mentorpay.example
    
  3. First Use Case: Creating a Payment Inject the client into a controller/service:

    use MentorPay\Bundle\Client;
    
    class PaymentController extends Controller
    {
        public function __construct(private Client $client) {}
    
        public function createPayment()
        {
            $payment = $this->client->createPayment([
                'amount' => 100.00,
                'currency' => 'USD',
                'description' => 'Mentorship fee',
                'metadata' => ['user_id' => 123],
            ]);
    
            return response()->json($payment);
        }
    }
    
  4. Key Files to Review

    • config/mentor_pay.php (default config)
    • src/Client.php (core API interactions)
    • src/Exception/ (error handling)

Implementation Patterns

Workflows

1. Payment Processing

  • Create & Confirm Payments Use Client::createPayment() for one-time payments or Client::createSubscription() for recurring.

    $payment = $this->client->createPayment($data);
    $confirmed = $this->client->confirmPayment($payment->id);
    
  • Webhook Handling Validate webhooks via Client::validateWebhook():

    public function handleWebhook(Request $request)
    {
        if ($this->client->validateWebhook($request->getContent(), $request->headers->get('X-Signature'))) {
            $event = $this->client->parseWebhook($request->getContent());
            // Process event (e.g., payment.succeeded)
        }
    }
    

2. Subscription Management

  • Create/Update Subscriptions

    $subscription = $this->client->createSubscription([
        'plan_id' => 'premium_monthly',
        'customer_id' => 'cus_123',
    ]);
    
  • Cancel/Resume Subscriptions

    $this->client->cancelSubscription($subscription->id);
    $this->client->resumeSubscription($subscription->id);
    

3. Customer Management

  • Create/Retrieve Customers
    $customer = $this->client->createCustomer([
        'name' => 'John Doe',
        'email' => 'john@example.com',
    ]);
    

Integration Tips

Laravel-Specific

  • Service Provider Binding Bind the Client to the container in AppServiceProvider:

    $this->app->bind(MentorPay\Bundle\Client::class, function ($app) {
        return new MentorPay\Bundle\Client($app['config']['mentor_pay']);
    });
    
  • Middleware for Authenticated Requests Create middleware to attach API keys to requests:

    public function handle($request, Closure $next)
    {
        $request->headers->set('Authorization', 'Bearer ' . config('mentor_pay.api_key'));
        return $next($request);
    }
    

Testing

  • Mock the Client Use Laravel’s Mockery to stub API calls:

    $mock = Mockery::mock(MentorPay\Bundle\Client::class);
    $mock->shouldReceive('createPayment')->andReturn((object)['id' => 'pay_123']);
    $this->app->instance(MentorPay\Bundle\Client::class, $mock);
    
  • Test Webhooks Locally Use php artisan mentor-pay:webhook-test (if the bundle includes a test command) or manually trigger events via Client::simulateWebhook().


Gotchas and Tips

Pitfalls

1. API Key Management

  • Never hardcode keys in config files. Use Laravel’s .env or a secrets manager.
  • Rotate keys after leaks: Update MENTOR_PAY_SECRET_KEY and regenerate webhook signatures.

2. Idempotency

  • Use idempotency_key for critical operations (e.g., payments) to avoid duplicate charges:
    $this->client->createPayment([
        'amount' => 100.00,
        'idempotency_key' => 'unique_key_here',
    ]);
    

3. Webhook Validation

  • Always validate signatures in production. Skipping this risks replay attacks:
    if (!$this->client->validateWebhook($rawBody, $signature)) {
        abort(403, 'Invalid webhook signature');
    }
    

4. Rate Limiting

  • The API may throttle requests. Implement exponential backoff in retries:
    try {
        $this->client->createPayment($data);
    } catch (RateLimitExceededException $e) {
        sleep(2 ** $e->getRetryAfter());
        retry();
    }
    

Debugging

1. Enable Logging

Configure Monolog in config/mentor_pay.php:

'logging' => [
    'enabled' => true,
    'channel' => 'single',
],

Logs will appear in storage/logs/laravel.log.

2. Common Errors

Error Cause Solution
Invalid API Key Wrong MENTOR_PAY_API_KEY Verify .env and regenerate keys.
Webhook signature mismatch Incorrect MENTOR_PAY_SECRET_KEY Update key and regenerate webhook secrets.
Plan not found Invalid plan_id Check API docs for valid plan IDs.
Customer already exists Duplicate customer_id Use updateCustomer() instead.

3. Testing Locally

  • Use the MentorPay Sandbox (if available) with test keys.
  • For webhooks, test with:
    curl -X POST -H "X-Signature: $SIGNATURE" -d '{"type":"payment.succeeded"}' http://localhost/webhook
    

Extension Points

1. Custom Responses

Extend the Client to transform responses:

class CustomClient extends MentorPay\Bundle\Client
{
    public function createPayment(array $data)
    {
        $response = parent::createPayment($data);
        return (object) [
            'id' => $response->id,
            'formatted_amount' => '$' . $response->amount,
        ];
    }
}

2. Event Dispatching

Listen for MentorPay events via Laravel’s event system:

// In EventServiceProvider
protected $listen = [
    MentorPay\Bundle\Events\PaymentSucceeded::class => [
        HandleSuccessfulPayment::class,
    ],
];

3. Custom Webhook Handlers

Override the default handler:

public function handleWebhook(Request $request)
{
    $event = $this->client->parseWebhook($request->getContent());
    match ($event->type) {
        'payment.succeeded' => $this->handlePaymentSuccess($event),
        'subscription.canceled' => $this->handleSubscriptionCancel($event),
        default => null,
    };
}

4. API Versioning

If the bundle supports multiple API versions, specify in config:

'api_version' => '2023-10', // Check MentorPay docs for latest
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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