advanced
stripe
payments
sync

Stripe Data Synchronization

Complete guide to synchronizing payment data between Stripe and Levy Fleets including CSV imports, API sync, and webhook integration

Levy Fleets Team25 décembre 202522 min read

Stripe Data Synchronization

The Stripe Data Sync feature enables synchronization of payment data between Stripe and Levy Fleets. This includes importing historical charges from CSV exports and real-time syncing via the Stripe API. This guide covers all aspects of Stripe integration for payment data management.

Accessing Stripe Import

Navigate to Admin > Stripe Import to access the Stripe data sync interface.

Requirements:

  • Admin access to the system
  • Stripe integration configured
  • Valid Stripe API credentials (for API sync)

Overview

Sync Methods

MethodDescriptionUse Case
CSV ImportUpload Stripe charge exportHistorical data, bulk import
API SyncFetch from Stripe APIRecent charges, real-time
WebhooksAutomatic push from StripeOngoing live updates

Data Captured

When syncing Stripe charges, the following data is stored:

Charge Details:

  • Charge ID, amount, currency, status
  • Created timestamp, captured status
  • Refund information (amount, date)
  • Payment intent ID

Card Information:

  • Card ID, brand, last 4 digits
  • Expiration month/year
  • Card fingerprint, funding type
  • AVS and CVC verification status

Customer Information:

  • Stripe Customer ID
  • Customer email and phone
  • Customer description

Ride Metadata (from charge metadata):

  • Ride ID, user ID, customer ID
  • Start/end coordinates
  • Distance and duration
  • Payment type and credits used

Dashboard Statistics

The Stripe Import page displays four metric cards:

MetricDescription
Total ChargesCount of all synced charge records
Today's ChargesCharges created today
Latest ChargeTimestamp of most recent charge
Webhook EventsTotal logged webhook events

These metrics update after each sync operation.


CSV Import

Exporting from Stripe

1

Log into Stripe Dashboard

Navigate to dashboard.stripe.com and log in to your account.

2

Navigate to Payments

Go to Payments > All payments in the sidebar.

3

Click Export

Click the Export button in the top-right corner.

4

Select Date Range

Choose the date range for the charges you want to export.

5

Choose CSV Format

Select CSV as the export format.

6

Download the File

Download the exported file to your computer.

Importing the CSV

  1. In Levy Fleets, go to Admin > Stripe Import
  2. Locate the "Import CSV" section
  3. Drag-and-drop your CSV file or click to browse
  4. Click "Import CSV (Background)"
  5. Import job starts processing

File Size Handling

File SizeProcessing Method
< 10 MBStandard background import
10+ MBClient-side parsing with batch upload

For very large files (10+ MB):

  • File is parsed in the browser
  • Data sent to server in 500-row batches
  • Progress displayed for each batch

Import Progress

The import runs in the background:

  • Progress bar shows completion percentage
  • Status updates every 2 seconds (polling)
  • Notification when complete
  • Error count displayed if issues occur

CSV Columns Mapped

Key columns from Stripe export:

Stripe ColumnDatabase Field
idcharge_id
Created date (UTC)created_at
Amountamount
Amount Refundedamount_refunded
Currencycurrency
Statusstatus
Capturedcaptured
Card Last4card_last4
Card Brandcard_brand
Customer IDcustomer_id
Customer Emailcustomer_email
ride_number (metadata)metadata_ride_number
user_id (metadata)metadata_user_id
customerId (metadata)metadata_customer_number

Plus 40+ additional columns for complete charge data.


API Sync

Manual Sync

  1. In the Stripe Import page, find "Manual Sync" section
  2. Click "Sync Last 24 Hours"
  3. System fetches charges from Stripe API
  4. Results display: imported, updated, errors

What Gets Synced

  • All charges created in the last 24 hours
  • Paginated fetching (100 per request)
  • Automatic handling of large result sets
  • Upserts (inserts new, updates existing)

Sync Results

After sync completes:

  • Imported: New charges added
  • Updated: Existing charges refreshed
  • Errors: Charges that failed to sync

