Guides and Examples
...
Subscriptions
Updating Subscriptions
19 min
this guide provides comprehensive instructions for updating subscription data using the nue lifecycle management api learn how to modify subscription settings, manage auto renewal configurations, update custom fields, and implement efficient subscription management workflows prerequisites before you begin, ensure you have a valid nue api key with subscription update permissions subscription ids for the subscriptions you want to update understanding of subscription data model and updateable fields basic knowledge of rest apis and json familiarity with subscription lifecycle and business rules authentication all subscription update operations require authentication using your nue api key in the nue api key header const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); basic subscription updates update auto renewal setting try it now update subscription ā https //api docs nue io/update subscription const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); // update subscription auto renewal setting const subscriptionid = "subscription 123e4567 e89b 12d3 a456 426614174000"; const updatedata = { autorenew false // disable auto renewal }; fetch(`https //api nue io/subscriptions/${subscriptionid}`, { method 'patch', headers myheaders, body json stringify(updatedata) }) then(response => response json()) then(result => { console log('subscription updated successfully ', result); if (result status === 'success' && result data length > 0) { const subscription = result data\[0]; console log('\nā
subscription update completed'); console log(`subscription id ${subscription id}`); console log(`name ${subscription name}`); console log(`auto renew ${subscription autorenew}`); console log(`status ${subscription status}`); console log(`last modified ${subscription lastmodifieddate}`); console log(`modified by ${subscription lastmodifiedbyid}`); // display renewal implications if (!subscription autorenew) { console log('\nā ļø auto renewal disabled manual renewal required'); console log(`subscription expires ${subscription subscriptionenddate}`); } else { console log('\nš auto renewal enabled'); console log(`next renewal ${subscription subscriptionenddate}`); } } }) catch(error => console log('error ', error)); update custom fields update custom fields on subscription records // update custom field data const customfieldupdate = { ruby custom field c "updated custom value", // example custom field autorenew true // can combine with standard field updates }; fetch(`https //api nue io/subscriptions/${subscriptionid}`, { method 'patch', headers myheaders, body json stringify(customfieldupdate) }) then(response => response json()) then(result => { if (result status === 'success') { const subscription = result data\[0]; console log('ā
custom field updated successfully'); console log(`subscription ${subscription name}`); console log(`custom field value ${subscription ruby custom field c}`); console log(`auto renew ${subscription autorenew}`); console log(`last modified ${subscription lastmodifieddate}`); // track the update for audit purposes logsubscriptionupdate(subscription id, customfieldupdate, 'custom field update'); } }) catch(error => console log('custom field update failed ', error)); function logsubscriptionupdate(subscriptionid, updatedata, updatetype) { const auditlog = { subscriptionid, updatetype, updatedfields object keys(updatedata), timestamp new date() toisostring(), updatedata }; console log('š update logged for audit ', auditlog); // in production, send to your audit/logging system } advanced subscription update workflows subscription update service implement a comprehensive service for subscription management with validation and business rules class subscriptionupdateservice { constructor(apikey) { this apikey = apikey; this headers = new headers(); this headers append("nue api key", apikey); this headers append("content type", "application/json"); // track updates for audit and rollback purposes this updatehistory = new map(); } async updatesubscription(subscriptionid, updatedata, options = {}) { try { // step 1 validate update data and business rules if (options validate) { await this validateupdate(subscriptionid, updatedata); } // step 2 get current subscription state for rollback const currentstate = await this getcurrentsubscriptionstate(subscriptionid); // step 3 apply business rules and transformations const processedupdate = this processupdatedata(updatedata, currentstate, options); // step 4 submit the update const result = await this submitupdate(subscriptionid, processedupdate); // step 5 track the update this trackupdate(subscriptionid, processedupdate, result, currentstate); // step 6 handle post update tasks if (options enablenotifications) { await this handlepostupdatetasks(result data\[0], processedupdate); } return { success true, subscriptionid, updatedsubscription result data\[0], appliedchanges processedupdate, previousstate currentstate }; } catch (error) { console error(`subscription update failed for ${subscriptionid} `, error); return { success false, subscriptionid, error error message, updatedata }; } } async validateupdate(subscriptionid, updatedata) { const errors = \[]; // validate updateable fields const allowedfields = \['autorenew']; const customfieldpattern = /^\[a za z0 9 ]+ \[a za z0 9 ]+ c$/; object keys(updatedata) foreach(field => { if (!allowedfields includes(field) && !customfieldpattern test(field)) { errors push(`field '${field}' is not updateable or invalid custom field format`); } }); // validate autorenew field specifically if (updatedata hasownproperty('autorenew') && typeof updatedata autorenew !== 'boolean') { errors push('autorenew must be a boolean value'); } // business rule validations if (updatedata autorenew === false) { // check if subscription is close to expiry const subscription = await this getcurrentsubscriptionstate(subscriptionid); const enddate = new date(subscription subscriptionenddate); const now = new date(); const daystoexpiry = math ceil((enddate now) / (1000 60 60 24)); if (daystoexpiry <= 30) { errors push(`warning disabling auto renewal for subscription expiring in ${daystoexpiry} days`); } } if (errors length > 0) { throw new error(`validation failed \n${errors join('\n')}`); } } async getcurrentsubscriptionstate(subscriptionid) { // in a real implementation, you would fetch the current subscription // for this example, we'll simulate the response console log(`fetching current state for subscription ${subscriptionid} `); // this would be a call to get /subscriptions with a filter // for demo purposes, returning mock data return { id subscriptionid, name "mock subscription", autorenew true, status "active", subscriptionenddate "2025 12 31", totalamount 120000 }; } processupdatedata(updatedata, currentstate, options) { const processed = { updatedata }; // apply business logic transformations if (processed autorenew !== undefined) { // log renewal setting changes if (processed autorenew !== currentstate autorenew) { console log(`š auto renewal changing ${currentstate autorenew} ā ${processed autorenew}`); // add metadata for audit trail if (options updatereason) { processed updatereason = options updatereason; } } } // handle custom field updates object keys(processed) foreach(field => { if (field includes(' c')) { console log(`š·ļø custom field update ${field} = ${processed\[field]}`); } }); return processed; } async submitupdate(subscriptionid, updatedata) { const response = await fetch(`https //api nue io/subscriptions/${subscriptionid}`, { method 'patch', headers this headers, body json stringify(updatedata) }); if (!response ok) { const errortext = await response text(); throw new error(`update failed ${response status} ${errortext}`); } const result = await response json(); if (result status !== 'success') { throw new error(`update failed ${result message || 'unknown error'}`); } return result; } trackupdate(subscriptionid, updatedata, result, previousstate) { const updaterecord = { subscriptionid, timestamp new date() toisostring(), updatedata, previousstate, newstate result data\[0], success true }; this updatehistory set(`${subscriptionid} ${date now()}`, updaterecord); console log(`š update tracked for subscription ${subscriptionid}`); } async handlepostupdatetasks(updatedsubscription, appliedchanges) { // post update notification and business logic // 1 send notifications if auto renewal changed if (appliedchanges hasownproperty('autorenew')) { await this sendautorenewalnotification(updatedsubscription, appliedchanges autorenew); } // 2 update related systems await this updaterelatedsystems(updatedsubscription, appliedchanges); // 3 schedule follow up tasks await this schedulefollowuptasks(updatedsubscription, appliedchanges); } async sendautorenewalnotification(subscription, newautorenewsetting) { console log(`š§ sending auto renewal notification `); const notification = { subscriptionid subscription id, subscriptionname subscription name, customerid subscription customerid, autorenewenabled newautorenewsetting, subscriptionenddate subscription subscriptionenddate, notificationtype 'auto renewal change' }; if (newautorenewsetting) { console log('ā
auto renewal enabled customer will be billed automatically'); } else { console log('ā ļø auto renewal disabled manual renewal required'); // schedule renewal reminder const enddate = new date(subscription subscriptionenddate); const reminderdate = new date(enddate gettime() 30 24 60 60 1000); notification reminderscheduled = reminderdate toisostring(); console log(`š
renewal reminder scheduled for ${reminderdate tolocaledatestring()}`); } // in production, integrate with your notification system console log('š§ notification queued ', notification); } async updaterelatedsystems(subscription, changes) { console log(`š updating related systems for subscription ${subscription id} `); // examples of related system updates // crm system updates // billing system notifications // customer portal updates // analytics/reporting systems const systemupdates = \[]; if (changes autorenew !== undefined) { systemupdates push({ system 'billing', action 'update auto renewal', subscriptionid subscription id, autorenew changes autorenew }); systemupdates push({ system 'crm', action 'update renewal flag', subscriptionid subscription id, autorenew changes autorenew }); } // custom field updates might need to sync to external systems object keys(changes) foreach(field => { if (field includes(' c')) { systemupdates push({ system 'data warehouse', action 'sync custom field', subscriptionid subscription id, field field, value changes\[field] }); } }); console log(`š ${systemupdates length} system updates queued `, systemupdates); } async schedulefollowuptasks(subscription, changes) { console log(`š
scheduling follow up tasks for subscription ${subscription id} `); const tasks = \[]; // if auto renewal was disabled, schedule renewal outreach if (changes autorenew === false) { const enddate = new date(subscription subscriptionenddate); const outreachdate = new date(enddate gettime() 45 24 60 60 1000); tasks push({ type 'renewal outreach', subscriptionid subscription id, scheduleddate outreachdate toisostring(), priority 'high', assignee 'account manager' }); } // if auto renewal was enabled, schedule renewal confirmation if (changes autorenew === true) { const enddate = new date(subscription subscriptionenddate); const confirmationdate = new date(enddate gettime() 7 24 60 60 1000); tasks push({ type 'renewal confirmation', subscriptionid subscription id, scheduleddate confirmationdate toisostring(), priority 'medium', assignee 'customer success' }); } console log(`š ${tasks length} follow up tasks scheduled `, tasks); } async bulkupdatesubscriptions(subscriptionupdates, options = {}) { console log(`š starting bulk update for ${subscriptionupdates length} subscriptions `); const results = { successful \[], failed \[], summary {} }; // process in batches to respect rate limits const batchsize = options batchsize || 5; for (let i = 0; i < subscriptionupdates length; i += batchsize) { const batch = subscriptionupdates slice(i, i + batchsize); console log(`processing batch ${math floor(i/batchsize) + 1}/${math ceil(subscriptionupdates length/batchsize)}`); const batchpromises = batch map(update => this updatesubscription(update subscriptionid, update updatedata, update options || options) ); const batchresults = await promise allsettled(batchpromises); batchresults foreach((result, index) => { const update = batch\[index]; if (result status === 'fulfilled' && result value success) { results successful push(result value); } else { const error = result status === 'rejected' ? result reason message result value error; results failed push({ subscriptionid update subscriptionid, updatedata update updatedata, error }); } }); // brief pause between batches if (i + batchsize < subscriptionupdates length) { await new promise(resolve => settimeout(resolve, 1000)); } } // generate summary results summary = { total subscriptionupdates length, successful results successful length, failed results failed length, successrate ((results successful length / subscriptionupdates length) 100) tofixed(1) }; this displaybulkresults(results); return results; } displaybulkresults(results) { console log('\nš bulk update results'); console log('=' repeat(50)); console log(`total updates ${results summary total}`); console log(`ā
successful ${results summary successful}`); console log(`ā failed ${results summary failed}`); console log(`š success rate ${results summary successrate}%`); if (results successful length > 0) { console log('\nā
successfully updated '); results successful foreach(result => { console log(` ⢠${result updatedsubscription name || result subscriptionid}`); console log(` changes ${object keys(result appliedchanges) join(', ')}`); }); } if (results failed length > 0) { console log('\nā failed updates '); results failed foreach(failure => { console log(` ⢠${failure subscriptionid}`); console log(` error ${failure error}`); }); } } getupdatehistory(subscriptionid) { const history = array from(this updatehistory entries()) filter((\[key, record]) => record subscriptionid === subscriptionid) map((\[key, record]) => record) sort((a, b) => new date(b timestamp) new date(a timestamp)); return history; } displayupdatehistory(subscriptionid) { const history = this getupdatehistory(subscriptionid); console log(`\nš update history for subscription ${subscriptionid}`); console log('=' repeat(60)); if (history length === 0) { console log('no update history found'); return; } history foreach((record, index) => { console log(`\n${index + 1} ${new date(record timestamp) tolocalestring()}`); console log(` updated fields ${object keys(record updatedata) join(', ')}`); object entries(record updatedata) foreach((\[field, newvalue]) => { const oldvalue = record previousstate\[field]; console log(` ${field} ${oldvalue} ā ${newvalue}`); }); }); } } // usage examples const subscriptionservice = new subscriptionupdateservice("your api key here"); // single subscription update with full workflow const singleupdate = await subscriptionservice updatesubscription( "subscription 123e4567 e89b 12d3 a456 426614174000", { autorenew false, ruby update reason c "customer requested manual renewal" }, { validate true, enablenotifications true, updatereason "customer preference change" } ); if (singleupdate success) { console log('ā
subscription updated successfully'); console log(`auto renew ${singleupdate updatedsubscription autorenew}`); } else { console error('ā update failed ', singleupdate error); } // bulk subscription updates const bulkupdates = \[ { subscriptionid "sub 001", updatedata { autorenew true }, options { updatereason "renewal optimization campaign" } }, { subscriptionid "sub 002", updatedata { autorenew false, ruby manual review c "true" }, options { updatereason "high value customer manual oversight" } }, { subscriptionid "sub 003", updatedata { ruby customer segment c "enterprise" } } ]; const bulkresults = await subscriptionservice bulkupdatesubscriptions(bulkupdates, { validate true, enablenotifications true, batchsize 3 }); console log(`bulk update completed ${bulkresults summary successful}/${bulkresults summary total} subscriptions updated`); // display update history subscriptionservice displayupdatehistory("subscription 123e4567 e89b 12d3 a456 426614174000"); specialized update scenarios auto renewal management campaign implement a campaign to optimize auto renewal settings across the subscription portfolio class autorenewalcampaign { constructor(subscriptionservice) { this subscriptionservice = subscriptionservice; } async optimizeautorenewalsettings(customerids, campaignrules) { console log(`šÆ starting auto renewal optimization campaign for ${customerids length} customers `); const results = { analyzed 0, updated 0, skipped 0, errors 0, details \[] }; for (const customerid of customerids) { try { // fetch customer subscriptions const subscriptions = await this fetchcustomersubscriptions(customerid); results analyzed += subscriptions length; // analyze and apply campaign rules for (const subscription of subscriptions) { const recommendation = this analyzesubscriptionforautorenewal(subscription, campaignrules); if (recommendation shouldupdate) { const updateresult = await this subscriptionservice updatesubscription( subscription id, { autorenew recommendation newautorenewsetting }, { validate true, enablenotifications true, updatereason recommendation reason } ); if (updateresult success) { results updated++; results details push({ subscriptionid subscription id, subscriptionname subscription name, action 'updated', oldsetting subscription autorenew, newsetting recommendation newautorenewsetting, reason recommendation reason }); } else { results errors++; results details push({ subscriptionid subscription id, action 'error', error updateresult error }); } } else { results skipped++; results details push({ subscriptionid subscription id, action 'skipped', reason recommendation reason }); } } } catch (error) { console error(`error processing customer ${customerid} `, error); results errors++; } } this displaycampaignresults(results); return results; } async fetchcustomersubscriptions(customerid) { // simplified fetch in production, use the full subscription service const encodedids = encodeuricomponent(json stringify(\[customerid])); const response = await fetch(`https //api nue io/subscriptions?customerids=${encodedids}\&status=active`, { method 'get', headers this subscriptionservice headers }); const result = await response json(); return result data || \[]; } analyzesubscriptionforautorenewal(subscription, campaignrules) { // apply business rules to determine auto renewal optimization // rule 1 high value subscriptions should have auto renewal enabled if (subscription totalacv >= campaignrules highvaluethreshold) { if (!subscription autorenew) { return { shouldupdate true, newautorenewsetting true, reason `high value subscription ($${subscription totalacv}) enabling auto renewal` }; } } // rule 2 low risk customers with good payment history if (campaignrules enableforlowrisk && this islowriskcustomer(subscription)) { if (!subscription autorenew) { return { shouldupdate true, newautorenewsetting true, reason 'low risk customer with good payment history enabling auto renewal' }; } } // rule 3 subscriptions expiring soon without auto renewal const daystoexpiry = this getdaystoexpiry(subscription subscriptionenddate); if (daystoexpiry <= 60 && !subscription autorenew) { return { shouldupdate true, newautorenewsetting true, reason `subscription expiring in ${daystoexpiry} days enabling auto renewal to prevent churn` }; } // rule 4 trial subscriptions should not have auto renewal if (subscription name tolowercase() includes('trial') && subscription autorenew) { return { shouldupdate true, newautorenewsetting false, reason 'trial subscription disabling auto renewal for manual conversion' }; } // no update needed return { shouldupdate false, reason 'current auto renewal setting is optimal' }; } islowriskcustomer(subscription) { // simplified risk assessment in production, integrate with credit/payment systems // for demo, assume customers with long subscription history are low risk const startdate = new date(subscription subscriptionstartdate); const monthsactive = math floor((new date() startdate) / (1000 60 60 24 30)); return monthsactive >= 12; // 12+ months = low risk } getdaystoexpiry(enddatestring) { const enddate = new date(enddatestring); const now = new date(); return math ceil((enddate now) / (1000 60 60 24)); } displaycampaignresults(results) { console log('\nšÆ auto renewal campaign results'); console log('=' repeat(50)); console log(`š subscriptions analyzed ${results analyzed}`); console log(`ā
updated ${results updated}`); console log(`āļø skipped ${results skipped}`); console log(`ā errors ${results errors}`); const updaterate = results analyzed > 0 ? ((results updated / results analyzed) 100) tofixed(1) 0; console log(`š update rate ${updaterate}%`); // group results by action const updated = results details filter(d => d action === 'updated'); const skipped = results details filter(d => d action === 'skipped'); const errors = results details filter(d => d action === 'error'); if (updated length > 0) { console log('\nā
updated subscriptions '); updated foreach(detail => { console log(` ⢠${detail subscriptionname} ${detail oldsetting} ā ${detail newsetting}`); console log(` reason ${detail reason}`); }); } if (errors length > 0) { console log('\nā failed updates '); errors foreach(detail => { console log(` ⢠${detail subscriptionid} ${detail error}`); }); } console log('\nš” campaign impact '); const enabledcount = updated filter(d => d newsetting === true) length; const disabledcount = updated filter(d => d newsetting === false) length; console log(` auto renewal enabled ${enabledcount} subscriptions`); console log(` auto renewal disabled ${disabledcount} subscriptions`); } } // usage example const renewalcampaign = new autorenewalcampaign(subscriptionservice); const campaignrules = { highvaluethreshold 50000, // $50k+ subscriptions enableforlowrisk true, disablefortrials true }; const customerids = \[ "d2e04653 ae90 49df a986 134cf64f6d03", "cc5e1f0f 5e14 48cc ab98 9e5b191aa46f" ]; const campaignresults = await renewalcampaign optimizeautorenewalsettings(customerids, campaignrules); console log(`campaign completed ${campaignresults updated} subscriptions optimized`); request body schema updateable fields field type description example autorenew boolean enable/disable automatic renewal true , false {customfield} c string custom field value (must match field api name) "custom value" custom field naming convention custom fields must follow the pattern {namespace} {fieldname} c examples ruby custom field c organization department c integration external id c response structure success response (200 ok) { "status" "success", "data" \[ { "actualsubscriptionterm" 12, "autorenew" false, "billcycleday" "7th of month", "billcyclestartmonth" "03", "billingaccountid" "81dd1eb9 7a2c 4486 be76 b1ac2f88bbb1", "billingperiod" "annual", "billingtiming" "in advance", "bundled" true, "createdbyid" "74ef82c9 a9d7 4262 8331 ba7ac33d1f76", "createddate" "2025 07 02t23 12 30 582z", "customerid" "81dd1eb9 7a2c 4486 be76 b1ac2f88bbb1", "evergreen" false, "id" "f594fd3a 3659 4039 ae5c b2c6863d98a5", "lastmodifiedbyid" "74ef82c9 a9d7 4262 8331 ba7ac33d1f76", "lastmodifieddate" "2025 07 02t23 12 30 621z", "listprice" 19 9, "name" "sub 00000309", "nextbillingdate" "2025 07 01", "orderondate" "2025 07 02", "orderproductid" "03139976 1cc2 4430 8f61 996e641c8745", "parentid" "3b573778 89c0 491d a972 bd3073d9add4", "parentobjecttype" "subscription", "pricebookentryid" "01u7z000005ynbaaa4", "pricebookid" "01s7z000006dt4raac", "productid" "01t7z00000dxt09aad", "quantity" 2, "renewalterm" 12, "rootid" "3b573778 89c0 491d a972 bd3073d9add4", "salesprice" 19 9, "status" "active", "subscriptioncompositeid" "sub 00000309 1", "subscriptionenddate" "2026 06 30", "subscriptionlevel" 2, "subscriptionstartdate" "2025 07 01", "subscriptionterm" 12, "subscriptionversion" 1, "taxamount" 0, "tcv" 0, "totalacv" 0, "totalamount" 0, "totalprice" 0, "totaltcv" 0, "uomid" "a0s7z00000hyfptaa5" } ], "warnings" \[] } error handling common update errors error description resolution subscription not found subscription id doesn't exist verify subscription id invalid field field not updateable or doesn't exist check allowed fields and custom field names validation error field value validation failed review field constraints and data types permission error insufficient permissions verify api key has update permissions robust update error handling async function safesubscriptionupdate(subscriptionid, updatedata, options = {}) { try { // validate input data if (!subscriptionid) { throw new error('subscription id is required'); } if (!updatedata || object keys(updatedata) length === 0) { throw new error('update data is required'); } const response = await fetch(`https //api nue io/subscriptions/${subscriptionid}`, { method 'patch', headers myheaders, body json stringify(updatedata) }); if (!response ok) { const errortext = await response text(); // handle specific error scenarios if (response status === 404) { throw new error(`subscription ${subscriptionid} not found`); } else if (response status === 400) { throw new error(`invalid update data ${errortext}`); } else if (response status === 403) { throw new error('insufficient permissions to update subscription'); } else { throw new error(`update failed ${response status} ${errortext}`); } } const result = await response json(); if (result status !== 'success') { throw new error(`update failed ${result message || 'unknown error'}`); } return { success true, subscription result data\[0], updatedfields object keys(updatedata) }; } catch (error) { console error(`subscription update failed for ${subscriptionid} `, error); return { success false, subscriptionid, error error message, updatedata }; } } best practices update strategy validate before updating to prevent api errors track update history for audit and rollback purposes implement business rules to ensure updates align with policies use batch processing for bulk updates with rate limiting auto renewal management monitor expiration dates when disabling auto renewal send notifications for auto renewal changes schedule follow up tasks for manual renewals consider customer segments when optimizing auto renewal data integrity backup current state before making updates validate custom field names and formats implement rollback procedures for failed bulk updates log all changes for compliance and audit performance batch updates efficiently to respect rate limits use async processing for large scale updates implement retry logic for transient failures monitor api usage and optimize call patterns this comprehensive guide enables you to efficiently update subscription data using the nue lifecycle management api, supporting everything from simple field updates to complex auto renewal optimization campaigns and bulk subscription management workflows