# ShipStation Integration Setup Guide

This guide walks you through setting up the ShipStation integration for this Next.js application.

## Prerequisites

- Active ShipStation account
- WooCommerce store configured
- Stripe account configured
- Next.js application deployed (or running locally with ngrok)

## Step 1: Get ShipStation API Credentials

1. **Log in to ShipStation**
   - Go to https://ship.shipstation.com

2. **Navigate to API Settings**
   - Click on your profile icon (top right)
   - Select "Account Settings"
   - Click "API Settings" in the left sidebar

3. **Generate API Keys**
   - Click "Generate API Keys" (or view existing keys)
   - Copy your API Key and API Secret
   - **⚠️ Important**: Store these securely - you won't be able to see the secret again

## Step 2: Configure Environment Variables

Add these to your `.env.local` file (or hosting provider's environment variables):

```env
# ShipStation Configuration
SHIPSTATION_API_KEY=your_api_key_here
SHIPSTATION_API_SECRET=your_api_secret_here
SHIPSTATION_WEBHOOK_SECRET=optional_webhook_secret
```

**For this specific installation** (from user's credentials):
```env
SHIPSTATION_API_KEY=45df243c25724253a8085b39e81c26c2
SHIPSTATION_API_SECRET=a99e4153d60a453685936dfd87b1d2df
```

## Step 3: Test API Connection

Run the test script to verify your credentials:

```bash
# Install tsx if you haven't already
npm install -D tsx

# Run the test script
npx tsx scripts/test-shipstation.ts
```

**Expected output**:
```
🚀 Testing ShipStation Integration

1. Checking environment variables...
   ✅ SHIPSTATION_API_KEY: 45df243c...
   ✅ SHIPSTATION_API_SECRET: a99e4153...

2. Testing ShipStation API connectivity...
   ✅ API authentication successful!

3. Testing order creation with mock data...
   ✅ Test order created successfully!
   ShipStation Order ID: 123456789
```

**If authentication fails**:
- Verify API key and secret are correct
- Check for typos or extra spaces
- Regenerate API keys in ShipStation if needed

## Step 4: Configure ShipStation Webhooks

1. **Go to ShipStation Settings**
   - Click "Settings" → "API Settings" → "Webhooks"

2. **Add New Webhook**
   - Click "+ Add Webhook"

3. **Configure Webhook URL**
   
   **For Production**:
   ```
   https://your-domain.com/api/shipstation/webhook
   ```
   
   **For Local Development** (using ngrok):
   ```bash
   # Start ngrok
   ngrok http 3000
   
   # Use the HTTPS URL provided by ngrok
   https://abc123.ngrok.io/api/shipstation/webhook
   ```

4. **Select Events**
   - ✅ `SHIP_NOTIFY` - Order has been shipped
   - ✅ `ITEM_SHIPPED` - Individual items shipped
   - (Optional) `ORDER_NOTIFY` - Order created/updated
   - (Optional) `ITEM_ORDER_NOTIFY` - Item order notification

5. **Save Webhook**
   - Click "Save Webhook"

## Step 5: Verify Stripe Webhook Configuration

Ensure your Stripe webhook is configured to send events to your application.

1. **Go to Stripe Dashboard**
   - Navigate to "Developers" → "Webhooks"

2. **Add or Update Endpoint**
   
   **URL**:
   ```
   https://your-domain.com/api/stripe/webhook
   ```

3. **Select Events**:
   - ✅ `payment_intent.succeeded`
   - ✅ `payment_intent.payment_failed`

4. **Get Webhook Secret**
   - Copy the webhook signing secret
   - Add to `.env.local` as `STRIPE_WEBHOOK_SECRET`

## Step 6: Deploy Application

If you're using Vercel or another hosting provider:

1. **Add Environment Variables**
   - Go to your project settings
   - Add all environment variables from Step 2
   - Redeploy the application

2. **Update Webhook URLs**
   - Update ShipStation webhook URL to production URL
   - Update Stripe webhook URL to production URL

## Step 7: Test End-to-End Flow

### Test Payment Processing

1. **Create a test product** in WooCommerce (if not already done)

2. **Process a test payment**:
   - Navigate to your checkout page
   - Use Stripe test card: `4242 4242 4242 4242`
   - Complete the checkout

3. **Verify in Stripe**:
   - Check Stripe dashboard for successful payment
   - Verify webhook was sent (check webhook logs)

4. **Verify in WooCommerce**:
   - Order status should be "processing"
   - Check order metadata for:
     - `_stripe_payment_intent_id`
     - `_shipstation_order_id` ✅ **NEW**
     - `_shipstation_synced_at` ✅ **NEW**

5. **Verify in ShipStation**:
   - Go to ShipStation dashboard
   - Check "Awaiting Shipment" orders
   - Your test order should appear with:
     - Order number matching WooCommerce order ID
     - Status: "Awaiting Shipment"
     - Correct billing/shipping addresses
     - Line items with product names and quantities

### Test Shipment Notification

1. **Mark order as shipped in ShipStation**:
   - Select the test order
   - Click "Create Label" or "Mark as Shipped"
   - Add tracking number (can be fake for testing)
   - Select carrier (e.g., "UPS", "USPS", "FedEx")
   - Click "Ship"

2. **Verify webhook received**:
   - Check application logs for:
     ```
     [shipstation] Webhook event received
     [shipstation] Order marked as shipped
     ```

3. **Verify in WooCommerce**:
   - Order status should be "shipped"
   - Check order metadata for:
     - `_tracking_number`
     - `_shipping_carrier`
     - `_shipped_date`
   - Customer note should include tracking information

## Step 8: Monitor for Issues

### Check Application Logs

Look for these log messages:

**Successful sync**:
```
[shipstation] Creating order in ShipStation
[shipstation] Successfully created order in ShipStation
[v0] Order payment completed (shipstationSynced: true)
```

**Failed sync**:
```
[shipstation] Failed to create order in ShipStation
[v0] Order marked for manual ShipStation sync
```

### Identify Failed Syncs

Orders that failed to sync will have:
- ✅ Status: "processing" (payment succeeded)
- ❌ Missing `_shipstation_order_id` metadata
- ❌ Present `_shipstation_sync_error` metadata

**To find failed orders** (using WooCommerce REST API):
```bash
curl "https://your-site.com/wp-json/wc/v3/orders?status=processing&meta_key=_shipstation_sync_error" \
  -u consumer_key:consumer_secret
```

## Troubleshooting

### Issue: Orders not appearing in ShipStation

**Possible causes**:
1. API credentials incorrect
2. ShipStation API down/slow
3. Network connectivity issues
4. Invalid address data

**Debug steps**:
1. Check application logs for error details
2. Verify API credentials with test script
3. Check order metadata for `_shipstation_sync_error`
4. Manually verify address data is valid

### Issue: Shipment webhooks not received

**Possible causes**:
1. Webhook URL incorrect
2. Webhook not enabled for correct events
3. Firewall blocking ShipStation IPs
4. Application not running/deployed

**Debug steps**:
1. Verify webhook URL in ShipStation settings
2. Test webhook manually from ShipStation dashboard
3. Check application logs for webhook receipt
4. Verify application is running and accessible

### Issue: Order status not updating to "shipped"

**Possible causes**:
1. "shipped" status doesn't exist in WooCommerce
2. Order not in "processing" status
3. Webhook payload invalid
4. WooCommerce API error

**Debug steps**:
1. Create custom "shipped" status in WooCommerce
2. Or, modify code to use "completed" instead
3. Check webhook payload in logs
4. Verify WooCommerce API credentials

## Custom Order Status Setup (Optional)

WooCommerce doesn't have a "shipped" status by default. You have two options:

### Option 1: Install Plugin (Recommended)

Install "WooCommerce Order Status Manager" or similar plugin:
1. Go to WordPress admin → Plugins → Add New
2. Search for "Order Status Manager"
3. Install and activate
4. Create custom "shipped" status with:
   - Slug: `shipped`
   - Label: `Shipped`
   - Icon: 📦 (optional)

### Option 2: Use "Completed" Status

Modify `app/api/shipstation/webhook/route.ts`:

```typescript
// Change this:
status: "shipped",

// To this:
status: "completed",
```

Also update `lib/woo.ts`:

```typescript
static isShipped(order: WooOrder): boolean {
  return order.status === "completed"
}
```

## Production Checklist

Before going live, ensure:

- [ ] Environment variables set in production
- [ ] ShipStation API credentials verified
- [ ] Stripe webhook configured with production URL
- [ ] ShipStation webhook configured with production URL
- [ ] Test payment processed successfully
- [ ] Test order appears in ShipStation
- [ ] Test shipment notification received
- [ ] Monitoring/alerting configured
- [ ] Custom "shipped" status created (if desired)
- [ ] Error handling tested (invalid credentials, network failures)

## Next Steps

1. **Monitor for 24-48 hours** after deployment
2. **Check for failed syncs** regularly
3. **Set up alerting** for ShipStation sync failures
4. **Consider building** admin retry tool for failed syncs
5. **Document** any custom modifications

## Support Resources

- **ShipStation API Docs**: https://www.shipstation.com/docs/api/
- **ShipStation Support**: https://help.shipstation.com/
- **Integration Guide**: See `SHIPSTATION_INTEGRATION.md`
- **Test Script**: `scripts/test-shipstation.ts`

## Security Notes

- ✅ API credentials stored in environment variables only
- ✅ Never exposed to client/browser
- ✅ All API calls from server-side only
- ✅ Rate limiting applied to webhooks
- ✅ Webhook payload validation with Zod schemas
- ✅ Graceful error handling (payment succeeds even if ShipStation fails)

## Questions?

If you encounter issues:
1. Check application logs first
2. Review `SHIPSTATION_INTEGRATION.md` for detailed documentation
3. Run `npx tsx scripts/test-shipstation.ts` to verify credentials
4. Check ShipStation API status page
5. Contact ShipStation support for API-specific issues