Webhook Integration

How Webhooks Work

Stripe sends real-time notifications to Levy Fleets:

  1. Event occurs in Stripe (charge, payment, etc.)
  2. Stripe sends POST to /api/webhooks/stripe
  3. Levy Fleets validates signature
  4. Event processed and data updated
  5. Response sent to Stripe

Supported Webhook Events

Charge Events:

Event TypeAction
charge.succeededUpsert charge, process risk score from Stripe Radar
charge.failedRecord failed charge
charge.capturedUpdate captured status
charge.updatedUpdate charge record
charge.refundedUpdate refund info
charge.expiredUpdate charge status
charge.pendingUpdate charge status

Dispute Events:

Event TypeAction
charge.refund.updatedLog refund updates
charge.dispute.createdLog dispute creation
charge.dispute.updatedLog dispute updates
charge.dispute.closedLog dispute closure
charge.dispute.funds_withdrawnLog funds withdrawn
charge.dispute.funds_reinstatedLog funds reinstated

Payment Intent Events:

Event TypeAction
payment_intent.succeededUpdate wallet balance, save payment method, update ride payment
setup_intent.succeededSave payment method

Customer Events:

Event TypeAction
customer.createdLink Stripe customer to customer record

Identity Verification Events:

Event TypeAction
identity.verification_session.requires_inputUpdate verification status, send notification email
identity.verification_session.processingUpdate verification status
identity.verification_session.canceledUpdate verification status
identity.verification_session.verifiedUpdate verification status, clear verification requirement

Configuring Webhooks

1

Open Stripe Developer Settings

In your Stripe Dashboard, go to Developers > Webhooks

2

Add Endpoint

Click Add endpoint

3

Enter Webhook URL

Enter URL: https://your-domain.com/api/webhooks/stripe

4

Select Events

Select the events you want to receive (see list above)

5

Copy Signing Secret

Copy the Signing secret from the webhook details

6

Add Environment Variable

Add to your environment variables as STRIPE_WEBHOOK_SECRET


Import Job Tracking

Active Jobs Section

The page displays currently processing imports:

Job Card Shows:

  • File name and size
  • Start time
  • Progress bar (processed/total rows)
  • Status badge

Status Indicators:

StatusBadgeDescription
ProcessingBlue spinnerCurrently running
CompletedGreen checkFinished successfully
Completed with ErrorsYellow alertFinished with some failures
FailedRed XCritical error stopped import

Row Counts:

  • Imported: New records created
  • Updated: Existing records updated
  • Skipped: Rows skipped (duplicates, invalid)
  • Errors: Rows that failed

Viewing Past Jobs

The import jobs API tracks:

  • Job ID and type
  • File name and size
  • Start and completion times
  • Row processing statistics
  • Error details (JSONB)

Conflict Handling

Duplicate Prevention

Charges are identified by Stripe charge ID:

  • stripe_charges.id is the primary key
  • ON CONFLICT (id) DO UPDATE prevents duplicates
  • Updates refresh existing records with new data

Customer Matching

When syncing, customers are matched by:

  1. Stripe Customer ID
  2. Email address
  3. Metadata customer_id

Data Merging

On conflict (existing charge):

  • Amount fields updated
  • Status updated
  • Refund info updated
  • Timestamps preserved
  • Metadata merged

Configuration

Required Environment Variables

# Stripe API Keys
STRIPE_SECRET_KEY=sk_live_...       # Live secret key
STRIPE_WEBHOOK_SECRET=whsec_...      # Webhook signing secret

# Optional
STRIPE_TEST_SECRET_KEY=sk_test_...   # Test mode key

API Version

The system uses Stripe API version 2023-10-16. This is set in the configuration and should match your Stripe dashboard settings.


Payment Method Saving

