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

Rdstation Laravel Package

silici0/rdstation

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require silici0/rdstation:dev-master
    php artisan vendor:publish --provider="silici0\RDStation\RDStationServiceProvider"
    php artisan migrate
    
  2. Configure API Credentials

    • Register an app at RDStation App Store.
    • Set client_id and client_secret in config/rdstation.php.
    • Configure the callback URL (yourdomain.com/rdstation) in the RDStation app settings.
  3. Authenticate

    • Visit yourdomain.com/rdstation to authorize the app.
    • After authorization, the package stores the code and auth_key in the database.
  4. First Use Case: Create/Update a Lead

    $rdstation = resolve('rdstation');
    $leadData = [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'personal_phone' => '(11) 98765-4321'
    ];
    $rdstation->createOrUpdate($leadData);
    

Implementation Patterns

Core Workflows

  1. Lead Management

    • Create/Update Leads: Use createOrUpdate() with an associative array of lead attributes.
      $rdstation->createOrUpdate([
          'email' => 'lead@example.com',
          'first_name' => 'Lead',
          'last_name' => 'User',
          'company_name' => 'Test Co.'
      ]);
      
    • Fetch Leads: Retrieve leads by email or ID.
      $lead = $rdstation->getLeadByEmail('lead@example.com');
      
  2. Event Tracking

    • Save Events: Track user interactions (e.g., conversions, page views) with saveEvent().
      $eventData = [
          'email' => 'user@example.com',
          'client_tracking_id' => Cookie::get('_rdtrk'),
          'traffic_source' => Cookie::get('__trf.src')
      ];
      $rdstation->saveEvent('PURCHASE_CONVERSION', $eventData);
      
    • UTM Parameters: Automatically capture UTM sources from cookies or query strings.
      $utmSource = request()->input('utm_source', Cookie::get('__trf.src'));
      $eventData['traffic_source'] = $utmSource;
      
  3. Funnel Updates

    • Update Funnel Stages: Use updateFunnel() to move leads through stages (e.g., "Lead," "Opportunity").
      $rdstation->updateFunnel('lead@example.com', 'OPENED_TICKET');
      
  4. Webhook Handling

    • Listen for Events: Register a route to handle RDStation webhook callbacks (e.g., POST /rdstation/webhook).
      Route::post('/rdstation/webhook', function (Request $request) {
          $rdstation = resolve('rdstation');
          $rdstation->handleWebhook($request->all());
      });
      

Integration Tips

  • Middleware for Auth: Protect routes requiring RDStation access with middleware.
    Route::middleware(['rdstation.auth'])->group(function () {
        Route::post('/leads', 'LeadController@store');
    });
    
  • Service Container Binding: Bind the RDStation client to the container for dependency injection.
    $this->app->bind('rdstation', function ($app) {
        return new \silici0\RDStation\RDStation($app['config']['rdstation']);
    });
    
  • Batch Processing: Use loops for bulk lead updates or event tracking.
    foreach ($leads as $lead) {
        $rdstation->createOrUpdate($lead);
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication Flow

    • Issue: The code and auth_key must be manually authorized via the callback URL (yourdomain.com/rdstation). Forgetting this step will result in 401 Unauthorized errors.
    • Fix: Ensure the callback URL is accessible and the user completes the OAuth flow.
  2. Rate Limiting

    • Issue: RDStation API has rate limits (e.g., 100 requests/minute). Exceeding limits may cause temporary bans.
    • Fix: Implement retries with exponential backoff or batch requests.
      try {
          $rdstation->createOrUpdate($lead);
      } catch (\silici0\RDStation\Exceptions\RateLimitException $e) {
          sleep(10); // Wait before retrying
          $rdstation->createOrUpdate($lead);
      }
      
  3. Lead Email as Key

    • Issue: The email field is required for most operations (e.g., createOrUpdate, getLeadByEmail). Missing or invalid emails will fail silently or return errors.
    • Fix: Validate emails before calling RDStation methods.
      if (!filter_var($lead['email'], FILTER_VALIDATE_EMAIL)) {
          throw new \InvalidArgumentException('Invalid email provided.');
      }
      
  4. Webhook Verification

    • Issue: RDStation webhooks must be verified using a shared secret. Failing to validate the signature can expose your endpoint to spoofing.
    • Fix: Use the handleWebhook() method and ensure the webhook_secret is set in config/rdstation.php.
      $rdstation->handleWebhook($request->all(), $request->header('X-Signature'));
      
  5. Database Dependencies

    • Issue: The package requires the rdstation_codes and rdstation_auth_keys tables. Skipping migrations will cause TableNotFoundException.
    • Fix: Always run migrations after publishing the config.
      php artisan migrate
      

Debugging Tips

  • Enable Logging: Configure the log_level in config/rdstation.php to debug API responses.
    'log_level' => 'debug', // Options: 'debug', 'info', 'error'
    
  • API Response Inspection: Use Laravel's logging or dd() to inspect raw responses.
    $response = $rdstation->getLeadByEmail('test@example.com');
    \Log::debug('RDStation Response:', $response);
    
  • OAuth Debugging: Check the rdstation_codes table for stored code values during the auth flow.

Extension Points

  1. Custom Fields

    • Use Case: RDStation supports custom fields (e.g., custom_field_1). Extend the package by adding methods to handle them.
    • Example:
      $rdstation->setCustomField('lead@example.com', 'custom_field_1', 'Value');
      
    • Implementation: Override the createOrUpdate method or add a new one in a service class.
  2. Event Hooks

    • Use Case: Trigger custom logic after lead creation or event tracking.
    • Example:
      $rdstation->afterCreateOrUpdate(function ($leadData) {
          \Log::info('Lead created/updated:', $leadData);
          // Send Slack notification, etc.
      });
      
    • Implementation: Use Laravel events or decorate the RDStation client.
  3. API Versioning

    • Use Case: Switch between RDStation API versions (e.g., v1 to v2) without breaking changes.
    • Implementation: Create a facade or abstract class to wrap the client and support version-specific logic.
      class RDStationClient {
          public function __call($method, $args) {
              if (method_exists($this->client, $method)) {
                  return $this->client->$method(...$args);
              }
              // Fallback or custom logic
          }
      }
      
  4. Testing

    • Use Case: Mock RDStation responses in unit tests.
    • Example:
      $mock = Mockery::mock('overload:' . \silici0\RDStation\RDStation::class);
      $mock->shouldReceive('createOrUpdate')->andReturn(['success' => true]);
      
    • Implementation: Use Laravel's HTTP testing or mock the service provider.
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver