> ## 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.

# Send magic link email to customer for portal access

> Sends an automated email to a customer containing a secure magic link for accessing their subscription management portal. The email is sent using the shop's configured email template and includes a time-limited authentication token.

**What This Endpoint Does:**
1. Validates customer exists and has subscriptions
2. Generates secure portal access token
3. Retrieves shop's email template configuration
4. Sends personalized email with magic link
5. Logs activity for audit trail

**Magic Link Functionality:**

**What is a Magic Link?**
A magic link is a special URL containing an encrypted authentication token that allows customers to access their portal without entering a password. Clicking the link automatically logs them in.

**Link Contents:**
- Shop's portal URL
- Encrypted customer token (2-hour expiration)
- Direct access to subscription management
- No password required

**Security:**
- Token expires in 2 hours
- Single customer authentication
- Cannot be used by others
- Logged for security audit

**Request Parameters:**

**email (required):**
- Customer's email address
- Must exactly match email in Shopify
- Customer must have at least one subscription
- Case-sensitive in some systems

**Email Template Configuration:**

**Template Requirements:**
- Email template must be configured in Appstle settings
- Template type: SUBSCRIPTION_MANAGEMENT_LINK
- Template must not be disabled
- Template includes shop branding and customization

**Email Content:**
- Personalized greeting with customer name
- Clickable magic link button/link
- Expiration notice (link valid 2 hours)
- Shop branding and footer
- Optional custom messaging

**Template Variables:**
- `{customer_name}`: Customer's display name
- `{magic_link}`: Portal URL with token
- `{shop_name}`: Store name
- `{expiration_time}`: Token expiry time

**Use Cases:**

**1. Customer Self-Service:**
- "Forgot password" alternative
- Quick portal access without account setup
- Passwordless authentication flow
- Reduce friction for customers

**2. Subscription Management Prompts:**
- "Manage your subscription" emails
- Pre-billing reminders with management link
- Post-purchase subscription setup
- Re-engagement campaigns

**3. Customer Support:**
- Send portal access to customers
- Enable self-service during support interactions
- Provide instant portal access
- Reduce support workload

**4. Automated Workflows:**
- Payment failure recovery emails
- Subscription expiration notices
- Pause/skip reminders
- Renewal notifications

**5. Marketing Campaigns:**
- Subscription feature announcements
- New product availability
- Loyalty program invitations
- Referral program links

**Process Flow:**

```
1. API receives email parameter
2. Searches subscription database for customer email
3. If not found → Returns 400 error
4. If found → Retrieves customer subscriptions
5. Sorts subscriptions by status (active first)
6. Checks email template configuration
7. If disabled → Returns 400 error with instructions
8. If enabled → Generates magic link token
9. Prepares email with template
10. Sends email via configured provider
11. Logs activity (source: MERCHANT_EXTERNAL_API)
12. Returns success message
```

**Response Format:**
```json
"Email triggered successfully."
```

**Simple string response** confirming email queued for delivery.

**Important Considerations:**

**Customer Validation:**
- Email MUST exist in subscription database
- Customer MUST have at least one subscription
- Customers without subscriptions cannot receive link
- Returns error if customer not found

**Email Template Disabled:**
- If template disabled in settings: Returns error
- Error message guides merchant to enable template
- Path: "More -> Notification Settings"
- Template must be explicitly enabled

**Email Delivery:**
- Email sent asynchronously
- Success response doesn't guarantee delivery
- Check email logs for delivery confirmation
- Respects shop's email provider settings

**Multiple Subscriptions:**
- If customer has multiple subscriptions: Sorts by status
- Active subscriptions shown first
- Link provides access to ALL customer subscriptions
- Portal displays all contracts

**Activity Logging:**
- All magic link emails logged
- Source: MERCHANT_EXTERNAL_API
- Includes timestamp and customer
- Viewable in activity logs

**Integration Examples:**

