# Membership Contracts APIs for managing membership/subscription contracts including creation, updates, status changes, line items, discounts, and billing operations ## Update subscription contract status (pause/resume/activate) - [PUT /api/external/v2/subscription-contracts-update-status](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatestatusv2.md): Changes the status of a subscription contract. This allows pausing, resuming, or activating subscriptions to control billing and delivery. Key Features: - Pause Subscriptions: Temporarily stop billing and deliveries - Resume Subscriptions: Reactivate paused subscriptions - Activate Subscriptions: Start inactive subscriptions - Activity Logging: All status changes are logged for audit trail - Customer Restrictions: Includes minimum cycle checks when called from customer portal Status Values: - ACTIVE: Subscription is active and billing/delivering normally - PAUSED: Subscription is temporarily paused (no billing, no deliveries) - CANCELLED: Subscription is cancelled (use DELETE endpoint instead) Pause vs. Cancel: - Pause: Temporary hold, customer can resume anytime - Cancel: Permanent termination, requires creating new subscription to restart Common Use Cases: - Vacation Hold: Customer going on vacation, pause deliveries temporarily - Financial Pause: Customer needs temporary break from payments - Product Surplus: Customer has too much product, pause until they use it - Seasonal Pause: Pause subscriptions during off-season (e.g., lawn care in winter) - Resume After Pause: Customer ready to restart after temporary hold - Reactivate Failed: Reactivate subscription after payment method updated Pause Behavior: - Billing Paused: No charges while paused - Deliveries Paused: No orders created while paused - Next Billing Date: Preserved or recalculated on resume (merchant setting) - Unlimited Duration: Pauses can be indefinite unless merchant sets limits Resume Behavior: - Immediate Reactivation: Subscription becomes active immediately - Next Billing Date: Calculated based on pause duration settings - Deliveries Resume: Next delivery scheduled according to interval Customer Portal Restrictions: When called from customer portal (vs. merchant API): - Minimum Cycles: Cannot pause/cancel until minimum billing cycles met - Freeze Period: Updates may be frozen until minimum requirements satisfied - Retention Rules: Special retention discounts may be offered on cancellation Important Notes: - Customer Communication: Consider sending email notifications on status changes - Billing Cycles Not Lost: Paused cycles don't count toward minimums - No Pro-rata: No refunds or credits when pausing mid-cycle Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update shipping address for subscription contract - [PUT /api/external/v2/subscription-contracts-update-shipping-address](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updateshippingaddressv2.md): Changes the delivery shipping address for a subscription contract. This allows customers to update where their subscription orders are delivered. Key Features: - Full Address Update: Change complete shipping address in one call - Address Validation: System validates address format and country codes - Immediate Effect: New address applies to the next delivery - Activity Logging: All address changes are logged for audit trail - International Support: Supports addresses in all countries Required Address Fields: - firstName: Recipient's first name - lastName: Recipient's last name - address1: Street address line 1 - city: City name - countryCode: ISO 3166-1 alpha-2 country code (e.g., US, CA, GB) - zip: Postal/ZIP code Optional Address Fields: - address2: Apartment, suite, unit number - company: Company name (for business addresses) - phone: Contact phone number - provinceCode: State/province code (e.g., CA, NY, ON) Common Use Cases: - Customer Moved: Update address after relocation - Temporary Address: Ship to vacation home or temporary location - Gift Recipient: Change recipient for gift subscriptions - Correct Typos: Fix address errors from initial signup - Business to Home: Switch between business and residential addresses - Seasonal Address: Update for snowbird/seasonal residents Country and Province Codes: - countryCode: Use ISO 3166-1 alpha-2 codes - Examples: US (United States), CA (Canada), GB (United Kingdom), AU (Australia) - provinceCode: Use ISO 3166-2 subdivision codes - US Examples: CA (California), NY (New York), TX (Texas) - Canada Examples: ON (Ontario), BC (British Columbia), QC (Quebec) Address Validation: - Format Validation: System checks required fields are present - Country Validation: Verifies country code is valid - Province Validation: Checks province code matches country - Postal Code: Validates postal code format for country Important Notes: - Shipping Rate Recalculation: New address may have different shipping costs - Delivery Method: System automatically selects appropriate delivery method - Next Order Only: Only affects future orders, not orders already placed - Address Book: Consider updating customer's default address separately - PO Boxes: Some delivery methods may not support PO Box addresses Shipping Cost Impact: - Changing address may change shipping costs for future deliveries - International addresses typically have higher shipping costs - Remote/rural areas may have additional delivery fees - Consider notifying customer of cost changes Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update subscription payment method - [PUT /api/external/v2/subscription-contracts-update-payment-method](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatepaymentmethodv2.md): Updates the payment method for a subscription contract by refreshing payment instrument from Shopify customer. This endpoint syncs the subscription's payment method with the customer's default payment method in Shopify. Payment Method Update Process: - Fetch Latest Payment: Retrieves customer's current default payment method from Shopify - Update Contract: Associates new payment method with subscription contract - Validate Payment: Ensures payment method is valid and active - Sync Changes: Updates payment instrument in subscription billing system Key Features: - Automatic Sync: Pulls latest payment method from Shopify customer record - Payment Validation: Verifies new payment method is usable for billing - Contract Update: Updates Shopify subscription contract with new payment - Failed Billing Recovery: Useful for updating payment after billing failures Use Cases: - Customer updates credit card and wants to apply to existing subscription - Recover from failed billing by allowing payment method update - Sync payment methods in customer portal workflows - Update expired or invalid payment methods - Switch between multiple saved payment methods - Integration with custom payment update flows Important Notes: - Customer must have a default payment method in Shopify - Payment method must be valid and not expired - Updates are reflected immediately for future billing - Does not retry failed billing attempts automatically Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update order note/instructions for subscription contract - [PUT /api/external/v2/subscription-contracts-update-order-note/{contractId}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updateordernotev2.md): Updates the persistent order note attached to a subscription contract. This note is automatically included with EVERY future recurring order generated from this subscription, appearing in Shopify admin order details and printable packing slips. IMPORTANT: Recurring vs One-Time Notes - This Endpoint (Contract Note): Applies to ALL FUTURE ORDERS permanently - Billing Attempt Note (/subscription-billing-attempts-update-order-note): Applies to ONE SPECIFIC ORDER only - Combined Behavior: If both notes exist, they are concatenated in the Shopify order How It Works: 1. Accepts subscription contract ID and new order note text 2. Stores note in subscription contract record 3. Every time a new order is created (monthly, weekly, etc.), note is automatically added 4. Previous contract note is replaced (not appended) 5. Empty string clears the existing note 6. Does NOT affect past orders already created Character Limits & Validation: - Maximum Length: 5000 characters (Shopify order note limit) - Encoding: UTF-8 supported (emojis, international characters allowed) - HTML: Plain text only - HTML tags display as text - Line Breaks: Use \n for line breaks (preserved in Shopify) - Special Characters: Automatically escaped for safety Common Use Cases: 1. Permanent Delivery Instructions Example: "Always leave package at back door. Do not ring doorbell (baby sleeping)." Use Case: Customer wants same delivery instructions for all future orders Applies To: Every monthly shipment permanently 2. Gift Subscription Messages Example: "This is a gift subscription for Mom. Happy Birthday! Love, Sarah" Use Case: Gift subscription with recurring message Applies To: All orders until subscription ends or note is changed 3. Special Handling Requirements Example: "FRAGILE - Glass bottles. Handle with care. Keep upright during shipping." Use Case: Delicate products requiring special warehouse handling Applies To: Every fulfillment automatically 4. Customer Preferences Example: "Customer is allergic to peanuts. NO peanut products. Double-check packaging." Use Case: Critical dietary restrictions or preferences Applies To: All future orders for safety compliance 5. Internal Merchant Notes Example: "VIP customer - priority processing. Include bonus samples." Use Case: Internal fulfillment team instructions Applies To: All shipments to provide consistent VIP treatment 6. Clearing Unwanted Notes Example: orderNote="" (empty string) Use Case: Customer moved, no longer needs "Leave at neighbor" note Result: Future orders have no contract note (one-time notes still possible) Where Note Appears: - Shopify Admin: Order details page under "Notes" - Packing Slips: Printed on warehouse packing slips (if enabled) - Order Confirmation Emails: May appear in customer emails (theme-dependent) - Fulfillment Apps: Visible to third-party logistics providers - Order APIs: Accessible via Shopify Order REST/GraphQL APIs When to Use Contract Note vs Billing Attempt Note: | Scenario | Use Contract Note | Use Billing Attempt Note | |----------|-------------------|-------------------------| | Permanent delivery instructions | ✅ | ❌ | | One-time special request | ❌ | ✅ | | Gift message for all shipments | ✅ | ❌ | | "Skip broccoli this week" | ❌ | ✅ | | Allergy warnings | ✅ | ❌ | | "Deliver to neighbor (vacation week)" | ❌ | ✅ | | VIP customer priority | ✅ | ❌ | Error Handling: 400 - Bad Request: - Order note exceeds 5000 character limit - Contract ID doesn't belong to authenticated shop - Contract is in invalid state 404 - Contract Not Found: - Subscription contract ID doesn't exist - Contract was deleted - Wrong shop (contract belongs to different store) Integration Best Practices: 1. Display Character Counter: Show "450 / 5000 characters" in UI 2. Preview Formatting: Show how line breaks will appear 3. Confirm Permanent Changes: Warn user "This note will appear on ALL future orders" 4. Sanitize Input: Strip HTML tags, prevent injection attacks 5. Show Current Note: Pre-fill form with existing note before update Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update minimum billing cycles for subscription contract - [PUT /api/external/v2/subscription-contracts-update-min-cycles](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatemincyclesv2.md): Sets the minimum number of billing cycles (payments) required before a customer can cancel their subscription. This is commonly used to enforce commitment periods or prevent early cancellations. Key Features: - Commitment Enforcement: Require customers to stay subscribed for a minimum period - Cancellation Prevention: Blocks cancellation until minimum cycles are met - Contract Terms: Implements contractual minimum billing requirements - Flexible Duration: Set any number from 0 (no minimum) to higher values Common Use Cases: - 3-Month Minimum: Set minCycles=3 for quarterly commitment - Annual Contract: Set minCycles=12 for yearly subscriptions - Trial Completion: Require 1-2 cycles before allowing cancellation - Remove Restriction: Set minCycles=0 or null to remove minimum Behavior: - Customer portal will show "X cycles remaining until cancellation allowed" - Cancellation button disabled until minimum met - Does not affect pausing subscriptions - Applies to future billing cycles, not retroactive Parameters: - contractId (required): The subscription contract ID - minCycles (optional): Number of minimum cycles (null or 0 = no minimum) Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update maximum billing cycles for subscription contract - [PUT /api/external/v2/subscription-contracts-update-max-cycles](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatemaxcyclesv2.md): Sets the maximum number of billing cycles (payments) after which the subscription will automatically expire and cancel. This is useful for creating fixed-term memberships or limited-duration subscriptions. Key Features: - Auto-Expiration: Subscription automatically cancels after max cycles reached - Fixed-Term Plans: Create memberships with defined end dates - No Manual Intervention: System handles cancellation automatically - Flexible Duration: Set any number or null for unlimited Common Use Cases: - 6-Month Program: Set maxCycles=6 for half-year membership - Annual Subscription: Set maxCycles=12 for one-year auto-expiring plan - Trial Extensions: Set maxCycles=3 for limited trial periods - Unlimited Subscription: Set maxCycles=null or 0 for no maximum Behavior: - Subscription cancels automatically after final billing cycle - Customer receives notification before expiration - No refunds issued on auto-cancellation - Contract status changes to EXPIRED after last cycle Parameters: - contractId (required): The subscription contract ID - maxCycles (optional): Maximum number of billing cycles (null or 0 = unlimited) Note: Setting maxCycles lower than current cycle count will cause immediate expiration. Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update subscription line item quantity and pricing - [PUT /api/external/v2/subscription-contracts-update-line-item](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatelineitemv2.md): Updates an existing line item in a subscription contract, modifying quantity, variant, or price. This endpoint allows comprehensive updates to subscription products. Line Item Update Process: - Line Item Identification: Locates line item using GraphQL line ID - Quantity Update: Changes product quantity for recurring orders - Variant Change: Can switch to different variant of same product - Price Override: Optional custom pricing override - Contract Sync: Updates Shopify subscription contract - Activity Logging: Records line item modification event Update Capabilities: - Quantity Adjustment: Increase or decrease product quantity - Variant Switching: Change product variant (size, color, flavor, etc.) - Custom Pricing: Override standard pricing per line item - Combined Updates: Change multiple properties in single request Parameters: - lineId: GraphQL ID of line item to update - quantity: New quantity (must be positive integer) - variantId: Product variant ID (can change to different variant) - price: Custom price override (optional, overrides default pricing) Price Override: - Allows custom per-line pricing - Useful for special pricing arrangements - Overrides default product pricing - Price in shop's base currency Use Cases: - Customer increases/decreases product quantity - Switch product variant (e.g., Medium → Large roast) - Special pricing for VIP customers - Seasonal variant changes (Summer → Winter flavor) - Customer portal quantity adjustments - Wholesale pricing overrides - Build-a-box quantity modifications Important Notes: - Quantity must be positive (use remove-line-item to delete) - Variant must be valid and available - Price updates don't affect existing discount percentages - Changes apply to next billing cycle Returns: Updated subscription contract object with modified line item Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update custom attributes on subscription line item - [PUT /api/external/v2/subscription-contracts-update-line-item-attributes](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatelineitemattributesv2.md): Updates custom attributes (metadata) on a specific subscription line item. Attributes allow storing custom key-value data on individual products in a subscription. Attribute Update Process: - Line Item Identification: Locates specific line item using GraphQL line ID - Attribute Replacement: Replaces existing attributes with new list - Contract Update: Syncs changes to Shopify subscription contract - Activity Logging: Records attribute modification event - Freeze Validation: Ensures subscription isn't frozen before updates Custom Attributes: - Key-Value Pairs: Store arbitrary metadata on line items - Flexible Data: Supports text, numbers, JSON as values - Per-Item Storage: Each line item has independent attributes - Order Propagation: Attributes carry forward to generated orders Attribute Structure: json [ {"key": "gift_message", "value": "Happy Birthday!"}, {"key": "custom_option", "value": "medium_roast"}, {"key": "special_instructions", "value": "Leave at door"} ] Line ID Format: - GraphQL ID format: gid://shopify/SubscriptionLine/[ID] - Retrieve from subscription contract details endpoint - Each line item has unique ID Use Cases: - Store gift message customizations per product - Track product-specific preferences (roast level, flavor, size) - Custom delivery instructions for specific items - Personalization options (monogram, engraving text) - Build-a-box selection metadata - Product customization workflows - Integration data synchronization Important Notes: - Attributes are replaced, not merged (send all desired attributes) - Maximum 250 characters per value - Subscription must not be frozen - Attributes visible in Shopify admin and order details Returns: Updated subscription contract object with modified attributes Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update delivery interval for subscription contract - [PUT /api/external/v2/subscription-contracts-update-delivery-interval](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatedeliveryintervalv2.md): Changes the delivery/shipping frequency of a subscription contract. This allows customers to modify how often they receive their subscription orders. Key Features: - Flexible Delivery: Change delivery frequency (daily, weekly, monthly, yearly) - Custom Intervals: Set custom interval counts (e.g., every 2 weeks, every 3 months) - Independent from Billing: Delivery interval can differ from billing interval - Immediate Effect: Changes apply to the next delivery cycle - Activity Logging: All changes are logged for audit trail Delivery Interval Options: - DAY: Daily delivery (intervalCount: how many days) - WEEK: Weekly delivery (intervalCount: how many weeks) - MONTH: Monthly delivery (intervalCount: how many months) - YEAR: Yearly delivery (intervalCount: how many years) Common Examples: - intervalCount=1, interval=MONTH: Deliver monthly - intervalCount=2, interval=WEEK: Deliver every 2 weeks - intervalCount=3, interval=MONTH: Deliver quarterly - intervalCount=1, interval=WEEK: Deliver weekly - intervalCount=6, interval=MONTH: Deliver twice a year Billing vs. Delivery Intervals: These can be different! For example: - Bill monthly, deliver weekly: Customer pays monthly but receives weekly shipments - Bill quarterly, deliver monthly: Customer pays every 3 months but receives monthly shipments - Bill annually, deliver monthly: Customer pays yearly upfront for monthly deliveries Common Use Cases: - Customer wants deliveries less frequently (save on shipping) - Customer wants deliveries more frequently (use products faster) - Adjust delivery to match consumption rate - Seasonal frequency changes (more in summer, less in winter) - Align deliveries with schedule (delivery when home from vacation) Important Notes: - Billing Date Unchanged: Only affects delivery schedule, not billing schedule - Next Delivery Date: System recalculates next delivery date based on new interval - Order Fulfillment: Each delivery creates a new order at the specified interval - Prepaid Memberships: Particularly useful for prepaid plans with multiple deliveries Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update billing interval for subscription contract - [PUT /api/external/v2/subscription-contracts-update-billing-interval](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatebillingintervalv2.md): Changes the billing frequency of a subscription contract. This allows customers to modify how often they are charged for their membership. Key Features: - Flexible Billing: Change billing frequency (daily, weekly, monthly, yearly) - Custom Intervals: Set custom interval counts (e.g., every 2 weeks, every 3 months) - Immediate Effect: Changes apply to the next billing cycle - Independent from Delivery: Billing interval can differ from delivery interval - Activity Logging: All changes are logged for audit trail Billing Interval Options: - DAY: Daily billing (intervalCount: how many days) - WEEK: Weekly billing (intervalCount: how many weeks) - MONTH: Monthly billing (intervalCount: how many months) - YEAR: Yearly billing (intervalCount: how many years) Common Examples: - intervalCount=1, interval=MONTH: Bill monthly - intervalCount=2, interval=WEEK: Bill every 2 weeks - intervalCount=3, interval=MONTH: Bill quarterly - intervalCount=6, interval=MONTH: Bill semi-annually - intervalCount=1, interval=YEAR: Bill annually Common Use Cases: - Customer wants to change from monthly to quarterly billing - Switch from annual to monthly payments - Adjust billing frequency to match cash flow - Promotional frequency changes - Align billing with payday schedules Important Notes: - Next Billing Date: System recalculates the next billing date based on new interval - Pro-rata Billing: No pro-rata adjustment; new interval starts from next billing date - Minimum Cycles: Respects minimum billing cycle requirements if configured - Customer Portal Protection: Includes freeze checks if called from customer portal Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update subscription contract billing date - [PUT /api/external/v2/subscription-contracts-update-billing-date](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatenextbillingdatev2.md): Updates the next billing date for a subscription contract. This reschedules when the next payment will be charged for the membership. Key Features: - Flexible Rescheduling: Move billing date forward or backward - Immediate Effect: Changes take effect immediately in the billing schedule - Automatic Adjustments: Future billing dates recalculate based on frequency - Customer Portal Compatible: Can be triggered from customer self-service portal - Activity Logging: All changes are tracked in activity logs Billing Date Update Rules: - New date must be in the future (past dates are rejected) - Cannot update if contract is paused or cancelled - Cannot update if minimum billing cycles enforcement is active - Date format must be ISO 8601 with timezone (e.g., 2024-12-25T10:00:00Z) - Subsequent billing dates auto-calculate based on delivery frequency Common Use Cases: - Customer requests to postpone next delivery/billing - Align billing date with customer payday or preference - Skip a billing cycle due to vacation or temporary hold - Synchronize multiple subscriptions to bill on same day - Resolve payment timing conflicts or scheduling issues - Adjust for seasonal demand or customer availability Important Notes: - Changing billing date does NOT change the billing cycle frequency - If minimum cycles are configured, this may be restricted - Activity logs capture old date, new date, and change source - Customer receives updated billing schedule notification Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Remove product from recurring subscription - [PUT /api/external/v2/subscription-contracts-remove-line-item](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/removelineitemv2.md): Removes a line item (product) from a subscription contract. The product will no longer be included in future recurring orders. Product Removal Process: - Line Item Identification: Locates specific line item using GraphQL line ID - Contract Update: Removes line item from subscription - Discount Handling: Optionally removes associated line-item discounts - Price Recalculation: Updates subscription total after removal - Activity Logging: Records product removal event Key Features: - Selective Removal: Remove specific products by line ID - Discount Control: Choose whether to remove product-specific discounts - Immediate Effect: Changes apply to next billing cycle - Price Updates: Automatically adjusts subscription pricing Discount Removal Option: - removeDiscount=true (default): Removes discounts tied to this line item - removeDiscount=false: Keeps discounts (may apply to other items if applicable) - Only affects line-item-specific discounts, not subscription-level discounts Line ID Format: - GraphQL ID format: gid://shopify/SubscriptionLine/[ID] - Retrieve from subscription contract details endpoint - Each line item has unique ID Use Cases: - Customer downgrades subscription to fewer products - Remove seasonal products at end of season - Customer portal product removal workflows - Discontinued product cleanup - Subscription simplification (too many items) - Build-a-box customization changes Important Notes: - Cannot remove last line item (subscription needs at least one product) - Subscription must not be frozen - Removal is permanent (re-add if needed) - May affect shipping costs if weight/volume changes Returns: Updated subscription contract object with line item removed Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Remove discount from subscription - [PUT /api/external/v2/subscription-contracts-remove-discount](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/removediscountv2.md): Removes a discount from a subscription contract. This endpoint allows you to remove previously applied discounts, restoring the subscription to full price. Discount Removal Process: - Identify Discount: Uses discount ID to locate specific discount on contract - Remove From Contract: Removes discount allocation from subscription - Recalculate Pricing: Updates subscription pricing to remove discount - Activity Logging: Records discount removal event - Immediate Effect: Changes apply to next billing cycle Key Features: - Selective Removal: Remove specific discounts by ID - Price Restoration: Returns subscription to original or remaining discount pricing - Multiple Discount Support: Works with subscriptions having multiple discounts - Activity Tracking: Logs removal for audit trail Finding Discount ID: - Retrieve subscription contract details to see applied discounts - Each discount has a unique Shopify GraphQL ID - Format: gid://shopify/SubscriptionManualDiscount/[ID] Use Cases: - End limited-time promotional discounts - Remove expired retention offers - Customer service discount adjustments - Clean up incorrectly applied discounts - Remove trial period pricing - End referral program bonuses Returns: Updated subscription contract object with discount removed Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Apply discount code to subscription - [PUT /api/external/v2/subscription-contracts-apply-discount](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/applydiscountcodev2.md): Applies an existing Shopify discount code to a subscription contract. The discount code must already exist in Shopify and be valid for subscription usage. Discount Application Process: - Code Validation: Verifies discount code exists in Shopify - Eligibility Check: Ensures code is valid for subscription use - Contract Update: Applies discount to subscription contract - Price Recalculation: Updates subscription pricing with discount applied - Activity Logging: Records discount application event Key Features: - Existing Code Support: Uses Shopify discount codes already created in admin - Automatic Validation: Checks code validity and subscription eligibility - Immediate Application: Discount applies to next billing cycle - Contract Synchronization: Keeps Shopify contract in sync with discount Discount Code Requirements: - Must exist in Shopify admin - Must be active and not expired - Must be eligible for subscription purchases - Usage limits must not be exceeded Use Cases: - Allow customers to apply promotional codes to existing subscriptions - Customer service applying retention discounts - Reward program integration with discount codes - Referral program discount application - Seasonal promotion code application - Win-back campaign discount codes Returns: Updated subscription contract object with discount applied Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Add product to recurring subscription - [PUT /api/external/v2/subscription-contracts-add-line-item](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/addlineitemv2.md): Adds a new product variant to a subscription contract's recurring line items. The product will be included in all future recurring orders. Product Addition Process: - Variant Validation: Verifies product variant exists and is available - Add to Contract: Adds line item to subscription's recurring products - Quantity Setting: Sets initial quantity for the product - Price Calculation: Calculates pricing including any applicable discounts - Shipping Update: May recalculate shipping if weight/dimensions change - Activity Logging: Records product addition event Key Features: - Recurring Addition: Product added to every future order - Quantity Control: Specify exact quantity to add - Discount Inheritance: New item inherits subscription-level discounts - Immediate Effect: Applies to next billing cycle - Freeze Protection: Validates subscription isn't frozen before minimum cycles Variant ID Format: - Accepts Shopify variant ID as string - Can be numeric ID or GraphQL format - Example: "12345678" or "gid://shopify/ProductVariant/12345678" Use Cases: - Customer upgrades subscription to include more products - Cross-sell additional products to existing subscribers - Allow customers to customize subscriptions in portal - Add seasonal products to subscriptions - Build-a-box subscription customization - Upsell workflows during customer interactions Important Notes: - Product must be available for purchase - Subscription must not be frozen (before min cycles) - Price updates automatically with subscription billing - Quantity must be positive integer Returns: Updated subscription contract object with new line item Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Create and add custom discount to subscription - [PUT /api/external/v2/subscription-contracts-add-discount](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/adddiscountv2.md): Creates a custom discount and applies it to a subscription contract. This endpoint allows you to create on-the-fly discounts without requiring pre-existing discount codes in Shopify. Discount Creation & Application: - Custom Discount: Creates discount directly on subscription contract - Flexible Types: Supports percentage off or fixed amount off - Cycle Limits: Optional limit on number of billing cycles discount applies - Item-Level Control: Option to apply discount to each item vs entire order - Immediate Effect: Discount applies to next billing cycle Discount Parameters: - Percentage: Percentage discount (e.g., 15 for 15% off) - use for discountType='PERCENTAGE' - Amount: Fixed amount discount (e.g., 10.00 for $10 off) - use for discountType='FIXED_AMOUNT' - Title: Display name for the discount (e.g., 'Loyalty Discount') - Cycle Limit: Number of billing cycles discount applies (null = unlimited) - Applies On Each Item: true = per-item discount, false = order-level discount Discount Types: - PERCENTAGE: Percentage-based discount (use 'percentage' parameter) - FIXED_AMOUNT: Fixed dollar amount discount (use 'amount' parameter) Cycle Limit Examples: - recurringCycleLimit=1: Discount for first order only - recurringCycleLimit=3: Discount for first 3 orders - recurringCycleLimit=null: Discount applies forever Use Cases: - Customer retention offers (e.g., 20% off next 3 orders) - Loyalty rewards and point redemptions - Win-back campaigns with limited-time discounts - Customer service compensation discounts - Referral program rewards - First-order discounts for new subscribers - Seasonal promotions on existing subscriptions Example Scenarios: 1. Retention Offer: 25% off for 2 billing cycles - percentage=25, recurringCycleLimit=2, discountType='PERCENTAGE' 2. Loyalty Reward: $5 off every order forever - amount=5.00, recurringCycleLimit=null, discountType='FIXED_AMOUNT' 3. First Order Deal: 50% off first order only - percentage=50, recurringCycleLimit=1, discountType='PERCENTAGE' Returns: Updated subscription contract object with discount applied Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update product variant in subscription contract - [PUT /api/external/v2/subscription-contract-update-variant](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/updatevariantv2.md): Replaces an existing product variant with a new variant in a subscription contract. This allows customers to swap products in their membership while maintaining their subscription. Key Features: - Product Swapping: Replace any line item's variant with a different variant - Quantity Preservation: Maintains the same quantity after variant swap - Price Updates: New variant pricing is applied automatically - Flexible Identification: Identify old variant by lineId OR variantId - Activity Logging: All variant changes are logged for audit trail Identification Methods: You can identify the old variant using either: - oldLineId: The Shopify line item ID from the subscription contract - oldVariantId: The Shopify product variant ID At least one of these must be provided. Common Use Cases: - Customer wants to change product flavor/color/size in their membership - Swap discontinued products with new alternatives - Change product preferences mid-subscription - Update seasonal product selections - Replace out-of-stock variants with alternatives Important Notes: - Immediate Effect: Variant change applies to the next billing cycle - Validation: System validates new variant exists and is available - Same Product: Old and new variants can be from different products - Price Changes: Customer is charged the new variant's price Variant ID Format: - Accepts both numeric IDs and GraphQL IDs (gid://shopify/ProductVariant/...) - System automatically converts to correct format Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Add product line item to subscription contract - [PUT /api/external/v2/subscription-contract-add-line-item](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/addlineitemv2_1.md): Adds a new product (line item) to an existing subscription contract. This allows customers or merchants to add products to their recurring subscription orders. Key Features: - Add Products: Include new products in future subscription deliveries - Quantity Control: Specify how many units of the product to add - Price Override: Set custom pricing for the added product - Immediate Effect: Changes apply to next billing cycle - Activity Logging: All additions are tracked in activity logs Required Parameters: - contractId: Subscription contract ID to modify - variantId: Shopify product variant ID (with gid:// prefix or numeric) - quantity: Number of units to add (must be positive integer) - price: Price per unit in shop's base currency Product Variant ID Format: Accepts two formats: - Shopify GID: gid://shopify/ProductVariant/12345678901 - Numeric ID: 12345678901 Price Behavior: - Price is per unit, not total - Must be in shop's base currency (USD, EUR, etc.) - Can override product's default price - Does not include taxes or shipping - Total line item cost = price × quantity Line Item Addition Rules: - Product variant must exist in Shopify catalog - Product must be active and available - Variant must have sufficient inventory (if tracked) - Contract must be ACTIVE or PAUSED (not CANCELLED) - Cannot add duplicate variants (use update quantity instead) Common Use Cases: - Customer adds complementary product to existing subscription - Upsell additional products through customer portal - Merchant adds bonus items to customer subscriptions - Build custom "add-on" product selection interfaces - Cross-sell related products to existing subscribers - Create bundle upgrades (add multiple products at once) Post-Addition Effects: - Next billing amount increases by (price × quantity) - Product appears in all future subscription deliveries - Customer receives confirmation of subscription update - Activity log records the addition with source (portal/merchant) - Contract's next billing date remains unchanged Integration Example: PUT /api/external/v2/subscription-contract-add-line-item? contractId=123456& variantId=gid://shopify/ProductVariant/987654321& quantity=2& price=19.99 This adds 2 units of variant 987654321 at $19.99 each ($39.98 total) to contract 123456. Important Notes: - Changes apply to NEXT billing cycle, not current/past orders - If product is out of stock, order may be delayed or skipped - Price changes don't affect historical orders - Consider inventory availability before adding products Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get subscription customer details - [GET /api/external/v2/subscription-customers/{customerId}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getsubscriptioncustomerv2.md): Retrieves comprehensive customer information from Shopify for a specific customer ID. This endpoint fetches the customer record directly from Shopify's API, returning all personal details, addresses, payment methods, and metadata associated with the customer account. What This Endpoint Returns: Provides a complete Shopify Customer object containing all customer-related data for building customer portals, validating identities, displaying profiles, or integrating with external CRM/analytics systems. Response Data Structure: json { "id": "gid://shopify/Customer/6789012345", "email": "customer@example.com", "firstName": "Jane", "lastName": "Smith", "phone": "+1-555-123-4567", "displayName": "Jane Smith", "defaultAddress": { "address1": "123 Main St", "city": "San Francisco", "province": "CA", "zip": "94102", "country": "United States" }, "addresses": [...], "tags": ["VIP", "Subscriber"], "note": "Prefers morning deliveries", "state": "ENABLED", "createdAt": "2023-01-15T10:30:00Z" } Customer Data Fields Returned: Personal Information: - id - Shopify global customer ID (format: gid://shopify/Customer/{numeric_id}) - firstName - Customer's first name - lastName - Customer's last name - displayName - Full name for display purposes - email - Primary email address (unique identifier) - phone - Contact phone number (optional, may be null) Address Information: - defaultAddress - Primary shipping/billing address object - address1, address2 - Street address lines - city, province, zip, country - Location details - provinceCode, countryCodeV2 - Standardized codes - company - Company name (if B2B customer) - addresses - Array of all saved addresses (shipping + billing) Account Status: - state - Account status: ENABLED, DISABLED, INVITED, DECLINED - verifiedEmail - Whether email has been verified (boolean) - taxExempt - Tax exemption status (boolean) - acceptsMarketing - Email marketing opt-in status Metadata & Custom Fields: - tags - Array of customer tags for segmentation - note - Merchant notes about the customer - metafields - Custom data fields (if queried) - numberOfOrders - Total lifetime order count Timestamps: - createdAt - When customer account was created - updatedAt - Last modification timestamp Common Use Cases & Integration Scenarios: 1. Customer Portal - Profile Display Use Case: Show customer their account information 1. Get customerId from session/JWT token 2. Call GET /subscription-customers/{customerId} 3. Display: Name, Email, Default Address 4. Show "Edit Profile" button linking to address update endpoint 2. Pre-fill Shipping Address Form Use Case: Auto-populate address form when updating shipping 1. Fetch customer data via this endpoint 2. Extract defaultAddress object 3. Pre-fill form fields with existing address 4. Allow customer to edit and submit changes 3. Identity Verification Before Critical Actions Use Case: Verify customer email before canceling subscription 1. User clicks "Cancel Subscription" 2. Fetch customer data 3. Compare session email with customer.email 4. If mismatch: Reject (security violation) 5. If match: Proceed with cancellation 4. CRM Integration / Analytics Use Case: Sync customer data to external CRM (Salesforce, HubSpot) 1. Webhook triggers on customer update 2. Call this endpoint to get fresh customer data 3. Map fields to CRM schema 4. Push to CRM via their API 5. Customer Segmentation Use Case: Filter customers by tags for targeted campaigns 1. Fetch customer details 2. Check tags array for "VIP" or "Churned" 3. Apply special pricing or retention offers 4. Customize email communications Customer ID Format & Validation: - Input: Numeric Shopify customer ID (e.g., 6789012345) - Not Accepted: GraphQL global ID format (will cause 400 error) - Extraction from GraphQL ID: If you have gid://shopify/Customer/6789012345, extract 6789012345 - Example Valid IDs: 123, 456789, 9876543210 Privacy & Security Considerations: PII Protection: - This endpoint returns personally identifiable information (PII) - Ensure compliance with GDPR, CCPA, and privacy regulations - Only expose customer data to authenticated, authorized users - Do not log full customer records (contains emails, addresses, phone numbers) Access Control: - Customer can only access their own data (enforced by authentication) - Merchants can access all customers via API key - Never expose API keys in frontend code - Use server-to-server calls for merchant access Data Minimization: - Only fetch customer data when necessary - Cache responsibly with short TTL (5-10 minutes max) - Clear cache on customer updates Error Handling & Edge Cases: 404 - Customer Not Found: Reasons: - Customer ID doesn't exist in Shopify - Customer was deleted from Shopify admin - Wrong shop (customer belongs to different store) - Typo in customer ID Solution: - Verify customer ID is correct - Check if customer exists in Shopify admin - Ensure shop domain matches customer's store 400 - Invalid Customer ID Format: Reasons: - Non-numeric customer ID provided - Negative number or zero - GraphQL format instead of numeric ID Solution: - Ensure customer ID is positive integer - Extract numeric portion from GraphQL ID if needed 401 - Authentication Failed: Reasons: - Missing API key or customer portal token - Expired authentication token - Invalid API key for the shop Solution: - Verify X-API-Key header is set - Regenerate API key if compromised - Check token expiration Null/Empty Fields: Some fields may be null/empty if customer hasn't provided data: - phone - Not all customers provide phone numbers - addresses - New customers may have empty address list - defaultAddress - Could be null if no addresses saved - note - Empty unless merchant added notes - tags - Empty array if no tags assigned Always handle null checks in your code. Performance & Caching Recommendations: - Response Time: Typically 100-300ms (Shopify GraphQL query) - Rate Limits: Subject to Shopify API rate limits (40 requests/second) - Caching: Safe to cache for 5-10 minutes (customer data changes infrequently) - Optimization: Fetch once per session, store in memory/local state Related Endpoints: - /subscription-customers-detail/valid/{customerId} - Gets customer + subscription details - /subscription-contract-details - Lists all subscriptions for customer - /customer-payments/token/{customerId} - Get customer payment tokens - /customer-portal-token - Generate authentication token for customer Authentication: Requires API key authentication via X-API-Key header or api_key parameter. Customer portal tokens also supported for self-service access. ## Get valid subscription contract IDs for customer - [GET /api/external/v2/subscription-customers/valid/{customerId}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getvalidsubscriptioncustomerv2.md): Retrieves a list of all valid (active, paused, or pending) subscription contract IDs associated with a specific customer. This endpoint is useful for quickly checking which subscriptions a customer has without retrieving full contract details. Key Features: - Quick Lookup: Returns only contract IDs, not full contract details - Active Subscriptions Only: Excludes cancelled or expired contracts - Set Response: Returns unique contract IDs (no duplicates) - Fast Performance: Lightweight query for list views Included Subscription Statuses: - ACTIVE: Currently active recurring subscriptions - PAUSED: Temporarily paused but valid subscriptions - PENDING: Scheduled to start in the future Excluded Subscription Statuses: - CANCELLED: Customer-cancelled subscriptions - EXPIRED: Reached max cycles or end date - FAILED: Failed billing with no recovery Common Use Cases: - Subscription Count: Quickly determine how many active subscriptions a customer has - Access Control: Verify customer has valid subscriptions before showing portal - List Navigation: Build dropdown or list of customer's subscriptions - Bulk Operations: Get all contract IDs for batch processing - Validation: Check if customer has any active memberships - Dashboard Display: Show subscription count without full data Example Response: json [12345, 12346, 12389] Parameters: - customerId (required, path): The Shopify customer ID Response: Returns a Set of Long values representing valid subscription contract IDs Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get detailed customer subscription information - [GET /api/external/v2/subscription-customers-detail/valid/{customerId}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getvalidsubscriptioncustomerdetailsv2.md): Retrieves comprehensive details for all subscription contracts associated with a specific customer. This endpoint returns complete subscription contract data including products, pricing, billing schedule, and status. Key Information Returned: - Contract Details: Contract ID, status (active, paused, cancelled), creation date - Products: Line items with product names, variants, quantities, and prices - Billing Information: Next billing date, billing frequency, payment method - Delivery Details: Shipping address, delivery method, delivery frequency - Pricing: Subtotal, discounts applied, total amount per cycle - Membership Plan: Associated subscription plan name and details - Order History: Past billing attempts and fulfillment records Subscription Contract Details Include: - Contract ID: Unique identifier for the subscription - Customer ID: Shopify customer ID associated with the contract - Status: ACTIVE, PAUSED, CANCELLED, EXPIRED - Billing Cycle: Number of completed billing cycles - Next Billing Date: When the next payment will be charged - Delivery Date: When the next order will be shipped - Products: All line items in the subscription with pricing - Discount Codes: Applied discount codes and their values - Custom Attributes: Any custom metadata or tags Common Use Cases: - Display full subscription list in customer account dashboard - Retrieve all contract details for customer support inquiries - Build custom customer portal with subscription management - Sync subscription data to external CRM or analytics systems - Generate customer subscription reports and analytics - Validate customer's active subscriptions before offering upgrades - Show subscription history and upcoming deliveries Response Format: Returns a List of SubscriptionContractDetailsDTO objects, one per active/paused contract. If customer has no subscriptions, returns an empty list. Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get raw subscription contract details from Shopify - [GET /api/external/v2/subscription-contracts/contract-external/{contractId}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getsubscriptioncontractrawexternalv2.md): Retrieves the complete subscription contract data directly from Shopify's GraphQL API. This returns the full, unmodified Shopify contract object with all nested data. Key Features: - Raw Shopify Data: Direct response from Shopify API, not transformed - Complete Contract: All contract fields, line items, billing details - Real-Time Data: Fetches current state from Shopify (not cached) - Nested Objects: Includes customer, addresses, discounts, line items Returned Contract Data: - Contract ID & Status: Shopify global ID, status (ACTIVE/PAUSED/CANCELLED/EXPIRED) - Customer Info: Customer object with name, email, addresses - Line Items: Products/variants in subscription with quantities, prices - Billing Details: Next billing date, billing policy (frequency, interval) - Delivery Details: Delivery policy, shipping address, method - Pricing: Line prices, discounts, currency code - Dates: Created at, updated at, next billing date - Custom Attributes: Any custom data attached to the contract - Discounts: Applied discount codes with amounts Common Use Cases: - Full Contract Display: Show all contract details in admin/portal - Debugging: Inspect raw Shopify contract structure - Data Export: Get complete contract for reporting/analytics - Integration Development: Understand Shopify's contract schema - Audit Trail: Capture complete contract state at a point in time Differences from other endpoints: - This returns Shopify's raw contract object - /api/external/v2/subscription-contract-details returns transformed DTO - This includes more nested Shopify-specific fields Parameters: - contractId (required, path): The subscription contract ID (numeric) Response: Returns complete Shopify SubscriptionContract GraphQL object Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Send customer portal magic link via email - [GET /api/external/v2/subscription-contracts-email-magic-link](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/emailmagiclinkv2.md): Automatically generates and emails a secure magic link to the customer for accessing their subscription management portal. This is a convenience endpoint that combines token generation and email delivery in a single API call. Key Features: - Automated Delivery: Generates magic link and sends email in one operation - Customer Lookup: Finds customer by email address automatically - Branded Emails: Uses shop's configured email templates and branding - Subscription Validation: Only sends if customer has active subscriptions - Time-Limited Links: Email contains token that expires after configured duration Email Contents: The sent email typically includes: - Magic Link Button: One-click access to customer portal - Link URL: Full URL with embedded authentication token - Expiration Notice: When the link will expire (e.g., "Valid for 24 hours") - Shop Branding: Store logo, colors, and custom messaging - Help Text: Instructions on how to use the portal Workflow: 1. API receives customer email address 2. System looks up customer in Shopify by email 3. Validates customer has active subscription contracts 4. Generates secure JWT authentication token 5. Constructs magic link URL with token 6. Sends branded email with magic link to customer 7. Returns success confirmation to API caller Email Template Customization: Email appearance and content can be customized via: - Shop's email notification settings in admin - Custom email templates for magic links - Localization settings for customer's language - Custom branding (logo, colors, footer) Common Use Cases: - Customer support: send portal access link to customers over phone/chat - Automated workflows: trigger magic link emails based on events - Forgot password alternative: passwordless portal access - Post-purchase flows: send portal access after first order - Reactivation campaigns: re-engage paused/cancelled customers - Customer onboarding: welcome emails with portal access - Subscription reminders: include portal link in reminder emails Integration Example: GET /api/external/v2/subscription-contracts-email-magic-link? email=customer@example.com& api_key=your_api_key This sends a magic link email to customer@example.com for portal access. Error Handling: - If customer not found, returns 400 Bad Request - If customer has no active subscriptions, returns 400 - If email service fails, returns 500 Internal Server Error - Invalid email format returns 400 Bad Request Email Delivery Notes: - Emails are sent asynchronously (may take 1-5 minutes to deliver) - Check spam folders if customer doesn't receive email - Respect customer's email preferences and unsubscribe status - Rate limits may apply to prevent abuse Security Considerations: - Only send to verified customer email addresses - Email contains passwordless authentication link - Links expire after configured duration (default: 24-72 hours) - Sending to wrong email grants that person subscription access - Consider email verification before using this endpoint Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get membership/subscription contract list - [GET /api/external/v2/subscription-contract-details](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getallsubscriptioncontractdetailsexternal.md): Retrieves a paginated list of membership/subscription contracts with advanced filtering capabilities. This endpoint provides comprehensive access to all subscription contracts in your store with flexible query options. Key Information Returned: - Contract Details: Contract ID, status, creation date, billing cycle - Customer Information: Customer name, email, Shopify customer ID - Subscription Items: Products, variants, quantities in subscription - Billing Information: Next billing date, billing frequency, pricing - Delivery Details: Shipping address, delivery method, next delivery date - Plan Information: Membership plan type, selling plan IDs - Status Tracking: Active, paused, cancelled, expired states Filtering Capabilities: - Date Ranges: Filter by creation date or next billing date - Customer Search: Search by customer name or email - Status Filter: Filter by contract status (active, paused, cancelled) - Plan Type: Filter by membership plan type - Billing Frequency: Filter by billing interval (weekly, monthly, etc.) - Product/Variant: Find contracts containing specific products or variants - Order Name: Search by Shopify order name/number - Selling Plan: Filter by Shopify selling plan IDs - Special Filters: Contracts with deleted products or bounced emails Pagination: - Supports standard pagination parameters (page, size, sort) - Returns pagination headers for total count and navigation - Default page size configurable via request parameters Use Cases: - Export subscription data to external CRM or analytics systems - Build custom subscription dashboards and reports - Sync membership data with external platforms - Identify subscriptions needing attention (bounced emails, deleted products) - Generate subscription activity reports by date range - Find all subscriptions for a specific product or variant - Monitor subscription health and churn metrics Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get pending downgrade for a subscription contract - [GET /api/external/v2/subscription-contract-details/{contractId}/pending-downgrade](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getpendingdowngradev2.md): Retrieves the pending/scheduled downgrade details for a specific subscription contract. This endpoint returns information about a downgrade that has been scheduled but not yet executed. Response Information: - contractId: The subscription contract ID - waitTillTimestamp: When the downgrade will be executed - oldVariantId: The current product variant ID - newVariantId: The target product variant ID after downgrade - oldPrice: Current subscription price - newPrice: New price after downgrade - sellingPlanId: The selling plan ID for the new subscription - sellingPlanName: Name of the selling plan Use Cases: - Check if a customer has a pending downgrade scheduled - Display pending downgrade information in custom dashboards - Verify downgrade details before allowing further modifications Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Cancel pending downgrade for a subscription contract - [DELETE /api/external/v2/subscription-contract-details/{contractId}/pending-downgrade](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/cancelpendingdowngradev2.md): Cancels a scheduled/pending downgrade for a specific subscription contract. This endpoint removes the pending downgrade so that the subscription will continue with its current plan. Important Notes: - The downgrade must be pending (not yet executed) to be cancelled - Once cancelled, the subscription will remain on its current plan - An activity log entry is created when a downgrade is cancelled Use Cases: - Allow customers to change their mind about a scheduled downgrade - Cancel downgrades when customers upgrade or renew - Administrative cancellation of pending plan changes Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get subscription order fulfillment details - [GET /api/external/v2/subscription-contract-details/subscription-fulfillments/{contractId}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getsubscriptionfulfillmentsexternalv2.md): Retrieves fulfillment information for the most recent order generated by a subscription contract. Shows shipping status, tracking numbers, and delivery progress. Key Features: - Latest Order: Returns fulfillment data for the most recent subscription order - Tracking Info: Includes tracking numbers, URLs, and shipping carriers - Fulfillment Status: Shows whether items are unfulfilled, fulfilled, or partially fulfilled - Multi-Fulfillment: Handles orders split across multiple shipments Returned Fulfillment Data: - Order Info: Order name/number, creation date, financial status - Fulfillment Status: FULFILLED, PARTIAL, UNFULFILLED, etc. - Fulfillments List: Array of all fulfillments for the order - Tracking Numbers: Tracking codes for each fulfillment - Tracking URLs: Direct links to carrier tracking pages - Shipping Carrier: Carrier name (USPS, FedEx, UPS, etc.) - Fulfillment Date: When each shipment was fulfilled - Line Items: Which products/variants are in each shipment - Delivery Address: Where the order is being shipped Common Use Cases: - Order Tracking: Show customers where their subscription delivery is - Customer Portal: Display "Track Your Order" links - Shipping Updates: Check fulfillment status for recent orders - Support: Help customers track delayed or missing shipments - Notifications: Trigger custom shipping notifications - Analytics: Track fulfillment performance metrics Response Structure: Returns an Order object containing: - Basic order information - Array of fulfillments with tracking details - Line items per fulfillment - Shipping and delivery information Note: This returns data for the MOST RECENT order only. For historical fulfillment data, use order history endpoints. Parameters: - contractId (required, path): The subscription contract ID Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get billing interval options for selling plans - [GET /api/external/v2/subscription-contract-details/billing-interval](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getsubscriptioncontractbillinginterval.md): Retrieves available billing frequency/interval options for specified Shopify selling plans (subscription plans). This endpoint returns all configured billing frequencies that customers can choose from for their subscriptions. Key Information Returned: - Frequency Options: List of available billing intervals (e.g., weekly, monthly, quarterly) - Interval Units: Time unit for each option (DAYS, WEEKS, MONTHS, YEARS) - Interval Count: Number of units between billings (e.g., 2 = every 2 weeks) - Display Names: Customer-friendly names for each frequency option - Plan IDs: Associated selling plan IDs for each frequency Billing Frequency Structure: Each FrequencyInfoDTO contains: - id: Selling plan ID (Shopify subscription plan identifier) - name: Display name (e.g., "Deliver every 2 weeks", "Monthly subscription") - intervalUnit: Time unit (DAY, WEEK, MONTH, YEAR) - intervalCount: Number of units between deliveries - billingPolicy: How billing is configured (EXACT_DAY, ANNIVERSARY) - deliveryPolicy: How delivery is scheduled Common Billing Intervals: - Weekly: intervalUnit=WEEK, intervalCount=1 - Bi-Weekly: intervalUnit=WEEK, intervalCount=2 - Monthly: intervalUnit=MONTH, intervalCount=1 - Every 2 Months: intervalUnit=MONTH, intervalCount=2 - Quarterly: intervalUnit=MONTH, intervalCount=3 - Semi-Annual: intervalUnit=MONTH, intervalCount=6 - Annual: intervalUnit=YEAR, intervalCount=1 Request Parameters: - sellingPlanIds: Comma-separated list of Shopify selling plan IDs (required) - Example: "123456,123457,123458" - Returns frequency options for all specified plans Common Use Cases: - Display available billing frequencies in customer portal - Allow customers to change subscription delivery frequency - Build frequency selector UI components - Validate frequency options before updating subscription - Sync available billing options with external systems - Show frequency options during subscription checkout Integration Example: 1. Get customer's current subscription selling plan ID 2. Call this endpoint with that selling plan ID 3. Display returned frequency options to customer 4. Customer selects new frequency 5. Update subscription with selected frequency Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Generate customer portal magic link - [GET /api/external/v2/manage-subscription-link/{customerId}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getmanagesubscriptionlink.md): Generates a secure, time-limited magic link that allows customers to access and manage their subscriptions. This passwordless authentication link directs customers to the subscription management portal. Magic Link Features: - Passwordless Access: No login credentials required, link serves as authentication - Time-Limited: Link expires after configured duration (typically 24-72 hours) - Single Customer: Link is bound to specific customer ID, cannot be reused for others - Secure Token: Uses cryptographically secure JWT tokens for authentication - Customer Portal: Directs to full-featured self-service subscription portal Returned Information: - Magic Link URL: Full URL to customer portal with embedded authentication token - Token: JWT token value (can be used separately if needed) - Expiration Time: When the magic link will expire (ISO 8601 format) - Customer ID: Shopify customer ID the link is generated for - Shop Domain: Store domain where subscriptions are hosted Customer Portal Capabilities (via Magic Link): - View all active and paused subscription contracts - Update shipping address for upcoming deliveries - Change payment method for future billing - Pause or resume subscription deliveries - Skip upcoming delivery orders - Modify delivery frequency (e.g., monthly to bi-monthly) - Add or remove products from subscription - Swap product variants (size, flavor, color) - Cancel subscription with reason feedback - View order history and upcoming deliveries - Apply discount codes to subscription Common Use Cases: - Send magic link via email for customer self-service - Include link in transactional emails (order confirmation, shipping notices) - Customer support: provide link to customers over phone/chat - Embed link in customer account page or dashboard - Automated email campaigns for subscription management reminders - Post-purchase flows to encourage subscription modifications - Win-back campaigns: send magic link to cancelled/paused customers Security Notes: - Links are single-use per session (new token generated each time) - Tokens include shop and customer validation to prevent tampering - Expired links automatically redirect to token request page - Links should be sent via secure channels (HTTPS, encrypted email) Integration Best Practices: - Always send magic links via email or SMS (don't display on public pages) - Set appropriate expiration time based on use case - Include clear call-to-action in emails ("Manage Your Subscription") - Handle expired tokens gracefully with re-send functionality - Track magic link generation for security audit logs Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Generate customer portal authentication token - [GET /api/external/v2/customer-portal-token](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/getcustomerportaltoken.md): Generates an authentication token for customer portal access using either customer ID or email address. This token can be used to create magic links or authenticate API requests on behalf of a customer. Key Features: - Flexible Lookup: Find customer by Shopify customer ID OR email address - JWT Token: Returns cryptographically secure JSON Web Token - Portal Access: Token grants access to customer subscription management portal - API Authentication: Can be used in subsequent API calls for customer-specific operations - Time-Limited: Token expires after configured duration (default: 24-72 hours) Request Parameters: Provide either customerId OR email (not both): - customerId: Shopify customer ID (numeric string, e.g., "6789012345") - email: Customer's email address as registered in Shopify Response Contains: - customerId: Shopify customer ID associated with the token - token: JWT authentication token for portal access - shop: Store domain the customer belongs to - expiresAt: Token expiration timestamp (ISO 8601) Common Use Cases: - Generate token to construct customer portal magic links - Authenticate customer in headless commerce implementations - Validate customer identity before allowing subscription changes - Create custom portal integrations with embedded authentication - Server-side customer lookup when only email is available - Build custom subscription management UIs with API authentication - Integrate with external CRM systems requiring customer tokens Token Usage: Once generated, the token can be: 1. Embedded in magic link URLs: https://portal.example.com?token={token} 2. Used as Bearer token in Authorization headers for API calls 3. Stored temporarily for customer session management 4. Passed to frontend applications for customer-specific operations Security Best Practices: - Never expose tokens in client-side logs or browser storage - Transmit tokens only over HTTPS - Implement token rotation for long-lived sessions - Validate token expiration before use - Revoke tokens when customer logs out or changes credentials Error Handling: - If neither customerId nor email is provided, returns 400 Bad Request - If both customerId and email are provided, customerId takes precedence - If customer not found, returns 404 Not Found - Invalid email format returns 400 Bad Request Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## syncCustomerInfoV2 - [DELETE /api/external/v2/subscription-customers/sync-info/{customerId}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/synccustomerinfov2.md) ## Cancel membership/subscription contract - [DELETE /api/external/v2/subscription-contracts/{id}](https://developers.membership.appstle.com/admin-api-swagger/membership-contracts/deletesubscriptioncontractv2.md): Cancels a membership/subscription contract and sends cancellation confirmation emails. This endpoint terminates the recurring subscription and processes all cancellation workflows. Cancellation Process: - Contract Termination: Marks subscription as cancelled in Shopify - Billing Stop: Prevents future billing attempts - Email Notification: Sends cancellation confirmation to customer - Activity Logging: Records cancellation event with source and feedback - Feedback Capture: Optional cancellation reason for analytics Key Features: - Immediate Cancellation: Stops subscription processing immediately - Feedback Collection: Capture customer cancellation reasons - Automated Emails: Customer receives cancellation confirmation - Activity Tracking: Logs cancellation to activity history - Source Attribution: Tracks whether cancellation came from customer portal or API Validation Checks: - Contract Ownership: Verifies contract belongs to authenticated shop - Minimum Cycles: Checks if minimum billing cycles requirement is met (if configured) - Freeze Status: Validates subscription is not frozen - Existing Status: Ensures contract is not already cancelled Email Notifications: - Sends cancellation confirmation to customer email - Includes subscription details and cancellation date - Uses customizable email templates from shop settings Use Cases: - Allow customers to cancel from custom portals or mobile apps - Bulk cancellation workflows via external systems - Integration with customer service platforms - Automated cancellation based on business rules - Churn management and retention workflows Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update subscription contract status (pause/resume/activate) - [PUT /api/external/v2/subscription-contracts-update-status](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/updatestatusv2.md): Changes the status of a subscription contract. This allows pausing, resuming, or activating subscriptions to control billing and delivery. Key Features: - Pause Subscriptions: Temporarily stop billing and deliveries - Resume Subscriptions: Reactivate paused subscriptions - Activate Subscriptions: Start inactive subscriptions - Activity Logging: All status changes are logged for audit trail - Customer Restrictions: Includes minimum cycle checks when called from customer portal Status Values: - ACTIVE: Subscription is active and billing/delivering normally - PAUSED: Subscription is temporarily paused (no billing, no deliveries) - CANCELLED: Subscription is cancelled (use DELETE endpoint instead) Pause vs. Cancel: - Pause: Temporary hold, customer can resume anytime - Cancel: Permanent termination, requires creating new subscription to restart Common Use Cases: - Vacation Hold: Customer going on vacation, pause deliveries temporarily - Financial Pause: Customer needs temporary break from payments - Product Surplus: Customer has too much product, pause until they use it - Seasonal Pause: Pause subscriptions during off-season (e.g., lawn care in winter) - Resume After Pause: Customer ready to restart after temporary hold - Reactivate Failed: Reactivate subscription after payment method updated Pause Behavior: - Billing Paused: No charges while paused - Deliveries Paused: No orders created while paused - Next Billing Date: Preserved or recalculated on resume (merchant setting) - Unlimited Duration: Pauses can be indefinite unless merchant sets limits Resume Behavior: - Immediate Reactivation: Subscription becomes active immediately - Next Billing Date: Calculated based on pause duration settings - Deliveries Resume: Next delivery scheduled according to interval Customer Portal Restrictions: When called from customer portal (vs. merchant API): - Minimum Cycles: Cannot pause/cancel until minimum billing cycles met - Freeze Period: Updates may be frozen until minimum requirements satisfied - Retention Rules: Special retention discounts may be offered on cancellation Important Notes: - Customer Communication: Consider sending email notifications on status changes - Billing Cycles Not Lost: Paused cycles don't count toward minimums - No Pro-rata: No refunds or credits when pausing mid-cycle Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update shipping address for subscription contract - [PUT /api/external/v2/subscription-contracts-update-shipping-address](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/updateshippingaddressv2.md): Changes the delivery shipping address for a subscription contract. This allows customers to update where their subscription orders are delivered. Key Features: - Full Address Update: Change complete shipping address in one call - Address Validation: System validates address format and country codes - Immediate Effect: New address applies to the next delivery - Activity Logging: All address changes are logged for audit trail - International Support: Supports addresses in all countries Required Address Fields: - firstName: Recipient's first name - lastName: Recipient's last name - address1: Street address line 1 - city: City name - countryCode: ISO 3166-1 alpha-2 country code (e.g., US, CA, GB) - zip: Postal/ZIP code Optional Address Fields: - address2: Apartment, suite, unit number - company: Company name (for business addresses) - phone: Contact phone number - provinceCode: State/province code (e.g., CA, NY, ON) Common Use Cases: - Customer Moved: Update address after relocation - Temporary Address: Ship to vacation home or temporary location - Gift Recipient: Change recipient for gift subscriptions - Correct Typos: Fix address errors from initial signup - Business to Home: Switch between business and residential addresses - Seasonal Address: Update for snowbird/seasonal residents Country and Province Codes: - countryCode: Use ISO 3166-1 alpha-2 codes - Examples: US (United States), CA (Canada), GB (United Kingdom), AU (Australia) - provinceCode: Use ISO 3166-2 subdivision codes - US Examples: CA (California), NY (New York), TX (Texas) - Canada Examples: ON (Ontario), BC (British Columbia), QC (Quebec) Address Validation: - Format Validation: System checks required fields are present - Country Validation: Verifies country code is valid - Province Validation: Checks province code matches country - Postal Code: Validates postal code format for country Important Notes: - Shipping Rate Recalculation: New address may have different shipping costs - Delivery Method: System automatically selects appropriate delivery method - Next Order Only: Only affects future orders, not orders already placed - Address Book: Consider updating customer's default address separately - PO Boxes: Some delivery methods may not support PO Box addresses Shipping Cost Impact: - Changing address may change shipping costs for future deliveries - International addresses typically have higher shipping costs - Remote/rural areas may have additional delivery fees - Consider notifying customer of cost changes Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update delivery interval for subscription contract - [PUT /api/external/v2/subscription-contracts-update-delivery-interval](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/updatedeliveryintervalv2.md): Changes the delivery/shipping frequency of a subscription contract. This allows customers to modify how often they receive their subscription orders. Key Features: - Flexible Delivery: Change delivery frequency (daily, weekly, monthly, yearly) - Custom Intervals: Set custom interval counts (e.g., every 2 weeks, every 3 months) - Independent from Billing: Delivery interval can differ from billing interval - Immediate Effect: Changes apply to the next delivery cycle - Activity Logging: All changes are logged for audit trail Delivery Interval Options: - DAY: Daily delivery (intervalCount: how many days) - WEEK: Weekly delivery (intervalCount: how many weeks) - MONTH: Monthly delivery (intervalCount: how many months) - YEAR: Yearly delivery (intervalCount: how many years) Common Examples: - intervalCount=1, interval=MONTH: Deliver monthly - intervalCount=2, interval=WEEK: Deliver every 2 weeks - intervalCount=3, interval=MONTH: Deliver quarterly - intervalCount=1, interval=WEEK: Deliver weekly - intervalCount=6, interval=MONTH: Deliver twice a year Billing vs. Delivery Intervals: These can be different! For example: - Bill monthly, deliver weekly: Customer pays monthly but receives weekly shipments - Bill quarterly, deliver monthly: Customer pays every 3 months but receives monthly shipments - Bill annually, deliver monthly: Customer pays yearly upfront for monthly deliveries Common Use Cases: - Customer wants deliveries less frequently (save on shipping) - Customer wants deliveries more frequently (use products faster) - Adjust delivery to match consumption rate - Seasonal frequency changes (more in summer, less in winter) - Align deliveries with schedule (delivery when home from vacation) Important Notes: - Billing Date Unchanged: Only affects delivery schedule, not billing schedule - Next Delivery Date: System recalculates next delivery date based on new interval - Order Fulfillment: Each delivery creates a new order at the specified interval - Prepaid Memberships: Particularly useful for prepaid plans with multiple deliveries Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update billing interval for subscription contract - [PUT /api/external/v2/subscription-contracts-update-billing-interval](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/updatebillingintervalv2.md): Changes the billing frequency of a subscription contract. This allows customers to modify how often they are charged for their membership. Key Features: - Flexible Billing: Change billing frequency (daily, weekly, monthly, yearly) - Custom Intervals: Set custom interval counts (e.g., every 2 weeks, every 3 months) - Immediate Effect: Changes apply to the next billing cycle - Independent from Delivery: Billing interval can differ from delivery interval - Activity Logging: All changes are logged for audit trail Billing Interval Options: - DAY: Daily billing (intervalCount: how many days) - WEEK: Weekly billing (intervalCount: how many weeks) - MONTH: Monthly billing (intervalCount: how many months) - YEAR: Yearly billing (intervalCount: how many years) Common Examples: - intervalCount=1, interval=MONTH: Bill monthly - intervalCount=2, interval=WEEK: Bill every 2 weeks - intervalCount=3, interval=MONTH: Bill quarterly - intervalCount=6, interval=MONTH: Bill semi-annually - intervalCount=1, interval=YEAR: Bill annually Common Use Cases: - Customer wants to change from monthly to quarterly billing - Switch from annual to monthly payments - Adjust billing frequency to match cash flow - Promotional frequency changes - Align billing with payday schedules Important Notes: - Next Billing Date: System recalculates the next billing date based on new interval - Pro-rata Billing: No pro-rata adjustment; new interval starts from next billing date - Minimum Cycles: Respects minimum billing cycle requirements if configured - Customer Portal Protection: Includes freeze checks if called from customer portal Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update subscription contract billing date - [PUT /api/external/v2/subscription-contracts-update-billing-date](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/updatenextbillingdatev2.md): Updates the next billing date for a subscription contract. This reschedules when the next payment will be charged for the membership. Key Features: - Flexible Rescheduling: Move billing date forward or backward - Immediate Effect: Changes take effect immediately in the billing schedule - Automatic Adjustments: Future billing dates recalculate based on frequency - Customer Portal Compatible: Can be triggered from customer self-service portal - Activity Logging: All changes are tracked in activity logs Billing Date Update Rules: - New date must be in the future (past dates are rejected) - Cannot update if contract is paused or cancelled - Cannot update if minimum billing cycles enforcement is active - Date format must be ISO 8601 with timezone (e.g., 2024-12-25T10:00:00Z) - Subsequent billing dates auto-calculate based on delivery frequency Common Use Cases: - Customer requests to postpone next delivery/billing - Align billing date with customer payday or preference - Skip a billing cycle due to vacation or temporary hold - Synchronize multiple subscriptions to bill on same day - Resolve payment timing conflicts or scheduling issues - Adjust for seasonal demand or customer availability Important Notes: - Changing billing date does NOT change the billing cycle frequency - If minimum cycles are configured, this may be restricted - Activity logs capture old date, new date, and change source - Customer receives updated billing schedule notification Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Update product variant in subscription contract - [PUT /api/external/v2/subscription-contract-update-variant](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/updatevariantv2.md): Replaces an existing product variant with a new variant in a subscription contract. This allows customers to swap products in their membership while maintaining their subscription. Key Features: - Product Swapping: Replace any line item's variant with a different variant - Quantity Preservation: Maintains the same quantity after variant swap - Price Updates: New variant pricing is applied automatically - Flexible Identification: Identify old variant by lineId OR variantId - Activity Logging: All variant changes are logged for audit trail Identification Methods: You can identify the old variant using either: - oldLineId: The Shopify line item ID from the subscription contract - oldVariantId: The Shopify product variant ID At least one of these must be provided. Common Use Cases: - Customer wants to change product flavor/color/size in their membership - Swap discontinued products with new alternatives - Change product preferences mid-subscription - Update seasonal product selections - Replace out-of-stock variants with alternatives Important Notes: - Immediate Effect: Variant change applies to the next billing cycle - Validation: System validates new variant exists and is available - Same Product: Old and new variants can be from different products - Price Changes: Customer is charged the new variant's price Variant ID Format: - Accepts both numeric IDs and GraphQL IDs (gid://shopify/ProductVariant/...) - System automatically converts to correct format Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Add product line item to subscription contract - [PUT /api/external/v2/subscription-contract-add-line-item](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/addlineitemv2_1.md): Adds a new product (line item) to an existing subscription contract. This allows customers or merchants to add products to their recurring subscription orders. Key Features: - Add Products: Include new products in future subscription deliveries - Quantity Control: Specify how many units of the product to add - Price Override: Set custom pricing for the added product - Immediate Effect: Changes apply to next billing cycle - Activity Logging: All additions are tracked in activity logs Required Parameters: - contractId: Subscription contract ID to modify - variantId: Shopify product variant ID (with gid:// prefix or numeric) - quantity: Number of units to add (must be positive integer) - price: Price per unit in shop's base currency Product Variant ID Format: Accepts two formats: - Shopify GID: gid://shopify/ProductVariant/12345678901 - Numeric ID: 12345678901 Price Behavior: - Price is per unit, not total - Must be in shop's base currency (USD, EUR, etc.) - Can override product's default price - Does not include taxes or shipping - Total line item cost = price × quantity Line Item Addition Rules: - Product variant must exist in Shopify catalog - Product must be active and available - Variant must have sufficient inventory (if tracked) - Contract must be ACTIVE or PAUSED (not CANCELLED) - Cannot add duplicate variants (use update quantity instead) Common Use Cases: - Customer adds complementary product to existing subscription - Upsell additional products through customer portal - Merchant adds bonus items to customer subscriptions - Build custom "add-on" product selection interfaces - Cross-sell related products to existing subscribers - Create bundle upgrades (add multiple products at once) Post-Addition Effects: - Next billing amount increases by (price × quantity) - Product appears in all future subscription deliveries - Customer receives confirmation of subscription update - Activity log records the addition with source (portal/merchant) - Contract's next billing date remains unchanged Integration Example: PUT /api/external/v2/subscription-contract-add-line-item? contractId=123456& variantId=gid://shopify/ProductVariant/987654321& quantity=2& price=19.99 This adds 2 units of variant 987654321 at $19.99 each ($39.98 total) to contract 123456. Important Notes: - Changes apply to NEXT billing cycle, not current/past orders - If product is out of stock, order may be delayed or skipped - Price changes don't affect historical orders - Consider inventory availability before adding products Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get detailed customer subscription information - [GET /api/external/v2/subscription-customers-detail/valid/{customerId}](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/getvalidsubscriptioncustomerdetailsv2.md): Retrieves comprehensive details for all subscription contracts associated with a specific customer. This endpoint returns complete subscription contract data including products, pricing, billing schedule, and status. Key Information Returned: - Contract Details: Contract ID, status (active, paused, cancelled), creation date - Products: Line items with product names, variants, quantities, and prices - Billing Information: Next billing date, billing frequency, payment method - Delivery Details: Shipping address, delivery method, delivery frequency - Pricing: Subtotal, discounts applied, total amount per cycle - Membership Plan: Associated subscription plan name and details - Order History: Past billing attempts and fulfillment records Subscription Contract Details Include: - Contract ID: Unique identifier for the subscription - Customer ID: Shopify customer ID associated with the contract - Status: ACTIVE, PAUSED, CANCELLED, EXPIRED - Billing Cycle: Number of completed billing cycles - Next Billing Date: When the next payment will be charged - Delivery Date: When the next order will be shipped - Products: All line items in the subscription with pricing - Discount Codes: Applied discount codes and their values - Custom Attributes: Any custom metadata or tags Common Use Cases: - Display full subscription list in customer account dashboard - Retrieve all contract details for customer support inquiries - Build custom customer portal with subscription management - Sync subscription data to external CRM or analytics systems - Generate customer subscription reports and analytics - Validate customer's active subscriptions before offering upgrades - Show subscription history and upcoming deliveries Response Format: Returns a List of SubscriptionContractDetailsDTO objects, one per active/paused contract. If customer has no subscriptions, returns an empty list. Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Send customer portal magic link via email - [GET /api/external/v2/subscription-contracts-email-magic-link](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/emailmagiclinkv2.md): Automatically generates and emails a secure magic link to the customer for accessing their subscription management portal. This is a convenience endpoint that combines token generation and email delivery in a single API call. Key Features: - Automated Delivery: Generates magic link and sends email in one operation - Customer Lookup: Finds customer by email address automatically - Branded Emails: Uses shop's configured email templates and branding - Subscription Validation: Only sends if customer has active subscriptions - Time-Limited Links: Email contains token that expires after configured duration Email Contents: The sent email typically includes: - Magic Link Button: One-click access to customer portal - Link URL: Full URL with embedded authentication token - Expiration Notice: When the link will expire (e.g., "Valid for 24 hours") - Shop Branding: Store logo, colors, and custom messaging - Help Text: Instructions on how to use the portal Workflow: 1. API receives customer email address 2. System looks up customer in Shopify by email 3. Validates customer has active subscription contracts 4. Generates secure JWT authentication token 5. Constructs magic link URL with token 6. Sends branded email with magic link to customer 7. Returns success confirmation to API caller Email Template Customization: Email appearance and content can be customized via: - Shop's email notification settings in admin - Custom email templates for magic links - Localization settings for customer's language - Custom branding (logo, colors, footer) Common Use Cases: - Customer support: send portal access link to customers over phone/chat - Automated workflows: trigger magic link emails based on events - Forgot password alternative: passwordless portal access - Post-purchase flows: send portal access after first order - Reactivation campaigns: re-engage paused/cancelled customers - Customer onboarding: welcome emails with portal access - Subscription reminders: include portal link in reminder emails Integration Example: GET /api/external/v2/subscription-contracts-email-magic-link? email=customer@example.com& api_key=your_api_key This sends a magic link email to customer@example.com for portal access. Error Handling: - If customer not found, returns 400 Bad Request - If customer has no active subscriptions, returns 400 - If email service fails, returns 500 Internal Server Error - Invalid email format returns 400 Bad Request Email Delivery Notes: - Emails are sent asynchronously (may take 1-5 minutes to deliver) - Check spam folders if customer doesn't receive email - Respect customer's email preferences and unsubscribe status - Rate limits may apply to prevent abuse Security Considerations: - Only send to verified customer email addresses - Email contains passwordless authentication link - Links expire after configured duration (default: 24-72 hours) - Sending to wrong email grants that person subscription access - Consider email verification before using this endpoint Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Get billing interval options for selling plans - [GET /api/external/v2/subscription-contract-details/billing-interval](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/getsubscriptioncontractbillinginterval.md): Retrieves available billing frequency/interval options for specified Shopify selling plans (subscription plans). This endpoint returns all configured billing frequencies that customers can choose from for their subscriptions. Key Information Returned: - Frequency Options: List of available billing intervals (e.g., weekly, monthly, quarterly) - Interval Units: Time unit for each option (DAYS, WEEKS, MONTHS, YEARS) - Interval Count: Number of units between billings (e.g., 2 = every 2 weeks) - Display Names: Customer-friendly names for each frequency option - Plan IDs: Associated selling plan IDs for each frequency Billing Frequency Structure: Each FrequencyInfoDTO contains: - id: Selling plan ID (Shopify subscription plan identifier) - name: Display name (e.g., "Deliver every 2 weeks", "Monthly subscription") - intervalUnit: Time unit (DAY, WEEK, MONTH, YEAR) - intervalCount: Number of units between deliveries - billingPolicy: How billing is configured (EXACT_DAY, ANNIVERSARY) - deliveryPolicy: How delivery is scheduled Common Billing Intervals: - Weekly: intervalUnit=WEEK, intervalCount=1 - Bi-Weekly: intervalUnit=WEEK, intervalCount=2 - Monthly: intervalUnit=MONTH, intervalCount=1 - Every 2 Months: intervalUnit=MONTH, intervalCount=2 - Quarterly: intervalUnit=MONTH, intervalCount=3 - Semi-Annual: intervalUnit=MONTH, intervalCount=6 - Annual: intervalUnit=YEAR, intervalCount=1 Request Parameters: - sellingPlanIds: Comma-separated list of Shopify selling plan IDs (required) - Example: "123456,123457,123458" - Returns frequency options for all specified plans Common Use Cases: - Display available billing frequencies in customer portal - Allow customers to change subscription delivery frequency - Build frequency selector UI components - Validate frequency options before updating subscription - Sync available billing options with external systems - Show frequency options during subscription checkout Integration Example: 1. Get customer's current subscription selling plan ID 2. Call this endpoint with that selling plan ID 3. Display returned frequency options to customer 4. Customer selects new frequency 5. Update subscription with selected frequency Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Generate customer portal magic link - [GET /api/external/v2/manage-subscription-link/{customerId}](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/getmanagesubscriptionlink.md): Generates a secure, time-limited magic link that allows customers to access and manage their subscriptions. This passwordless authentication link directs customers to the subscription management portal. Magic Link Features: - Passwordless Access: No login credentials required, link serves as authentication - Time-Limited: Link expires after configured duration (typically 24-72 hours) - Single Customer: Link is bound to specific customer ID, cannot be reused for others - Secure Token: Uses cryptographically secure JWT tokens for authentication - Customer Portal: Directs to full-featured self-service subscription portal Returned Information: - Magic Link URL: Full URL to customer portal with embedded authentication token - Token: JWT token value (can be used separately if needed) - Expiration Time: When the magic link will expire (ISO 8601 format) - Customer ID: Shopify customer ID the link is generated for - Shop Domain: Store domain where subscriptions are hosted Customer Portal Capabilities (via Magic Link): - View all active and paused subscription contracts - Update shipping address for upcoming deliveries - Change payment method for future billing - Pause or resume subscription deliveries - Skip upcoming delivery orders - Modify delivery frequency (e.g., monthly to bi-monthly) - Add or remove products from subscription - Swap product variants (size, flavor, color) - Cancel subscription with reason feedback - View order history and upcoming deliveries - Apply discount codes to subscription Common Use Cases: - Send magic link via email for customer self-service - Include link in transactional emails (order confirmation, shipping notices) - Customer support: provide link to customers over phone/chat - Embed link in customer account page or dashboard - Automated email campaigns for subscription management reminders - Post-purchase flows to encourage subscription modifications - Win-back campaigns: send magic link to cancelled/paused customers Security Notes: - Links are single-use per session (new token generated each time) - Tokens include shop and customer validation to prevent tampering - Expired links automatically redirect to token request page - Links should be sent via secure channels (HTTPS, encrypted email) Integration Best Practices: - Always send magic links via email or SMS (don't display on public pages) - Set appropriate expiration time based on use case - Include clear call-to-action in emails ("Manage Your Subscription") - Handle expired tokens gracefully with re-send functionality - Track magic link generation for security audit logs Authentication: Requires API key authentication via X-API-Key header or api_key parameter ## Generate customer portal authentication token - [GET /api/external/v2/customer-portal-token](https://developers.membership.appstle.com/admin-api-swagger/subscription-contract-management/getcustomerportaltoken.md): Generates an authentication token for customer portal access using either customer ID or email address. This token can be used to create magic links or authenticate API requests on behalf of a customer. Key Features: - Flexible Lookup: Find customer by Shopify customer ID OR email address - JWT Token: Returns cryptographically secure JSON Web Token - Portal Access: Token grants access to customer subscription management portal - API Authentication: Can be used in subsequent API calls for customer-specific operations - Time-Limited: Token expires after configured duration (default: 24-72 hours) Request Parameters: Provide either customerId OR email (not both): - customerId: Shopify customer ID (numeric string, e.g., "6789012345") - email: Customer's email address as registered in Shopify Response Contains: - customerId: Shopify customer ID associated with the token - token: JWT authentication token for portal access - shop: Store domain the customer belongs to - expiresAt: Token expiration timestamp (ISO 8601) Common Use Cases: - Generate token to construct customer portal magic links - Authenticate customer in headless commerce implementations - Validate customer identity before allowing subscription changes - Create custom portal integrations with embedded authentication - Server-side customer lookup when only email is available - Build custom subscription management UIs with API authentication - Integrate with external CRM systems requiring customer tokens Token Usage: Once generated, the token can be: 1. Embedded in magic link URLs: https://portal.example.com?token={token} 2. Used as Bearer token in Authorization headers for API calls 3. Stored temporarily for customer session management 4. Passed to frontend applications for customer-specific operations Security Best Practices: - Never expose tokens in client-side logs or browser storage - Transmit tokens only over HTTPS - Implement token rotation for long-lived sessions - Validate token expiration before use - Revoke tokens when customer logs out or changes credentials Error Handling: - If neither customerId nor email is provided, returns 400 Bad Request - If both customerId and email are provided, customerId takes precedence - If customer not found, returns 404 Not Found - Invalid email format returns 400 Bad Request Authentication: Requires API key authentication via X-API-Key header or api_key parameter