When payment_intent.succeeded or setup_intent.succeeded events are processed:

  1. Payment method ID and Stripe customer ID extracted
  2. Customer looked up by stripe_customer_id
  3. New payment method saved to payment_methods table with:
    • customer_uuid - Link to customer record
    • stripe_payment_method_id - Stripe's payment method ID
    • type - Card type (usually 'card')
    • last4 - Last 4 digits for display
    • brand - Card brand (Visa, Mastercard, etc.)

Wallet Top-ups

When a payment_intent.succeeded event indicates a wallet top-up:

Payment Intent Types (from metadata.type):

  • wallet_topup - Manual wallet top-up by customer
  • auto_topup - Automatic top-up triggered by low balance
  • ride_payment - Direct ride payment

Processing Steps for wallet_topup:

  1. Customer resolved by metadata (customer_uuid, customer_number, or user_id)
  2. Current wallet balance retrieved from customer record
  3. Payment amount added to balance
  4. wallet_transactions record created with type credit
  5. Customer balance updated

Auto Top-up Handling

For auto_topup, the balance and transaction have already been recorded by the client, so no additional wallet update is performed during webhook processing.

Transaction Types:

  • credit - Money added to wallet
  • debit - Money spent from wallet

Ride Payment Updates

When a ride payment completes:

  1. ride_uuid extracted from metadata
  2. Ride record located
  3. total_cost updated with payment amount
  4. Ride marked as paid

Risk Score Processing

From charge outcomes, risk data is captured:

FieldDescription
stripe_risk_score0-100 risk score
stripe_risk_levelnormal, elevated, highest

Risk Level Mapping:

  • normal = score 10
  • elevated = score 50
  • highest = score 75

High risk customers may be flagged for identity verification.


Security

Webhook Validation

All webhooks are validated:

  1. Signature header extracted
  2. stripe.webhooks.constructEvent() verifies signature
  3. Invalid signatures return 400 error
  4. Prevents spoofed events

API Key Security

  • Never expose STRIPE_SECRET_KEY in client code
  • Use environment variables only
  • Rotate keys if compromised
  • Use restricted keys where possible

Data Storage

  • Card numbers not stored (only last 4)
  • Sensitive data encrypted at rest
  • PCI compliance maintained through Stripe

Security Best Practice

Never commit Stripe API keys to version control. Always use environment variables and ensure your .env files are in .gitignore.


Troubleshooting

CSV Import Fails

Possible Causes:

  • Invalid CSV format
  • Wrong column headers
  • File too large
  • Network timeout

Solutions:

  • Verify export is from Stripe
  • Check file isn't corrupted
  • Split large files into smaller chunks
  • Retry with stable connection

API Sync Returns No Data

Possible Causes:

  • No charges in last 24 hours
  • API key invalid or expired
  • Stripe account has no data

Solutions:

  • Expand date range
  • Verify API key in environment
  • Check Stripe dashboard for charges

Webhooks Not Processing

Possible Causes:

  • Webhook secret mismatch
  • Endpoint URL incorrect
  • Server not reachable
  • Event type not subscribed

Solutions:

  • Verify STRIPE_WEBHOOK_SECRET
  • Check endpoint URL in Stripe dashboard
  • Ensure server is accessible
  • Add required event types

Duplicate Charges Appearing

Cause: Same charge processed multiple times

Note: This shouldn't happen due to upsert logic. If it does:

  • Check for unique constraint on charge ID
  • Verify database migrations are current

Best Practices

Regular Syncing

  1. Daily manual sync: Run API sync each morning
  2. Weekly CSV export: Import historical data weekly
  3. Webhook monitoring: Check webhook logs regularly

Data Verification

After syncing:

  1. Compare counts with Stripe dashboard
  2. Spot check recent charges
  3. Verify customer matching is working

Performance

  1. Off-peak imports: Run large CSV imports during low traffic
  2. Monitor webhooks: Keep webhook processing fast
  3. Database indexes: Ensure proper indexes exist

What's Next?

Stripe Integration Ready

With Stripe data sync configured, you'll have complete visibility into payment activity across your fleet. Use webhooks for real-time updates and periodic CSV imports to ensure complete historical data.