**Webhook Trigger - Payment Failed:**
```javascript
async function handlePaymentFailure(webhook) {
  const customerEmail = webhook.customer.email;
  
  // Send magic link to customer
  await fetch(
    `/api/external/v2/subscription-contracts-email-magic-link?email=${customerEmail}`,
    { headers: { 'X-API-Key': process.env.APPSTLE_API_KEY } }
  );
  
  console.log(`Magic link sent to ${customerEmail} for payment update`);
}
```

**Customer Support Button:**
```javascript
async function sendPortalAccess(customerEmail) {
  try {
    const response = await fetch(
      `/api/external/v2/subscription-contracts-email-magic-link?email=${encodeURIComponent(customerEmail)}`,
      { 
        headers: { 'X-API-Key': apiKey },
        method: 'GET'
      }
    );
    
    if (response.ok) {
      alert('Portal access email sent to customer!');
    }
  } catch (error) {
    console.error('Failed to send magic link:', error);
  }
}
```

**Best Practices:**

1. **Validate Email**: Check email format before calling API
2. **Rate Limiting**: Don't spam customers - limit frequency
3. **Error Handling**: Handle customer not found gracefully
4. **User Feedback**: Confirm email sent to user
5. **Test Template**: Ensure email template configured and working
6. **Monitor Logs**: Check activity logs for delivery issues

**Common Errors:**

**"Customer Email does not exist":**
- Email not found in subscription database
- Customer has no subscriptions
- Email may be misspelled

**"Email template not found":**
- SUBSCRIPTION_MANAGEMENT_LINK template not configured
- Contact Appstle support to set up template

**"Email is currently disabled":**
- Template disabled in Notification Settings
- Navigate to More -> Notification Settings
- Enable "Subscription Management Link" email

**Authentication:** Requires valid X-API-Key header



## OpenAPI

````yaml /subscription/admin-api-swagger.json get /api/external/v2/subscription-contracts-email-magic-link
openapi: 3.0.1
info:
  description: >-
    Comprehensive API documentation for managing subscriptions, payments, and
    related operations. These APIs allow you to programmatically manage
    subscription lifecycles, handle payments, configure products, and integrate
    subscription functionality into your applications.
  title: Admin APIs
  version: 0.0.1
servers:
  - url: https://subscription-admin.appstle.com
security: []
tags:
  - description: >-
      Core APIs for managing the complete subscription lifecycle including
      creation, updates, pausing, resuming, and cancellation of subscriptions.
    name: Subscription Management
  - description: >-
      APIs for managing subscription payment methods, processing payments,
      handling payment retries, and updating billing information.
    name: Subscription Payments
  - description: >-
      APIs for managing subscription contracts including delivery schedules,
      pricing, order notes, billing cycles, and shipping addresses.
    name: Subscription Contracts
  - description: >-
      APIs for managing products within subscriptions including adding,
      removing, updating quantities, and swapping products.
    name: Subscription Products
  - description: >-
      APIs for handling billing operations, payment processing, and financial
      transactions related to subscriptions.
    name: Billing & Payments
  - description: >-
      APIs for managing discounts and promotional codes applied to
      subscriptions.
    name: Subscription Discounts
  - description: >-
      APIs for managing one-time add-on products that can be purchased alongside
      recurring subscription items.
    name: Subscription One-Time Products
  - description: >-
      APIs for managing subscription plans, pricing tiers, and plan
      configurations.
    name: Subscription Plans
  - description: >-
      APIs for managing customizable product boxes and bundles where customers
      can select multiple items.
    name: Build-a-Box & Bundles
  - description: >-
      APIs for managing the product catalog including product information,
      variants, and inventory.
    name: Product Catalog
  - description: >-
      APIs for managing operational settings, configurations, and administrative
      functions.
    name: Operations & Settings
  - description: >-
      APIs powering the customer-facing portal where subscribers can manage
      their own subscriptions.
    name: Customer Portal
  - description: APIs for managing customer information, profiles, and account details.
    name: Customers
  - description: >-
      APIs for retrieving aggregated subscription data, customer subscription
      history, and account-level subscription information.
    name: Subscription Data
  - description: >-
      APIs for managing delivery profiles, shipping rates, free shipping
      configuration, and delivery method options on subscriptions.
    name: Delivery & Shipping
  - description: >-
      APIs for managing storefront customization including custom CSS, theme
      settings, label translations, and merchant-defined widget configuration.
    name: Customization
  - description: >-
      APIs for configuring cancellation flows, retention offers, cancellation
      reason management, and win-back automation.
    name: Customer Retention
