> ## Documentation Index
> Fetch the complete documentation index at: https://developers.appstle.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Retry billing for failed attempt

> Immediately triggers a billing attempt for a subscription contract, bypassing the normal scheduled billing time. This endpoint processes the billing asynchronously via Shopify's Subscription Billing API, creating an order and charging the customer's payment method.

**How Billing Retry Works:**
1. **Validation**: Checks if shop has `enableImmediatePlaceOrder` permission (premium feature)
2. **Async Trigger**: Queues billing job in background (returns immediately)
3. **Shopify API Call**: Sends `subscriptionBillingAttemptCreate` mutation to Shopify
4. **Payment Processing**: Charges customer's stored payment method
5. **Order Creation**: Creates Shopify order if payment succeeds
6. **Notification**: Sends order confirmation email to customer (if enabled)
7. **Webhook Events**: Triggers `SUBSCRIPTION_BILLING_ATTEMPTS_SUCCESS` or `_FAILURE` webhook

**When to Use This Endpoint:**
- **Payment Failed Previously**: Customer updated credit card, retry failed billing
- **Scheduled Too Far Out**: Customer wants early delivery, bill before scheduled date
- **Payment Method Updated**: Customer just added new payment method, retry immediately
- **Manual Recovery**: Merchant intervention to recover failed subscription
- **Testing/QA**: Validate subscription billing flow in test environments
- **Customer Request**: Expedited order fulfillment for urgent needs

**Important Limitations & Restrictions:**
- **Permission Required**: Only available to shops with `enableImmediatePlaceOrder` permission
  - This is a premium feature - free plans will receive 400 error
  - Upgrade subscription plan in Appstle admin to enable
- **Rate Limiting**: Maximum 5 billing attempts per contract per hour (anti-abuse)
- **Billing Attempt Status**: Can retry attempts with status `QUEUED`, `SCHEDULED`, or `FAILED`
- **Cannot Retry**: Billing attempts with status `SUCCESS` (order already created)
- **Duplicate Prevention**: Shopify prevents duplicate orders within 24-hour window
- **Payment Method Required**: Contract must have valid payment method attached

**Asynchronous Processing Details:**
This endpoint returns **immediately** (200 OK) before billing completes. Actual billing happens in background:
- **Success Response**: Means billing job was queued, NOT that payment succeeded
- **Actual Result**: Check via webhooks or poll `/subscription-billing-attempts` endpoint
- **Processing Time**: Typically 5-30 seconds depending on Shopify API response time
- **Timeout Handling**: Background job retries up to 3 times if Shopify API times out

**Checking Billing Result (Recommended Flow):**
```
Step 1: Call this endpoint to trigger billing
  PUT /subscription-billing-attempts/attempt-billing/123456
  Response: 200 OK (billing queued)

Step 2: Wait 10-15 seconds for processing

Step 3: Poll billing attempt status
  GET /subscription-billing-attempts?id=123456
  Check 'status' field:
  - SUCCESS: Order created, payment captured
  - FAILED: Payment declined or error occurred
  - PROCESSING: Still in progress, poll again

Step 4: (Alternative) Use webhooks for real-time updates
  Configure webhook: SUBSCRIPTION_BILLING_ATTEMPTS_SUCCESS
  Receive notification when billing completes
```

**Common Error Scenarios:**
- **400 - Permission Denied**: "You don't have permission to place immediate orders"
  - **Solution**: Upgrade to premium plan with `enableImmediatePlaceOrder` feature
- **400 - Rate Limit**: "Too many billing attempts. Maximum 5 per hour per contract."
  - **Solution**: Wait before retrying, investigate why billing keeps failing
- **400 - Invalid Status**: "Cannot retry billing attempt with status SUCCESS"
  - **Solution**: Order already created successfully, check order history
- **404 - Not Found**: "Billing attempt not found"
  - **Solution**: Verify billing attempt ID belongs to this shop
- **500 - Shopify API Error**: Background job may fail if Shopify API is down
  - **Solution**: Retry after 5 minutes, check Shopify status page

