# Customer Portal APIs Comprehensive API documentation for the customer-facing subscription portal. These APIs enable customers to manage their subscriptions, update billing information, modify delivery schedules, and access their account details through your storefront. **Important**: These APIs must be called from your shop's domain (e.g., https://www.myshop.com/apps/subscriptions/cp/api/**) and require customer authentication. Unauthenticated requests will return a 401 Unauthorized error. Version: 0.0.1 ## Servers ``` https://www.myshop.com/apps ``` ## Download OpenAPI description [Customer Portal APIs](https://developers.subscription.appstle.com/_bundle/customer-portal-swagger.yaml) ## Customer Portal Core customer portal APIs for managing customer account settings, authentication, and portal configurations. ### Process refund for subscription order - [PUT /subscriptions/cp/api/subscription-billing-attempts/refund-fulfillment/{id}](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/refundfulfillment.md): Processes a refund for a fulfilled subscription order. This creates a refund in Shopify and returns the money to the customer's original payment method. What it does: 1. Validates order is eligible for refund (fulfilled, not already refunded) 2. Creates refund transaction in Shopify 3. Processes refund with payment gateway 4. Updates order status to 'Refunded' 5. Sends refund confirmation email to customer 6. Logs refund activity Refund Eligibility: - Order must be fulfilled - Cannot already be refunded - Must be within merchant's refund policy window - Payment gateway must support refunds Refund Processing: - Refund is processed to original payment method - Takes 5-10 business days to appear in customer's account - Processing fees are typically not refunded - Partial refunds are supported (if configured) Important Warnings: - This action cannot be undone - Refunded orders cannot be un-refunded - Inventory is restocked automatically - Refunds may incur gateway fees Authentication: Customer must be logged in and own the subscription ### Redeem loyalty points for a reward - [POST /subscriptions/cp/api/loyalty-integration/redeem](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/redeempoints.md): Allows a customer to redeem their loyalty points for a specific reward option. This deducts points from their balance and generates a discount code or applies the reward. What happens: 1. Validates customer has enough points 2. Deducts points from customer's balance 3. Generates discount code (for discount rewards) 4. Records redemption in customer's history 5. Returns discount code or confirmation Reward Types: - Discount codes: Generates unique code customer can use at checkout - Auto-apply discounts: Automatically applied to next order - Free products: Adds free product to next order - Free shipping: Waives shipping on next order Important Notes: - Points are deducted immediately and cannot be refunded - Discount codes typically expire after 30 days - Some rewards have minimum purchase requirements - Rewards cannot be combined with other discounts (depends on configuration) Use Cases: - Customer clicks 'Redeem' button in customer portal - Apply points at checkout - Redeem points for subscription discount Authentication: Customer must be logged in via Shopify customer session ### Initiate Customer Account API OAuth flow - [POST /subscriptions/cp/api/customer-account-api/initiate](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/initiateoauth.md): Initiates the OAuth 2.0 authorization flow for Shopify's Customer Account API. This endpoint is used when a customer wants to grant the subscription app access to their Shopify customer account data. What is Customer Account API? Shopify's Customer Account API allows apps to access customer data (orders, addresses, payment methods) on behalf of the customer. This requires customer consent through an OAuth flow. How it works: 1. Customer portal calls this endpoint with a return URL 2. Backend generates PKCE challenge and state parameter 3. Returns authorization URL to redirect customer to Shopify 4. Customer authorizes on Shopify 5. Shopify redirects back to callback endpoint with authorization code 6. Callback endpoint exchanges code for access token Important Notes: - Requires customer to be logged in to the Shopify store - Only works with stores that have 'New Customer Accounts' enabled - Uses PKCE (Proof Key for Code Exchange) for security - State parameter prevents CSRF attacks - Access tokens are stored securely and used for subsequent Customer Account API calls Authentication: Customer must be logged in via Shopify customer session ### Proxy GraphQL queries to Shopify Customer Account API - [POST /subscriptions/cp/api/customer-account-api/graphql](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/proxygraphql.md): Executes GraphQL queries against Shopify's Customer Account API on behalf of the authenticated customer. This endpoint handles token management, refresh, and authentication automatically. What you can query: - Customer profile information - Order history and details - Saved addresses - Payment methods - Subscriptions (via Customer Account API schema) Token Management: - Automatically uses stored access token - Refreshes expired tokens automatically - Returns 401 if customer needs to re-authenticate Example Queries: graphql query { customer { id emailAddress { emailAddress } defaultAddress { address1 city } } } Authentication: Customer must be logged in and have completed OAuth flow ### Get available loyalty point redemption options - [GET /subscriptions/cp/api/loyalty-integration/redeem-options](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/getredeemoptionsforcp.md): Returns all available rewards that the customer can redeem their loyalty points for. This shows customers what they can spend their points on. Common Redemption Options: - Discount codes (e.g., $5 off for 500 points) - Percentage discounts (e.g., 10% off for 1000 points) - Free shipping rewards - Free products or samples - Exclusive access to sales Response includes: - Redemption option ID - Name and description - Points cost - Reward value (dollar amount or percentage) - Availability (minimum purchase, restrictions) - Whether customer has enough points Filtering: - Only shows active redemption options - Filters based on customer's tier/VIP level - Shows whether customer has sufficient points Use Cases: - Display 'Redeem Points' section in customer portal - Show available rewards in checkout - Encourage customers to save points for bigger rewards Authentication: Customer must be logged in via Shopify customer session ### Get customer loyalty points and rewards data - [GET /subscriptions/cp/api/loyalty-integration/customer](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/fetchcustomerdetailforcp.md): Retrieves the loyalty/rewards program data for the currently logged-in customer. This includes points balance, tier status, and available rewards. Supported Loyalty Programs: - Appstle Loyalty & Rewards - Yotpo Loyalty & Referrals - Smile.io (via Appstle integration) What you get: - Current points balance - Points pending (from recent orders) - VIP tier/level - Points history - Available reward redemptions Use Cases: - Display points balance in customer portal - Show available rewards customer can redeem - Display VIP tier badge - Show points expiration dates Authentication: Customer must be logged in via Shopify customer session Note: Requires loyalty app integration to be configured in merchant settings ### Get currently logged-in customer ID - [GET /subscriptions/cp/api/logged-in-customer](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/updatesubscriptioncontractdetails_1.md): Returns the customer ID of the currently authenticated customer from their Shopify session. This endpoint is used by the customer portal UI to identify which customer is logged in. Use Cases: - Customer portal initialization - determine who's logged in - Fetch customer-specific data (subscriptions, orders, settings) - Validate customer session before displaying sensitive information - Personalize customer portal UI with customer name/email How it works: - Customer must be logged in to their Shopify customer account - Session is validated via Shopify App Proxy - Returns Shopify customer ID (numeric) Important Notes: - This endpoint only works when called from the shop domain (via Shopify App Proxy) - Customer must be logged in to Shopify - Returns null if customer is not authenticated - Do not use this for external API integrations - use External APIs with explicit customer ID instead Authentication: Requires active Shopify customer session (browser-based) ### Get custom CSS for customer portal - [GET /subscriptions/cp/api/subscription-custom-csses/{id}](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/getsubscriptioncustomcss.md): Retrieves the custom CSS styling configuration for the customer portal. This endpoint returns all custom CSS rules that have been configured to customize the appearance, layout, and branding of the subscription customer portal. What is Custom CSS? Custom CSS allows merchants to fully customize the visual appearance of their customer portal beyond the basic theme settings. This enables complete brand alignment and creates a seamless experience that matches the merchant's main store design. Custom CSS Capabilities: - Layout Customization: - Modify page layouts and spacing - Adjust grid and flexbox configurations - Control responsive breakpoints - Customize navigation and sidebars - Typography: - Custom fonts and font families - Font sizes, weights, and line heights - Letter spacing and text transforms - Heading and paragraph styles - Colors and Branding: - Brand color palette application - Custom background colors and gradients - Button and link styling - Hover and focus states - Border colors and shadows - Component Styling: - Subscription card appearances - Form input styling - Button designs and interactions - Modal and dialog boxes - Navigation menus - Product images and thumbnails - Advanced Features: - CSS animations and transitions - Media queries for responsive design - Pseudo-elements and pseudo-classes - Custom icons using CSS - Transform and filter effects CSS Structure: The returned CSS includes: - Global styles for portal-wide consistency - Component-specific styles - Responsive design rules - Theme overrides - Custom animations - Print styles (optional) Common CSS Selectors Available: css / Portal container / .subscription-portal { } / Subscription cards / .subscription-card { } .subscription-card-header { } .subscription-card-body { } / Buttons / .btn-primary { } .btn-secondary { } .btn-cancel { } / Forms / .form-control { } .form-group { } .form-label { } / Navigation / .portal-nav { } .nav-item { } / Product displays / .product-item { } .product-image { } .product-title { } Use Cases: - Apply custom branding to match main store design - Create unique visual experiences for different customer segments - Implement seasonal or promotional themes - Enhance mobile responsiveness - Add accessibility improvements (high contrast, larger fonts) - A/B test different portal designs - Integrate with design systems - Implement dark mode or theme switching Important Notes: - CSS is sanitized for security (XSS prevention) - Certain properties may be restricted for security reasons - External resources (fonts, images) must use HTTPS - CSS is cached for performance - changes may take a few minutes to propagate - Invalid CSS syntax is automatically filtered out - Some core portal elements have !important styles that cannot be overridden Best Practices: - Use specific selectors to avoid conflicts - Test across different browsers and devices - Keep CSS organized with comments - Use CSS variables for maintainability - Minify CSS for production performance - Consider accessibility in color choices (WCAG compliance) - Provide fallbacks for advanced CSS features Security Considerations: - CSS is sanitized to prevent code injection - External URLs are validated - JavaScript in CSS is blocked (e.g., expression(), behavior()) - Data URIs are validated for malicious content Authentication: Requires valid X-API-Key header ### Calculate refund amount preview - [GET /subscriptions/cp/api/subscription-billing-attempts/refund-preview/{id}](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/calculaterefundpreview.md): Calculates the refund amount that would be issued if a specific subscription order fulfillment were refunded. This provides a preview without actually processing the refund. What it calculates: - Total refund amount (order amount minus processing fees) - Restocking fees (if applicable) - Gateway fees that cannot be refunded - Net refund amount customer will receive Use Cases: - Show customer how much they'll get back before confirming refund - Display refund breakdown in customer portal - Validate refund eligibility Important Notes: - This is a preview only - does not process refund - Refund amount may vary based on payment gateway - Some gateways don't refund processing fees - Refunds can only be issued for fulfilled orders Authentication: Customer must be logged in and own the subscription ### Get available ways to earn loyalty points - [GET /subscriptions/cp/api/loyalty-integration/earn-options](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/getearnoptions.md): Returns all active point earning campaigns and rules that the customer can participate in. This shows customers how they can earn more points. Common Earning Methods: - Points per dollar spent on purchases - Bonus points for first subscription - Points for referring friends - Birthday bonus points - Social media follows (Instagram, Facebook, Twitter) - Product reviews - Account creation bonus Response includes: - Campaign name and description - Points awarded - Action required (e.g., 'Follow on Instagram') - Icon/image URL - Terms and conditions Use Cases: - Display 'Ways to Earn' section in customer portal - Show earning opportunities on product pages - Encourage customer engagement Authentication: Customer must be logged in via Shopify customer session ### Get customer portal settings - [GET /subscriptions/cp/api/customer-portal-settings/{id}](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/getcustomerportalsettings.md): Retrieves the customer portal configuration and settings for the authenticated shop. The customer portal is the self-service interface where subscribers can manage their subscriptions, update payment methods, modify delivery addresses, and more. What is the Customer Portal? The customer portal is a dedicated web interface that allows your subscribers to manage their subscription accounts independently. This reduces support burden and improves customer experience by enabling self-service subscription management. Settings Returned: - Display Configuration: - Portal theme and branding settings - Custom colors and logo - Layout preferences - Custom CSS selectors - Feature Toggles: - Enable/disable subscription pausing - Enable/disable order skipping - Enable/disable product swapping - Enable/disable frequency changes - Enable/disable quantity modifications - Enable/disable address editing - Enable/disable payment method updates - Enable/disable subscription cancellation - Subscription Management Options: - Maximum pause duration allowed - Minimum subscription duration requirements - Skip limits per billing cycle - Product swap availability - One-time product add-ons - Communication Settings: - Email notification preferences - Custom portal messaging - Support contact information - Help text and instructions - Access Control: - Portal authentication method - Password requirements - Magic link settings - Session duration - Advanced Options: - Custom domain configuration - Redirect URLs - Webhook endpoints - Analytics tracking settings Use Cases: - Display customer portal with correct branding and theme - Determine which features are available to subscribers - Build custom portal interfaces using your settings - Sync portal configuration across systems - Validate subscription management capabilities - Configure third-party integrations Important Notes: - Settings are shop-specific and unique per merchant - Some features may be restricted based on subscription plan - Changes to settings are reflected immediately in the portal - Custom CSS must be valid and secure - Portal URL is typically: shop-domain.com/apps/subscriptions Common Configuration Scenarios: 1. Standard Self-Service Portal: - Allow pausing (up to 3 months) - Allow skipping (max 2 consecutive orders) - Allow frequency changes - Allow quantity updates - Allow address editing - Enable payment method updates - Enable cancellation with feedback 2. Locked-Down Portal (Minimal Self-Service): - Disable pausing - Disable skipping - Disable cancellation (require support contact) - Allow address editing only - Allow payment method updates only 3. Full-Service Portal (Maximum Flexibility): - Enable all subscription management features - Allow unlimited pauses and skips - Enable product swapping - Enable one-time add-ons - Allow subscription splitting/merging - Custom branding and domain Authentication: Requires valid X-API-Key header ### Check Customer Account API authentication status - [GET /subscriptions/cp/api/customer-account-api/status](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/checkauthstatus.md): Checks whether the current customer has valid Customer Account API tokens stored. Used by the customer portal to determine if the customer needs to authenticate. Use Cases: - Check if customer is authenticated before making Customer Account API GraphQL calls - Determine whether to show 'Connect Account' button in UI - Validate token validity before attempting sensitive operations Response: Returns authentication status and customer ID. Authentication: Customer must be logged in via Shopify customer session ### Handle OAuth callback from Shopify - [GET /subscriptions/cp/api/customer-account-api/oauth/callback](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/handleoauthcallback.md): OAuth 2.0 callback endpoint that receives the authorization code from Shopify after customer authorization. This endpoint is called automatically by Shopify after the customer authorizes the app. Flow: 1. Shopify redirects customer here with authorization code and state 2. Validates state parameter to prevent CSRF 3. Exchanges authorization code for access token using PKCE verifier 4. Validates ID token (JWT) from Shopify 5. Stores access token and refresh token securely 6. Redirects customer back to original return URL Security: - Validates state parameter matches stored value - Uses PKCE code verifier to exchange authorization code - Validates ID token signature and claims - State expires after 10 minutes Error Handling: - If customer denies authorization, redirects with error parameter - If token exchange fails, redirects with error parameter - All errors are logged for debugging Note: This endpoint should not be called directly - it's invoked by Shopify's OAuth redirect. ### Logout from Customer Account API - [GET /subscriptions/cp/api/customer-account-api/logout](https://developers.subscription.appstle.com/customer-portal-swagger/customer-portal/handlelogout.md): Logs out the customer from the Customer Account API session. This can be initiated either by the customer clicking logout in the customer portal, or by Shopify's end session callback. What it does: - Deletes stored access and refresh tokens - Initiates Shopify's end session flow (if tokens available) - Redirects to return URL or back to customer portal Two scenarios: 1. App-initiated logout: Customer clicks logout in portal - Portal calls this endpoint with return URL - Tokens deleted, redirects to Shopify end session endpoint - Shopify redirects back to return URL 2. Shopify-initiated logout: Customer logs out globally from Shopify - Shopify calls this endpoint with id_token_hint - Tokens deleted, returns success Important: - This only logs out from Customer Account API, not from Shopify customer account - Customer will need to re-authenticate to use Customer Account API features again - Does not affect regular customer portal access (subscription management) Authentication: Optional - can be called from Shopify without authentication ## Subscription Management APIs for customers to view and manage their subscription contracts including status updates, frequency changes, and cancellations. ### Update subscription contract status - [PUT /subscriptions/cp/api/subscription-contracts-update-status](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/updatestatus.md): Updates the status of a subscription contract to ACTIVE, PAUSED, or CANCELLED. This endpoint manages the lifecycle of subscriptions with automatic state tracking and notifications. Status Transitions: - ACTIVE: Resumes a paused subscription, enabling future billing and deliveries - PAUSED: Temporarily suspends all billing and deliveries until manually resumed - CANCELLED: Permanently terminates the subscription (irreversible) Key Features: - Validates status transitions (prevents same-status updates) - Tracks status change timestamps for audit trails - Sends automated email notifications to customers - Creates detailed activity logs for each status change - Handles concurrent modifications with automatic retry - Adjusts next billing date when resuming subscriptions Permission Requirements (Customer Portal): When called from customer portal context: - PAUSED status requires 'pauseResumeSub' permission - ACTIVE status (resuming) requires 'resumeSub' permission - CANCELLED status requires 'cancelSub' permission - External API calls bypass these permission checks Status Change Side Effects: - Activating: Recalculates next billing date, marks activation timestamp - Pausing: Stops all scheduled orders, marks pause timestamp - Cancelling: Terminates subscription permanently, marks cancellation timestamp Error Recovery: The system automatically handles: - Invalid discount codes by removing them and retrying - Concurrent modifications by retrying the operation - This ensures reliable status updates in production environments Important Notes: - Status values are case-insensitive - Cancelled subscriptions cannot be reactivated - Paused subscriptions retain all settings and can be resumed - Email notifications are sent automatically unless internally suppressed Authentication: Requires valid X-API-Key header ### Update subscription delivery address and method - [PUT /subscriptions/cp/api/subscription-contracts-update-shipping-address](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/updateshippingaddress.md): Updates the shipping address or delivery method for a subscription contract. Supports standard shipping, local delivery, and pickup options with comprehensive address validation. Delivery Method Types: - SHIPPING: Standard shipping to customer address (default) - LOCAL: Local delivery within specified zip codes - PICK_UP: Customer pickup at designated location Key Features: - Zip code restrictions for customer portal access - Optional ShipperHQ address validation - Automatic phone number handling for local delivery - Email notifications to customers - Shipping price recalculation - Activity log tracking with old/new addresses Zip Code Validation (Customer Portal Only): When called from customer portal: - Standard shipping: Validates against 'allowToSpecificZipCode' setting - Local delivery: Validates against 'allowToSpecificZipCodeForLocalDelivery' setting - External API calls bypass zip code restrictions Address Validation: - If ShipperHQ is configured, addresses are validated for deliverability - Invalid addresses will return appropriate error messages - Helps prevent failed deliveries and shipping issues Special Handling: - Local delivery addresses missing phone numbers are auto-populated - Uses customer's phone if available, otherwise defaults to placeholder - Handles missing address components gracefully Post-Update Actions: - Sends 'SHIPPING_ADDRESS_UPDATED' email to customer - Creates activity log with address change details - Triggers asynchronous shipping price recalculation - May remove invalid discount codes automatically Important Notes: - Province codes should use ISO 3166-2 format (e.g., 'NY' for New York) - Country codes should use ISO 3166-1 alpha-2 format (e.g., 'US') - Phone numbers should include country code for international addresses - Pickup locations must be pre-configured in Shopify Authentication: Requires valid X-API-Key header ### Update custom attributes on a subscription contract - [POST /subscriptions/cp/api/update-custom-note-attributes](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/updateordernoteattributes.md): Updates or replaces custom key-value attributes on a subscription contract. These attributes are stored with the subscription and can be used to track custom data, preferences, or metadata that's important for your business processes. Custom Attributes Overview: Custom attributes are key-value pairs that allow you to store additional information on subscriptions. They are: - Visible in the Shopify admin and accessible via API - Included in order data when subscription orders are created - Preserved across subscription lifecycle events - Useful for integrations and custom workflows Update Modes: - Merge Mode (overwriteExistingAttributes=false): Adds new attributes and updates existing ones with matching keys. Other attributes remain unchanged. - Replace Mode (overwriteExistingAttributes=true): Completely replaces all existing attributes with the provided list. Common Use Cases: - Store gift messages or special instructions - Track referral sources or marketing campaigns - Add internal reference numbers or tracking codes - Store customer preferences or customization options - Integration data for third-party systems Important Notes: - Attribute keys should not conflict with Shopify's reserved attributes - Both keys and values are stored as strings - Changes are logged in the activity history - Invalid discount codes may be automatically removed during update Authentication: Requires valid X-API-Key header ### Split or duplicate an existing subscription contract - [POST /subscriptions/cp/api/subscription-contract-details/split-existing-contract](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/splitexistingcontract.md): Creates a new subscription contract by either splitting (moving) or duplicating selected line items from an existing contract. This endpoint allows you to divide a subscription into multiple contracts or create a copy with specific products. Split vs Duplicate Mode: - Split (isSplitContract=true): Moves the selected line items from the original contract to a new contract. The original contract will no longer contain these items. - Duplicate (isSplitContract=false): Creates a new contract with copies of the selected line items while keeping them in the original contract. Important Notes: - When splitting, at least one subscription product must remain in the original contract - The new contract inherits all settings from the original: customer, payment method, billing/delivery policies, shipping address, and custom attributes - Billing schedule is automatically generated for the new contract - One-time products and free products don't count towards the minimum product requirement Use Cases: - Split a subscription when customer wants different delivery schedules for different products - Create a gift subscription from an existing subscription - Separate products for different shipping addresses - Duplicate a subscription for testing or backup purposes Authentication: Requires valid X-API-Key header ### Replace product variants in a subscription contract - [POST /subscriptions/cp/api/subscription-contract-details/replace-variants-v3](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/replacevariantsv3.md): Replaces existing product variants with new ones in a subscription contract. This endpoint supports both regular subscription products and one-time products, allowing you to swap products, update quantities, and manage the product mix in a subscription. Key Features: - Bulk Replace: Replace multiple products at once by providing lists of old and new variants - Line-Specific Replace: Target a specific line item using oldLineId for precise replacement - Quantity Management: Set new quantities for replaced products - One-Time Products: Add or remove one-time purchase products independently - Discount Preservation: Configurable discount carry-forward logic Discount Carry Forward Options: - PRODUCT_THEN_EXISTING: First tries to apply the new product's selling plan discount, then falls back to existing discount - PRODUCT_PLAN: Always uses the new product's selling plan discount - EXISTING_PLAN: Maintains the existing product's discount structure Important Notes: - At least one regular subscription product must remain in the contract - One-time products and free products don't count towards the minimum product requirement - The system automatically handles pricing adjustments based on billing/delivery intervals - Shipping prices are automatically recalculated after changes Use Cases: - Product upgrades/downgrades (e.g., switching coffee blend or size) - Quantity adjustments during product swap - Adding limited-time or seasonal products as one-time purchases - Bulk product replacements for subscription migrations Authentication: Requires valid X-API-Key header ### Get variant contextual pricing - [GET /subscriptions/cp/api/data/variant-contextual-pricing](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/getvariantcontextualpricing.md): Retrieves contextual pricing information for a product variant based on currency and country. This endpoint provides localized pricing data for international subscriptions and multi-currency support. Pricing Information Returned: - Base price in specified currency - Compare-at price (if applicable) - Country-specific pricing adjustments - Tax information for the region - Currency conversion data Parameters: - variantId - Shopify variant ID (required) - currencyCode - ISO 4217 currency code (e.g., USD, EUR, GBP) (required) - countryCode - ISO 3166-1 country code (e.g., US, GB, CA) (optional) Use Cases: - Display localized pricing in customer portal - Calculate subscription totals for international customers - Support multi-currency subscriptions - Show accurate pricing based on customer location - Validate pricing before subscription creation Important Notes: - Requires Shopify Markets or multi-currency setup - Prices are returned in the requested currency - Country-specific pricing takes precedence over currency-only pricing - Returns 404 if variant doesn't exist or isn't available in specified market Authentication: Requires valid api_key parameter ### Get selling plans for products - [GET /subscriptions/cp/api/data/products-selling-plans](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/getproductsellingplandata.md): Retrieves all selling plans (subscription plans) associated with a set of products. This endpoint is useful for determining which subscription options are available for specific products. Selling Plan Information: - Selling plan ID and name - Billing and delivery frequencies - Pricing policies (discounts) - Plan description and options - Product associations Use Cases: - Display subscription options on product pages - Validate subscription plan availability - Build subscription plan selector UI - Sync plan data across systems Request: - Accepts multiple product IDs as comma-separated values - Returns aggregated selling plans from all products Authentication: Requires valid api_key parameter ### Get products data with pagination - [GET /subscriptions/cp/api/data/products](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/getproductsdata_1.md): Retrieves paginated product catalog data from Shopify, optionally filtered by search term, selling plans, or subscription contracts. This endpoint provides access to your store's product catalog with subscription-specific information. What This Endpoint Returns: Product information including: - Product ID, title, handle, and description - Product images and media - Variants with pricing and availability - Associated selling plans (subscription plans) - Product status and tags - Vendor and product type Pagination: Uses cursor-based pagination for efficient data retrieval: - next=true - Get next page of results - cursor - Pagination cursor from previous response - Returns cursor for next page in response Filtering Options: 1. Search (search parameter): - Search by product title, description, or SKU - Partial matching supported - Case-insensitive 2. Selling Plan Filter (sellingPlanIds parameter): - Filter products by subscription plans - Comma-separated list of selling plan IDs - Only returns products with specified plans 3. Contract Filter (contractId parameter): - Get products available for specific subscription - Useful for product swap functionality - Returns products compatible with contract Use Cases: - Display product catalog in custom subscription UI - Build product selection for subscription creation - Implement product swap functionality - Search products for subscription management - Sync product data to external systems Authentication: Requires valid api_key parameter ### Get single product data by ID - [GET /subscriptions/cp/api/data/product](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/getproductdata.md): Retrieves detailed information for a specific product by its Shopify product ID. Returns complete product details including all variants, images, and selling plan associations. Product Information Returned: - Basic Details: Title, description, handle, status - Variants: All product variants with pricing - Images: Product images and variant-specific images - Selling Plans: Associated subscription plans - Metadata: Tags, vendor, product type - Options: Color, size, and other variant options Use Cases: - Display product details in subscription management UI - Validate product availability for subscriptions - Get pricing information for subscription creation - Fetch product data for order processing Authentication: Requires valid api_key parameter ### Get delivery options for subscription contract - [GET /subscriptions/cp/api/data/contract-delivery-options](https://developers.subscription.appstle.com/customer-portal-swagger/subscription-management/getcontractdeliveryoptions.md): Retrieves all valid delivery methods available for a specific subscription contract. Returns shipping profiles and delivery options based on the contract's delivery address and product characteristics. Delivery Information Returned: - Available shipping profiles - Delivery methods for each profile - Shipping rates and costs - Delivery speed (standard, express, etc.) - Method names and descriptions - Eligibility based on address and products Filtering Behavior: By default, returns only delivery methods valid for the contract: - Matches delivery address country/region - Compatible with subscription products - Available for contract weight/dimensions Include All Methods: Use header X-Include-All-Methods: true to return all delivery methods regardless of eligibility. Useful for admin UIs where you want to show all options. Use Cases: - Display delivery method selector in customer portal - Allow customers to change shipping method - Calculate shipping costs for subscription - Validate delivery method during subscription updates - Show upgrade options (standard to express) Common Scenarios: Customer Portal - Change Delivery Speed: 1. Call this endpoint with contractId 2. Display available methods to customer 3. Customer selects preferred method 4. Update subscription with new delivery method ID Subscription Creation - Delivery Selection: 1. Get delivery options for draft contract 2. Present options during checkout/signup 3. Create subscription with selected method Important Notes: - Delivery options depend on current contract address - Changing address may change available methods - Costs may vary based on products in subscription - Some methods may have minimum order requirements - International shipping may have additional restrictions Authentication: Requires X-API-Key header ## Billing & Payments APIs for managing payment methods, billing information, and processing subscription payments. ### Update billing interval for a subscription contract - [PUT /subscriptions/cp/api/subscription-contracts-update-billing-interval](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/updatebillinginterval.md): Updates the billing frequency (how often the customer is charged) for a subscription contract. This comprehensive operation recalculates billing dates, adjusts pricing, updates selling plans, and may also modify delivery intervals. Key Features: - Changes billing frequency while maintaining subscription continuity - Automatically adjusts delivery interval when linked to billing - Recalculates next billing date based on store settings - Reprices all line items for the new frequency - Finds and applies matching selling plans - Handles anchor day adjustments for consistent billing - Validates prepaid subscription constraints Billing Interval Types: - DAY: Daily billing (use with caution) - WEEK: Weekly billing (e.g., every 1, 2, 3 weeks) - MONTH: Monthly billing (e.g., every 1, 2, 3 months) - YEAR: Annual billing Validation Rules: - Cannot set the same interval as current (no-op prevention) - For prepaid subscriptions: billing interval must exceed delivery interval - Example: Can't bill monthly if delivering weekly (would be paying for 1 delivery but receiving 4) Next Billing Date Calculation: The system uses sophisticated logic to determine the new billing date: 1. Starts from current or last successful billing date 2. Applies store timezone and order time preferences 3. Ensures date is in the future 4. Respects day-of-week preferences if configured 5. May keep current date if 'enableChangeFromNextBillingDate' is false Side Effects: - Delivery Interval: Updated if currently equal to billing interval - Line Item Pricing: Recalculated based on new frequency multiplier - Selling Plans: Finds and applies best matching plans for products - Anchor Days: Updates billing anchor for consistent scheduling - Email Notifications: Sends 'ORDER_FREQUENCY_UPDATED' to customer - Activity Logs: Records both billing and delivery changes Prepaid vs Pay-Per-Delivery: - Pay-per-delivery: Billing and delivery intervals typically match - Prepaid: Customer pays upfront for multiple deliveries - This endpoint enforces prepaid logic to prevent undercharging Authentication: Requires valid X-API-Key header ### Update next billing date for a subscription contract - [PUT /subscriptions/cp/api/subscription-contracts-update-billing-date](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/updatenextbillingdate.md): Reschedules the next billing date for an active subscription contract. This endpoint allows you to change when the next order will be created and processed. Key Features: - Updates the next billing date to the specified date - Optionally reschedules all future orders based on the new date - Syncs the updated date to Shopify - Sends confirmation email to customer The rescheduleFutureOrder Parameter: - true (default): Updates the next billing date AND recalculates all future queued orders based on the new date. Use this to shift the entire billing schedule. - false: Only updates the next billing date. Other queued orders remain unchanged. Use this for one-time date adjustments. Important Notes: - The new date must be in the future (with 10 minute grace period) - Date is validated against the shop's timezone - If anchor days are configured, future orders may align to those anchors Process Flow: 1. Validates the contract exists and belongs to the shop 2. Validates the new date is not in the past 3. Updates the billing attempt to the new date 4. Syncs the updated nextBillingDate to Shopify 5. If rescheduleFutureOrder=true, regenerates the queue from the new date 6. Sends confirmation email to customer 7. Records activity log entry Date Format: - Must be ISO 8601 format with timezone - Examples: 2024-03-15T12:00:00Z, 2024-03-15T12:00:00+05:30 - URL encode the date when passing as query parameter Timezone Handling: - The provided date is used as-is for the billing attempt - Validation (past date check) uses the shop's configured timezone - All dates in the response are in UTC (Z suffix) Date Restrictions (Customer Portal Only): When called from customer portal context: - Minimum days from today (skipDaysFromCurrentDate setting) - Maximum days from today (billingDateRestrictToDays setting) - External API calls bypass these restrictions Authentication: Requires valid X-API-Key header ### Unskip a previously skipped order - [PUT /subscriptions/cp/api/subscription-billing-attempts/unskip-order/{id}](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/unskiporder.md): Reverses a skip action on a billing attempt. The order will be restored to QUEUED status and will be processed on its scheduled date. Important Notes: - Only works on billing attempts with SKIPPED status - Must be done before the scheduled billing date - Cannot unskip after the billing date has passed - Activity logs are created for audit trail Use Cases: - Customer changes their mind about skipping - Correct accidental skip actions - Restore delivery after resolving temporary issue Authentication: Requires valid X-API-Key header ### Skip the next upcoming order for a subscription - [PUT /subscriptions/cp/api/subscription-billing-attempts/skip-upcoming-order](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/skipfirstupcomingorder.md): Skips the next scheduled billing attempt for a subscription contract without requiring the billing attempt ID. Automatically finds and skips the earliest QUEUED billing attempt. Convenience Feature: - No need to know the specific billing attempt ID - Automatically finds the next order - Ideal for "skip next order" functionality in customer portals Use Cases: - Simple "skip next delivery" button in customer portal - Quick skip without looking up billing attempt details - One-click skip functionality Authentication: Requires valid X-API-Key header ### Skip a specific order - [PUT /subscriptions/cp/api/subscription-billing-attempts/skip-order/{id}](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/skiporder.md): Skips a specific billing attempt by ID. The order will not be processed on its scheduled date. This is useful when customers want to skip a particular delivery without canceling their subscription. Important Behaviors: - Only QUEUED billing attempts can be skipped - Skipped orders remain in the system with SKIPPED status - Future orders are not affected - Can be unskipped before the scheduled date if needed - Activity logs are created for audit trail Use Cases: - Customer is on vacation - Customer has excess inventory - Temporary delivery pause for one cycle Authentication: Requires valid X-API-Key header ### Reschedule a billing attempt to a new date - [PUT /subscriptions/cp/api/subscription-billing-attempts/reschedule-order/{id}](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/rescheduleorder.md): Changes the scheduled billing date for a billing attempt. This allows customers to adjust when their next order will be processed. Rescheduling Options: - Move to earlier date (if allowed by shop settings) - Move to later date - Optionally reschedule all future orders by the same offset Important Behaviors: - Only QUEUED billing attempts can be rescheduled - New date must be in the future - Can affect future billing schedule if rescheduleFutureOrder is true - Activity logs are created for audit trail Use Cases: - Customer wants to delay next delivery - Customer wants to receive order earlier - Adjust delivery schedule to align with customer needs - Coordinate deliveries with customer vacation/travel Authentication: Requires valid X-API-Key header ### Trigger immediate billing for an order - [PUT /subscriptions/cp/api/subscription-billing-attempts/attempt-billing/{id}](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/attemptbilling.md): Immediately processes a billing attempt, creating an order in Shopify. This bypasses the scheduled billing date and processes the order right away. Important Notes: - Requires shop permission 'enableImmediatePlaceOrder' - Only QUEUED billing attempts can be processed - Creates an actual order in Shopify - Charges the customer's payment method immediately - Cannot be undone once processed Use Cases: - Customer requests early delivery - Process order immediately after resolving payment issue - Manual order processing for special cases Authentication: Requires valid X-API-Key header and shop permission ### Update subscription billing attempt - [PUT /subscriptions/cp/api/subscription-billing-attempts](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/updatesubscriptionbillingattempt.md): Updates an existing subscription billing attempt. This endpoint allows modification of billing attempt details such as billing date, order note, and other attributes. Important Notes: - Only QUEUED billing attempts can be updated - Cannot update attempts that are already processed or failed - Billing attempt must belong to the authenticated shop Authentication: Requires valid X-API-Key header ### Get upcoming orders (top orders) - [GET /subscriptions/cp/api/subscription-billing-attempts/top-orders](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/gettopordersforcp.md): Retrieves upcoming (queued) billing attempts for a subscription contract or customer. Returns the next scheduled orders that have not yet been processed. Query Options: - Filter by contract ID to see upcoming orders for a specific subscription - Filter by customer ID to see all upcoming orders for a customer - Results are ordered by billing date (earliest first) Use Cases: - Display "Your Next Order" in customer portal - Show upcoming delivery schedule - Calculate upcoming charges - Preview next order contents Authentication: Requires valid X-API-Key header ### Get past orders - [GET /subscriptions/cp/api/subscription-billing-attempts/past-orders](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/getpastordersforcp.md): Retrieves paginated list of past (processed) billing attempts for a subscription contract or customer. Includes successful orders, failed attempts, and skipped orders. Filter Options: - By contract ID: Get order history for specific subscription - By customer ID: Get all orders across all customer subscriptions - Pagination: Control page size and page number Order Information: - Billing attempt status (SUCCESS, FAILED, SKIPPED) - Shopify order ID for successful attempts - Billing date and processing date - Order total and line items - Error messages for failed attempts Authentication: Requires valid X-API-Key header ### Get past orders report with detailed filtering - [GET /subscriptions/cp/api/subscription-billing-attempts/past-orders/report](https://developers.subscription.appstle.com/customer-portal-swagger/billing-and-payments/getpastordersreportforcp.md): Retrieves a detailed report of past billing attempts with advanced filtering options. This endpoint provides comprehensive data for analytics, troubleshooting, and reporting purposes. Filter Options: - By status: SUCCESS, FAILED, SKIPPED - By date range: Filter by billing date range - By attempt count: Filter by number of retry attempts - By contract status: Filter by subscription contract status - By contract ID: Get report for specific subscription Response Includes: - Detailed billing attempt information - Shopify exception details for failed attempts (optional) - Retry attempt count - Processing timestamps - Order totals and line items Authentication: Requires valid X-API-Key header ## Product Catalog APIs for retrieving product information, selling plans, variant data, and subscription-enabled products available to customers. ### Get product swap variant groups for a contract - [POST /subscriptions/cp/api/product-swaps-by-variant-groups/{contractId}](https://developers.subscription.appstle.com/customer-portal-swagger/product-catalog/getproductswapsbyvariantid.md): Retrieves product swap variant groups for the next 10 billing cycles of a specific subscription contract. This endpoint calculates and returns which products will be swapped to in future billing cycles based on configured swap automations. Response Structure: Returns a 2D array (List>): - Outer array: Represents the next 10 billing cycles - Inner arrays: Contains the variant(s) that will be swapped to for that specific cycle - Index 0: Variants for the next (upcoming) billing cycle - Index 1: Variants for the cycle after that - And so on for the next 10 cycles Variant Details: Each variant object includes: - variantId: Shopify variant ID - quantity: Number of units to swap - title: Variant title (e.g., "Medium Roast - 12oz") - image: Product/variant image URL - productTitle: Full product name - productId: Shopify product GID - variantTitle: Full display name combining product and variant titles - swapId: ID of the swap automation rule that triggered this swap How It Works: 1. Takes the current products in the subscription 2. Applies configured swap automations for the next 10 cycles 3. Calculates which products will be swapped based on: - Billing cycle number - Swap rule configurations (forBillingCycle, checkForEveryRecurringOrder) - Rule sequence/priority 4. Returns the projected product lineup for each cycle Use Cases: - Preview upcoming product swaps in customer portals - Show customers their subscription product timeline - Build interactive swap calendars - Display "what you'll receive" for future orders - Debug and verify swap automation configurations Important Notes: - Returns 10 cycles even if no swaps are configured (returns current products) - Multiple variants in an inner array means multiple products will be in that order - Empty inner arrays indicate no products for that cycle (rare edge case) - The swapId can be used to trace which automation rule triggered the swap Authentication: Requires valid X-API-Key header