paths:
  /api/external/v2/subscription-contracts-email-magic-link:
    get:
      tags:
        - Subscription Contracts
        - Customer Portal
      summary: Send magic link email to customer for portal access
      description: >-
        Sends an automated email to a customer containing a secure magic link
        for accessing their subscription management portal. The email is sent
        using the shop's configured email template and includes a time-limited
        authentication token.


        **What This Endpoint Does:**

        1. Validates customer exists and has subscriptions

        2. Generates secure portal access token

        3. Retrieves shop's email template configuration

        4. Sends personalized email with magic link

        5. Logs activity for audit trail


        **Magic Link Functionality:**


        **What is a Magic Link?**

        A magic link is a special URL containing an encrypted authentication
        token that allows customers to access their portal without entering a
        password. Clicking the link automatically logs them in.


        **Link Contents:**

        - Shop's portal URL

        - Encrypted customer token (2-hour expiration)

        - Direct access to subscription management

        - No password required


        **Security:**

        - Token expires in 2 hours

        - Single customer authentication

        - Cannot be used by others

        - Logged for security audit


        **Request Parameters:**


        **email (required):**

        - Customer's email address

        - Must exactly match email in Shopify

        - Customer must have at least one subscription

        - Case-sensitive in some systems


        **Email Template Configuration:**


        **Template Requirements:**

        - Email template must be configured in Appstle settings

        - Template type: SUBSCRIPTION_MANAGEMENT_LINK

        - Template must not be disabled

        - Template includes shop branding and customization


        **Email Content:**

        - Personalized greeting with customer name

        - Clickable magic link button/link

        - Expiration notice (link valid 2 hours)

        - Shop branding and footer

        - Optional custom messaging


        **Template Variables:**

        - `{customer_name}`: Customer's display name

        - `{magic_link}`: Portal URL with token

        - `{shop_name}`: Store name

        - `{expiration_time}`: Token expiry time


        **Use Cases:**


        **1. Customer Self-Service:**

        - "Forgot password" alternative

        - Quick portal access without account setup

        - Passwordless authentication flow

        - Reduce friction for customers


        **2. Subscription Management Prompts:**

        - "Manage your subscription" emails

        - Pre-billing reminders with management link

        - Post-purchase subscription setup

        - Re-engagement campaigns


        **3. Customer Support:**

        - Send portal access to customers

        - Enable self-service during support interactions

        - Provide instant portal access

        - Reduce support workload


        **4. Automated Workflows:**

        - Payment failure recovery emails

        - Subscription expiration notices

        - Pause/skip reminders

        - Renewal notifications


        **5. Marketing Campaigns:**

        - Subscription feature announcements

        - New product availability

        - Loyalty program invitations

        - Referral program links


        **Process Flow:**


        ```

        1. API receives email parameter

        2. Searches subscription database for customer email

        3. If not found → Returns 400 error

        4. If found → Retrieves customer subscriptions

        5. Sorts subscriptions by status (active first)

        6. Checks email template configuration

        7. If disabled → Returns 400 error with instructions

        8. If enabled → Generates magic link token

        9. Prepares email with template

        10. Sends email via configured provider

        11. Logs activity (source: MERCHANT_EXTERNAL_API)

        12. Returns success message

        ```


        **Response Format:**

        ```json

        "Email triggered successfully."

        ```


        **Simple string response** confirming email queued for delivery.


        **Important Considerations:**


        **Customer Validation:**

        - Email MUST exist in subscription database

        - Customer MUST have at least one subscription

        - Customers without subscriptions cannot receive link

        - Returns error if customer not found


        **Email Template Disabled:**

        - If template disabled in settings: Returns error

        - Error message guides merchant to enable template

        - Path: "More -> Notification Settings"

        - Template must be explicitly enabled


        **Email Delivery:**

        - Email sent asynchronously

        - Success response doesn't guarantee delivery

        - Check email logs for delivery confirmation

        - Respects shop's email provider settings


        **Multiple Subscriptions:**

        - If customer has multiple subscriptions: Sorts by status

        - Active subscriptions shown first

        - Link provides access to ALL customer subscriptions

        - Portal displays all contracts


        **Activity Logging:**

        - All magic link emails logged

        - Source: MERCHANT_EXTERNAL_API

        - Includes timestamp and customer

        - Viewable in activity logs


        **Integration Examples:**


        **Webhook Trigger - Payment Failed:**

        ```javascript

        async function handlePaymentFailure(webhook) {
          const customerEmail = webhook.customer.email;
          
          // Send magic link to customer
          await fetch(
            `/api/external/v2/subscription-contracts-email-magic-link?email=${customerEmail}`,
            { headers: { 'X-API-Key': process.env.APPSTLE_API_KEY } }
          );
          
          console.log(`Magic link sent to ${customerEmail} for payment update`);
        }

        ```


        **Customer Support Button:**

        ```javascript

        async function sendPortalAccess(customerEmail) {
          try {
            const response = await fetch(
              `/api/external/v2/subscription-contracts-email-magic-link?email=${encodeURIComponent(customerEmail)}`,
              { 
                headers: { 'X-API-Key': apiKey },
                method: 'GET'
              }
            );
            
            if (response.ok) {
              alert('Portal access email sent to customer!');
            }
          } catch (error) {
            console.error('Failed to send magic link:', error);
          }
        }

        ```


        **Best Practices:**


        1. **Validate Email**: Check email format before calling API

        2. **Rate Limiting**: Don't spam customers - limit frequency

        3. **Error Handling**: Handle customer not found gracefully

        4. **User Feedback**: Confirm email sent to user

        5. **Test Template**: Ensure email template configured and working

        6. **Monitor Logs**: Check activity logs for delivery issues


        **Common Errors:**


        **"Customer Email does not exist":**

        - Email not found in subscription database

        - Customer has no subscriptions

        - Email may be misspelled


        **"Email template not found":**

        - SUBSCRIPTION_MANAGEMENT_LINK template not configured

        - Contact Appstle support to set up template


        **"Email is currently disabled":**

        - Template disabled in Notification Settings

        - Navigate to More -> Notification Settings

        - Enable "Subscription Management Link" email


        **Authentication:** Requires valid X-API-Key header
      operationId: emailMagicLinkV2
      parameters:
        - 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
        - description: Customer email
          in: query
          name: email
          required: true
          schema:
            type: string
      responses:
        '200':
          content:
            application/json:
              example: Email triggered successfully.
              schema:
                type: string
          description: Email successfully queued for delivery
        '400':
          content:
            application/json:
              examples:
                Customer Not Found:
                  description: Customer Not Found
                  value:
                    detail: UserGeneratedError:Customer Email does not exist
                    status: 400
                    title: Customer not found
                    type: https://example.com/errors/bad-request
                Email Template Disabled:
                  description: Email Template Disabled
                  value:
                    detail: >-
                      UserGeneratedError:The Subscription Management Link email
                      is currently disabled in Notification Settings. To enable
                      it, go to More -> Notification Settings.
                    status: 400
                    title: Email disabled
                    type: https://example.com/errors/bad-request
                Email Template Not Found:
                  description: Email Template Not Found
                  value:
                    detail: UserGeneratedError:Email template not found
                    status: 400
                    title: Email template not configured
                    type: https://example.com/errors/bad-request
          description: Bad request - Customer not found or email template disabled
        '401':
          content:
            application/json:
              example:
                detail: Valid X-API-Key header is required
                status: 401
                title: Authentication required
                type: https://example.com/errors/unauthorized
          description: Authentication required
        '500':
          content:
            application/json:
              example:
                detail: Failed to send magic link email
                status: 500
                title: Email send failed
                type: https://example.com/errors/internal-error
          description: Internal server error - Email send failure

````