**Payment Failure Reasons (Check After Async Processing):**
After billing processes, if status becomes `FAILED`, common reasons include:
- **Card Declined**: Insufficient funds, expired card, fraud detection
- **Invalid Payment Method**: Customer deleted payment method
- **3D Secure Failed**: Authentication challenge not completed
- **Gateway Error**: Payment processor (Stripe/Shopify Payments) issue
- **Inventory Shortage**: Product out of stock, cannot fulfill order
- **Subscription Canceled**: Contract canceled between retry trigger and processing

**Integration Best Practices:**
1. **Always Check Permission First**: Call `/shop-info` or similar to verify feature access
2. **Implement Webhooks**: Don't rely on polling - use webhooks for real-time status
3. **User Communication**: Warn user "Billing in progress..." since it's async
4. **Idempotency**: Safe to call multiple times - Shopify prevents duplicate orders
5. **Error Handling**: Gracefully handle permission errors for free plan users
6. **Logging**: Track billing attempt ID for troubleshooting and support

**Example Use Case - Customer Portal:**
```
Scenario: Customer's card declined, they updated payment method

1. Customer sees "Payment Failed" in portal
2. Customer clicks "Update Payment Method" → adds new card
3. Customer clicks "Retry Payment Now" button
4. Frontend calls: PUT /subscription-billing-attempts/attempt-billing/789
5. Display: "Processing payment..." spinner
6. Poll endpoint every 5 seconds for status update
7. On SUCCESS: Show "Payment successful! Order #12345 created."
8. On FAILED: Show decline reason + retry instructions
```

**Difference from Skip/Reschedule:**
- **Attempt Billing**: Immediately charges customer and creates order NOW
- **Skip**: Postpones order to next billing cycle, no charge
- **Reschedule**: Changes billing date without triggering immediate charge

**Authentication:** Requires API key authentication via X-API-Key header or api_key parameter. Additionally requires merchant account to have `enableImmediatePlaceOrder` permission (premium feature).



## OpenAPI

````yaml /memberships/admin-api-swagger.json put /api/external/v2/subscription-billing-attempts/attempt-billing/{id}
openapi: 3.0.1
info:
  description: >-
    Comprehensive API documentation for managing memberships, payments, and
    related operations. These APIs allow you to programmatically manage
    membership lifecycles, handle payments, configure products, and integrate
    membership functionality into your applications.
  title: Admin APIs
  version: 0.0.1
servers:
  - url: https://membership-admin.appstle.com
security: []
tags:
  - description: >-
      APIs for managing Shopify delivery profiles, shipping rates, zones, and
      free shipping configuration for subscription memberships
    name: Shipping & Delivery Profiles
  - description: >-
      APIs for retrieving historical discount code usage and redemption
      information for membership contracts
    name: Customer Discount History
  - description: >-
      APIs for managing membership cancellation flow settings including
      retention offers, survey questions, and cancel confirmation screens
    name: Cancellation Flow Configuration
  - description: >-
      APIs for managing membership billing attempts, recurring orders, payment
      retries, order history, and order skipping
    name: Billing & Orders
  - description: >-
      APIs for managing one-time product additions to upcoming subscription
      orders, including adding, retrieving, and removing one-off items
    name: One-Time Add-Ons
  - description: >-
      APIs for managing membership/subscription plan groups, including creating
      plans, configuring discounts, billing intervals, and assigning products to
      plans
    name: Membership Plans
  - description: >-
      APIs for managing subscription product bundles, bundle configurations,
      item grouping, and bundle-specific discount codes
    name: Product Bundles
  - description: >-
      APIs for retrieving custom CSS styles applied to subscription widgets and
      customer portal for theme customization
    name: Custom CSS Styling
  - description: >-
      APIs for managing customer portal settings including UI customization,
      text labels, feature toggles, and branding options for the member
      self-service portal
    name: Customer Portal Configuration
  - description: >-
      APIs for managing membership/subscription contracts including creation,
      updates, status changes, line items, discounts, and billing operations
    name: Membership Contracts
  - description: >-
      APIs for managing subscription bundle configuration settings including
      bundle behavior, pricing rules, and display options
    name: Bundle Settings
  - description: >-
      APIs for managing customer payment methods, payment tokens, and payment
      method retrieval for subscriptions
    name: Customer Payment Methods
  - description: >-
      APIs for retrieving product swap/substitution options allowing members to
      exchange subscription items based on configured swap rules and variant
      groups
    name: Product Swap Rules
  - description: >-
      APIs for retrieving product catalog, variants, pricing, and inventory
      information for subscription memberships.
    name: Product & Inventory Data
  - description: >-
      APIs for managing shop-level membership settings, configuration, and
      general store information.
    name: Shop Settings
  - description: >-
      APIs for performing bulk/mass operations on multiple membership contracts
      including status updates, product replacements, and billing date changes.
    name: Bulk Operations
paths:
  /api/external/v2/subscription-billing-attempts/attempt-billing/{id}:
    put:
      tags:
        - Billing & Orders
      summary: Retry billing for failed attempt
      description: >-
        Immediately triggers a billing attempt for a subscription contract,
        bypassing the normal scheduled billing time. This endpoint processes the
        billing asynchronously via Shopify's Subscription Billing API, creating
        an order and charging the customer's payment method.


        **How Billing Retry Works:**

        1. **Validation**: Checks if shop has `enableImmediatePlaceOrder`
        permission (premium feature)

        2. **Async Trigger**: Queues billing job in background (returns
        immediately)

        3. **Shopify API Call**: Sends `subscriptionBillingAttemptCreate`
        mutation to Shopify

        4. **Payment Processing**: Charges customer's stored payment method

        5. **Order Creation**: Creates Shopify order if payment succeeds

        6. **Notification**: Sends order confirmation email to customer (if
        enabled)

        7. **Webhook Events**: Triggers `SUBSCRIPTION_BILLING_ATTEMPTS_SUCCESS`
        or `_FAILURE` webhook


        **When to Use This Endpoint:**

        - **Payment Failed Previously**: Customer updated credit card, retry
        failed billing

        - **Scheduled Too Far Out**: Customer wants early delivery, bill before
        scheduled date

        - **Payment Method Updated**: Customer just added new payment method,
        retry immediately

        - **Manual Recovery**: Merchant intervention to recover failed
        subscription

        - **Testing/QA**: Validate subscription billing flow in test
        environments

        - **Customer Request**: Expedited order fulfillment for urgent needs


        **Important Limitations & Restrictions:**

        - **Permission Required**: Only available to shops with
        `enableImmediatePlaceOrder` permission
          - This is a premium feature - free plans will receive 400 error
          - Upgrade subscription plan in Appstle admin to enable
        - **Rate Limiting**: Maximum 5 billing attempts per contract per hour
        (anti-abuse)

        - **Billing Attempt Status**: Can retry attempts with status `QUEUED`,
        `SCHEDULED`, or `FAILED`

        - **Cannot Retry**: Billing attempts with status `SUCCESS` (order
        already created)

        - **Duplicate Prevention**: Shopify prevents duplicate orders within
        24-hour window

        - **Payment Method Required**: Contract must have valid payment method
        attached


        **Asynchronous Processing Details:**

        This endpoint returns **immediately** (200 OK) before billing completes.
        Actual billing happens in background:

        - **Success Response**: Means billing job was queued, NOT that payment
        succeeded

        - **Actual Result**: Check via webhooks or poll
        `/subscription-billing-attempts` endpoint

        - **Processing Time**: Typically 5-30 seconds depending on Shopify API
        response time

        - **Timeout Handling**: Background job retries up to 3 times if Shopify
        API times out


        **Checking Billing Result (Recommended Flow):**

        ```

        Step 1: Call this endpoint to trigger billing
          PUT /subscription-billing-attempts/attempt-billing/123456
          Response: 200 OK (billing queued)

        Step 2: Wait 10-15 seconds for processing


        Step 3: Poll billing attempt status
          GET /subscription-billing-attempts?id=123456
          Check 'status' field:
          - SUCCESS: Order created, payment captured
          - FAILED: Payment declined or error occurred
          - PROCESSING: Still in progress, poll again

        Step 4: (Alternative) Use webhooks for real-time updates
          Configure webhook: SUBSCRIPTION_BILLING_ATTEMPTS_SUCCESS
          Receive notification when billing completes
        ```


        **Common Error Scenarios:**

        - **400 - Permission Denied**: "You don't have permission to place
        immediate orders"
          - **Solution**: Upgrade to premium plan with `enableImmediatePlaceOrder` feature
        - **400 - Rate Limit**: "Too many billing attempts. Maximum 5 per hour
        per contract."
          - **Solution**: Wait before retrying, investigate why billing keeps failing
        - **400 - Invalid Status**: "Cannot retry billing attempt with status
        SUCCESS"
          - **Solution**: Order already created successfully, check order history
        - **404 - Not Found**: "Billing attempt not found"
          - **Solution**: Verify billing attempt ID belongs to this shop
        - **500 - Shopify API Error**: Background job may fail if Shopify API is
        down
          - **Solution**: Retry after 5 minutes, check Shopify status page

        **Payment Failure Reasons (Check After Async Processing):**

        After billing processes, if status becomes `FAILED`, common reasons
        include:

        - **Card Declined**: Insufficient funds, expired card, fraud detection

        - **Invalid Payment Method**: Customer deleted payment method

        - **3D Secure Failed**: Authentication challenge not completed

        - **Gateway Error**: Payment processor (Stripe/Shopify Payments) issue

        - **Inventory Shortage**: Product out of stock, cannot fulfill order

        - **Subscription Canceled**: Contract canceled between retry trigger and
        processing


        **Integration Best Practices:**

        1. **Always Check Permission First**: Call `/shop-info` or similar to
        verify feature access

        2. **Implement Webhooks**: Don't rely on polling - use webhooks for
        real-time status

        3. **User Communication**: Warn user "Billing in progress..." since it's
        async

        4. **Idempotency**: Safe to call multiple times - Shopify prevents
        duplicate orders

        5. **Error Handling**: Gracefully handle permission errors for free plan
        users

        6. **Logging**: Track billing attempt ID for troubleshooting and support


        **Example Use Case - Customer Portal:**

        ```

        Scenario: Customer's card declined, they updated payment method


        1. Customer sees "Payment Failed" in portal

        2. Customer clicks "Update Payment Method" → adds new card

        3. Customer clicks "Retry Payment Now" button

        4. Frontend calls: PUT
        /subscription-billing-attempts/attempt-billing/789

        5. Display: "Processing payment..." spinner

        6. Poll endpoint every 5 seconds for status update

        7. On SUCCESS: Show "Payment successful! Order #12345 created."

        8. On FAILED: Show decline reason + retry instructions

        ```


        **Difference from Skip/Reschedule:**

        - **Attempt Billing**: Immediately charges customer and creates order
        NOW

        - **Skip**: Postpones order to next billing cycle, no charge

        - **Reschedule**: Changes billing date without triggering immediate
        charge


        **Authentication:** Requires API key authentication via X-API-Key header
        or api_key parameter. Additionally requires merchant account to have
        `enableImmediatePlaceOrder` permission (premium feature).
      operationId: attemptBillingV2
      parameters:
        - description: Billing attempt ID to retry
          example: 123456
          in: path
          name: id
          required: true
          schema:
            format: int64
            type: integer
        - description: API Key (Deprecated - Use Header X-API-Key instead)
          in: query
          name: api_key
          required: false
          schema:
            type: string
        - in: header
          name: X-API-Key
          required: false
          schema:
            type: string
      responses:
        '200':
          description: >-
            Billing attempt successfully queued for asynchronous processing.
            This does NOT mean payment succeeded - billing happens in
            background. Poll the billing attempt status or use webhooks to check
            actual result.
        '400':
          description: >-
            Bad request - possible reasons:

            1. Missing `enableImmediatePlaceOrder` permission (upgrade plan
            required)

            2. Rate limit exceeded (max 5 attempts/hour per contract)

            3. Invalid billing attempt status (e.g., already SUCCESS)

            4. Contract canceled or payment method missing
        '401':
          description: Authentication required - invalid or missing API key
        '404':
          description: >-
            Billing attempt not found with provided ID or doesn't belong to
            authenticated shop
        '500':
          description: >-
            Internal server error - Shopify API unavailable or background job
            queue failure. Retry after 5 minutes.

````