Guides and Examples
...
Orders
Generate Magic Links
17 min
this guide provides comprehensive instructions for generating magic links from draft orders using the nue lifecycle management api learn how to create shareable pdf quote links with standard or custom branding, manage link security, and implement efficient quote generation workflows prerequisites before you begin, ensure you have a valid nue api key with order management permissions draft order ids for which you want to generate magic links template ids for custom branding (optional, configured in your nue account) understanding of draft order lifecycle and quote generation basic knowledge of rest apis and json familiarity with pdf quote sharing workflows authentication all magic link generation 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 magic link generation generate standard magic link try it now generate draft order magic link ā https //api docs nue io/generate draft order magic link const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); // generate standard magic link for a draft order const draftorderid = "123e4567 e89b 12d3 a456 426614174000"; fetch(`https //api nue io/orders/magiclink/order/${draftorderid}`, { method 'get', headers myheaders }) then(response => response json()) then(result => { console log('magic link generated successfully ', result); if (result magiclink) { console log('\nā
standard magic link generated'); console log(`order id ${draftorderid}`); console log(`magic link ${result magiclink}`); // the magic link can be shared with customers console log('\nš§ ready to share with customer for quote review'); console log('š” customer can view and download pdf quote without login'); // example of how to use the link sharewithcustomer(result magiclink, null, draftorderid); } }) catch(error => console log('error ', error)); function sharewithcustomer(magiclink, templateid, orderid) { // customer communication const emailtemplate = { to 'customer\@example com', subject templateid ? 'your branded quote is ready' 'your quote is ready for review', body ` dear customer, your ${templateid ? 'professionally branded ' ''}quote is ready for review please click the link below to view and download your pdf quote ${magiclink} this secure link allows you to ⢠view your complete quote details ⢠download a pdf copy for your records ⢠share with your team for approval ${templateid ? 'our branded presentation reflects the quality and professionalism you can expect from our partnership ' ''} the quote is valid for 30 days if you have any questions, please contact us best regards, sales team ` }; console log('\nš§ email template prepared ', emailtemplate); } generate branded magic link with custom template try it now generate draft order magic link with custom template ā https //api docs nue io/generate draft order magic link with custom template // generate branded magic link with custom template const draftorderid = "123e4567 e89b 12d3 a456 426614174000"; const templateid = "f47ac10b 58cc 4372 a567 0e02b2c3d479"; fetch(`https //api nue io/orders/magiclink/order/${draftorderid}/template/${templateid}`, { method 'get', headers myheaders }) then(response => response json()) then(result => { console log('branded magic link generated successfully ', result); if (result magiclink) { console log('\nā
branded magic link generated'); console log(`order id ${draftorderid}`); console log(`template id ${templateid}`); console log(`magic link ${result magiclink}`); // the branded magic link includes custom styling and branding console log('\nšØ branded quote includes '); console log('⢠custom company logo and colors'); console log('⢠branded headers and footers'); console log('⢠custom styling and layout'); console log('⢠professional branded appearance'); sharewithcustomer(result magiclink, templateid, draftorderid); } }) catch(error => console log('error ', error)); generate links for different customer segments create magic links using different templates based on customer segments async function generatesegmentedmagiclink(draftorderid, customersegment) { const myheaders = new headers(); myheaders append("nue api key", "your api key here"); myheaders append("content type", "application/json"); // template mapping based on customer segment const templatemapping = { 'enterprise' 'f47ac10b 58cc 4372 a567 0e02b2c3d479', 'midmarket' '6ba7b810 9dad 11d1 80b4 00c04fd430c8', 'smb' '6ba7b811 9dad 11d1 80b4 00c04fd430c8', 'partner' '6ba7b812 9dad 11d1 80b4 00c04fd430c8', 'trial' '6ba7b813 9dad 11d1 80b4 00c04fd430c8' }; const templateid = templatemapping\[customersegment]; try { console log(`šØ generating ${customersegment} quote for order ${draftorderid} `); // choose endpoint based on whether template is specified const endpoint = templateid ? `https //api nue io/orders/magiclink/order/${draftorderid}/template/${templateid}` `https //api nue io/orders/magiclink/order/${draftorderid}`; const response = await fetch(endpoint, { method 'get', headers myheaders }); if (response ok) { const result = await response json(); return { success true, orderid draftorderid, segment customersegment, templateid templateid || 'standard', magiclink result magiclink, brandingfeatures getbrandingfeatures(customersegment) }; } else { throw new error(`http ${response status} ${response statustext}`); } } catch (error) { return { success false, orderid draftorderid, segment customersegment, error error message }; } } function getbrandingfeatures(segment) { const features = { 'enterprise' \[ 'premium executive level design', 'custom enterprise logo placement', 'executive summary section', 'advanced security notices', 'white glove service indicators' ], 'midmarket' \[ 'professional business design', 'company branding integration', 'scalability messaging', 'roi highlighting', 'growth focused content' ], 'smb' \[ 'clean, accessible design', 'value focused messaging', 'easy to understand pricing', 'small business testimonials', 'quick start guidance' ], 'partner' \[ 'co branded design elements', 'partner program benefits', 'channel specific pricing', 'partner support information', 'joint value proposition' ], 'trial' \[ 'evaluation focused design', 'trial to paid messaging', 'feature comparison charts', 'implementation timeline', 'trial extension options' ] }; return features\[segment] || \['standard design']; } // usage examples for different customer segments const ordersegmentexamples = \[ { orderid "order enterprise 001", segment "enterprise" }, { orderid "order midmarket 002", segment "midmarket" }, { orderid "order smb 003", segment "smb" }, { orderid "order partner 004", segment "partner" }, { orderid "order trial 005", segment "trial" } ]; // generate links for all segments promise all( ordersegmentexamples map(example => generatesegmentedmagiclink(example orderid, example segment) ) ) then(results => { console log('\nšØ segment specific magic links generated '); results foreach(result => { if (result success) { console log(`\nā
${result segment touppercase()} template `); console log(` order ${result orderid}`); console log(` template ${result templateid}`); console log(` link ${result magiclink}`); console log(` features `); result brandingfeatures foreach(feature => { console log(` ⢠${feature}`); }); } else { console log(`\nā ${result segment} ${result error}`); } }); }); advanced magic link management comprehensive magic link service implement a service that handles both standard and branded magic link generation class magiclinkservice { constructor(apikey) { this apikey = apikey; this headers = new headers(); this headers append("nue api key", apikey); this headers append("content type", "application/json"); // template configuration (in production, load from api or config) this templateconfig = this initializetemplateconfig(); this linktracking = new map(); } initializetemplateconfig() { return { 'f47ac10b 58cc 4372 a567 0e02b2c3d479' { name 'enterprise premium', description 'high end branded template for enterprise customers', features \['custom executive design', 'premium branding', 'security badges'], usecase 'large enterprise deals > $100k', approvalrequired true }, '6ba7b810 9dad 11d1 80b4 00c04fd430c8' { name 'professional standard', description 'clean professional template for mid market', features \['professional layout', 'company branding', 'roi focus'], usecase 'mid market customers $10k $100k', approvalrequired false }, '6ba7b812 9dad 11d1 80b4 00c04fd430c8' { name 'partner co branded', description 'joint branding template for channel partners', features \['co branded headers', 'partner benefits', 'channel pricing'], usecase 'channel partner opportunities', approvalrequired false }, '6ba7b813 9dad 11d1 80b4 00c04fd430c8' { name 'trial conversion', description 'conversion focused template for trial users', features \['trial benefits', 'upgrade messaging', 'feature highlights'], usecase 'trial to paid conversions', approvalrequired false } }; } async generatemagiclink(draftorderid, options = {}) { try { // step 1 determine if template should be used const templateid = options templateid || this selectoptimaltemplate(options); // step 2 validate template if specified if (templateid) { const templateinfo = this validatetemplate(templateid); // check approval requirements if (templateinfo approvalrequired && !options approved) { return await this handleapprovalrequired(draftorderid, templateid, options); } } // step 3 validate order for magic link generation if (options validateorder) { await this validatedraftorder(draftorderid); } // step 4 generate the magic link (standard or branded) const linkresult = await this requestmagiclink(draftorderid, templateid); // step 5 track link generation this tracklinkgeneration(draftorderid, templateid, linkresult, options); // step 6 prepare communication const communication = this preparecommunication( linkresult, templateid ? this templateconfig\[templateid] null, options ); return { success true, orderid draftorderid, templateid templateid || 'standard', templatename templateid ? this templateconfig\[templateid]? name 'standard', magiclink linkresult magiclink, branding templateid ? this templateconfig\[templateid] null, communication communication, generatedat new date() toisostring() }; } catch (error) { console error(`magic link generation failed `, error); return { success false, orderid draftorderid, templateid options templateid, error error message }; } } selectoptimaltemplate(options) { // auto select template based on business rules const { dealvalue, customersegment, ordertype } = options; if (dealvalue >= 100000) return 'f47ac10b 58cc 4372 a567 0e02b2c3d479'; // enterprise premium if (customersegment === 'partner') return '6ba7b812 9dad 11d1 80b4 00c04fd430c8'; // partner cobranded if (ordertype === 'trial conversion') return '6ba7b813 9dad 11d1 80b4 00c04fd430c8'; // trial conversion if (dealvalue >= 10000) return '6ba7b810 9dad 11d1 80b4 00c04fd430c8'; // professional standard // return null for standard template return null; } validatetemplate(templateid) { const template = this templateconfig\[templateid]; if (!template) { throw new error(`template '${templateid}' not found available templates ${object keys(this templateconfig) join(', ')}`); } return template; } async handleapprovalrequired(draftorderid, templateid, options) { console log(`ā ļø template '${templateid}' requires approval for order ${draftorderid}`); const approvalrequest = { orderid draftorderid, templateid templateid, requestedby options requestedby || 'api user', reason options approvalreason || 'high value template usage', submittedat new date() toisostring() }; return { success false, requiresapproval true, approvalrequest approvalrequest, message `template '${templateid}' requires management approval` }; } async validatedraftorder(draftorderid) { console log(`validating draft order ${draftorderid} `); // in production, validate order exists and is in draft status return true; } async requestmagiclink(draftorderid, templateid) { // choose endpoint based on whether template is specified const endpoint = templateid ? `https //api nue io/orders/magiclink/order/${draftorderid}/template/${templateid}` `https //api nue io/orders/magiclink/order/${draftorderid}`; const response = await fetch(endpoint, { method 'get', headers this headers }); if (!response ok) { let errormessage = `magic link generation failed ${response status}`; if (response status === 400) { errormessage += templateid ? ' invalid template id or order configuration' ' invalid order configuration'; } else if (response status === 404) { errormessage += ' order not found or template not found'; } throw new error(errormessage); } const result = await response json(); if (!result magiclink) { throw new error('magic link not returned in response'); } return result; } tracklinkgeneration(orderid, templateid, linkresult, options) { const tracking = { orderid, templateid templateid || 'standard', templatename templateid ? this templateconfig\[templateid]? name 'standard', magiclink linkresult magiclink, generatedat new date() toisostring(), generatedby options requestedby || 'api', customersegment options customersegment, dealvalue options dealvalue, purpose options purpose || 'quote generation' }; this linktracking set(`${orderid} ${templateid || 'standard'}`, tracking); console log(`š magic link tracked ${orderid} using ${templateid || 'standard'}`); } preparecommunication(linkresult, templateinfo, options) { const customername = options customername || 'valued customer'; const iscustomtemplate = !!templateinfo; const subject = options subject || (iscustomtemplate ? `your ${templateinfo name} quote is ready` 'your quote is ready for review'); let message; if (iscustomtemplate) { const featureslist = templateinfo features map(feature => `ā ${feature}`) join('\n '); message = options custommessage || ` dear ${customername}, your professionally branded quote has been prepared using our ${templateinfo name} template, designed specifically for ${templateinfo usecase tolowercase()} view your branded quote ${linkresult magiclink} this premium quote includes ${featureslist} our branded presentation reflects the quality and professionalism you can expect throughout our partnership the quote design has been tailored to showcase the value and benefits specific to your business needs the quote is valid for 30 days and includes all the detailed information needed for your review and approval process we look forward to discussing how we can support your objectives best regards, your dedicated account team `; } else { message = options custommessage || ` dear ${customername}, your quote is ready for review please click the secure link below to view and download your pdf quote ${linkresult magiclink} this link allows you to ā view complete quote details ā download pdf for your records ā share with your team for approval the quote is valid for 30 days if you have any questions or need assistance, please don't hesitate to contact us best regards, sales team `; } return { to options customeremail, subject subject, message message, templateused templateinfo? name || 'standard', branding templateinfo }; } async generatemultiplemagiclinks(orders, globaloptions = {}) { console log(`š generating magic links for ${orders length} orders `); const results = \[]; const batchsize = globaloptions batchsize || 5; for (let i = 0; i < orders length; i += batchsize) { const batch = orders slice(i, i + batchsize); const batchpromises = batch map(order => this generatemagiclink(order orderid, { globaloptions, order options }) ); const batchresults = await promise allsettled(batchpromises); results push( batchresults); // brief pause between batches if (i + batchsize < orders length) { await new promise(resolve => settimeout(resolve, 500)); } } // analyze results const successful = results filter(r => r status === 'fulfilled' && r value success); const failed = results filter(r => r status === 'rejected' || !r value success); console log(`\nš magic link generation results `); console log(`ā
successful ${successful length}`); console log(`ā failed ${failed length}`); if (successful length > 0) { console log('\nā
generated magic links '); successful foreach(result => { const data = result value; console log(`order ${data orderid} (${data templatename}) ${data magiclink}`); }); } if (failed length > 0) { console log('\nā failed generations '); failed foreach((result, index) => { const error = result status === 'rejected' ? result reason message result value error; console log(`order ${orders\[index]? orderid || 'unknown'} ${error}`); }); } return { total orders length, successful successful length, failed failed length, links successful map(r => r value), errors failed }; } getavailabletemplates() { return object entries(this templateconfig) map((\[id, config]) => ({ id, name config name, description config description, features config features, usecase config usecase, approvalrequired config approvalrequired })); } getlinkanalytics() { const history = array from(this linktracking values()); const analytics = { totalgenerated history length, templateusage {}, customersegments {}, averagedealvalue 0, toptemplates \[] }; let totaldealvalue = 0; let dealcount = 0; history foreach(record => { // template usage analytics templateusage\[record templateid] = (analytics templateusage\[record templateid] || 0) + 1; // customer segments if (record customersegment) { analytics customersegments\[record customersegment] = (analytics customersegments\[record customersegment] || 0) + 1; } // deal values if (record dealvalue) { totaldealvalue += record dealvalue; dealcount++; } }); analytics averagedealvalue = dealcount > 0 ? totaldealvalue / dealcount 0; analytics toptemplates = object entries(analytics templateusage) sort((\[,a], \[,b]) => b a) map((\[templateid, count]) => ({ templateid, templatename this templateconfig\[templateid]? name || templateid, usagecount count })); return analytics; } displayanalytics() { const analytics = this getlinkanalytics(); console log('\nš magic link analytics'); console log('=' repeat(40)); console log(`total generated ${analytics totalgenerated}`); console log(`average deal value $${analytics averagedealvalue tolocalestring()}`); console log('\nšØ template usage '); analytics toptemplates foreach(template => { console log(` ${template templatename} ${template usagecount} uses`); }); if (object keys(analytics customersegments) length > 0) { console log('\nš„ customer segments '); object entries(analytics customersegments) foreach((\[segment, count]) => { console log(` ${segment} ${count} quotes`); }); } } } // usage examples const magiclinkservice = new magiclinkservice("your api key here"); // display available templates console log('\nšØ available templates '); magiclinkservice getavailabletemplates() foreach(template => { console log(`\n${template name} (${template id})`); console log(` ${template description}`); console log(` use case ${template usecase}`); console log(` features ${template features join(', ')}`); console log(` approval required ${template approvalrequired ? 'yes' 'no'}`); }); // generate standard magic link const standardlink = await magiclinkservice generatemagiclink( "123e4567 e89b 12d3 a456 426614174000", { customername "standard customer", customeremail "customer\@example com", validateorder true } ); // generate branded magic link for enterprise customer const enterpriselink = await magiclinkservice generatemagiclink( "456e7890 e89b 12d3 a456 426614174001", { templateid "f47ac10b 58cc 4372 a567 0e02b2c3d479", // enterprise premium customername "enterprise corp", customeremail "buyer\@enterprise com", customersegment "enterprise", dealvalue 250000, requestedby "account manager" } ); // generate links with auto template selection const autotemplatelink = await magiclinkservice generatemagiclink( "789e1234 e89b 12d3 a456 426614174002", { customername "mid market inc", customeremail "buyer\@midmarket com", customersegment "midmarket", dealvalue 75000, // will auto select professional standard template validateorder true } ); // bulk generation with mixed templates const bulkorders = \[ { orderid "bulk order 001", options { templateid "f47ac10b 58cc 4372 a567 0e02b2c3d479", // enterprise premium customername "enterprise customer", customeremail "enterprise\@example com" } }, { orderid "bulk order 002", options { customername "standard customer", customeremail "standard\@example com" } }, { orderid "bulk order 003", options { templateid "6ba7b812 9dad 11d1 80b4 00c04fd430c8", // partner cobranded customername "partner company", customeremail "partner\@example com" } } ]; const bulkresults = await magiclinkservice generatemultiplemagiclinks(bulkorders); console log(`bulk generation completed ${bulkresults successful}/${bulkresults total} links created`); // display analytics magiclinkservice displayanalytics(); response structure success response (200 ok) standard magic link { "magiclink" "https //quotes nue io/order/123e4567 e89b 12d3 a456 426614174000" } branded magic link with template { "magiclink" "https //quotes nue io/order/123e4567 e89b 12d3 a456 426614174000/template/custom branded template" } error handling common magic link errors error code description resolution order not found draft order doesn't exist verify order id is correct invalid order status order not in draft status ensure order is in draft state invalid template id template id is invalid or not accessible verify template id and permissions template not found specified template does not exist check available templates template approval required template requires approval for use submit for approval or use different template robust error handling async function safemagiclinkgeneration(draftorderid, templateid = null) { try { const endpoint = templateid ? `https //api nue io/orders/magiclink/order/${draftorderid}/template/${templateid}` `https //api nue io/orders/magiclink/order/${draftorderid}`; const response = await fetch(endpoint, { method 'get', headers myheaders }); if (!response ok) { const errortext = await response text(); if (response status === 400 && templateid) { throw new error(`template '${templateid}' is invalid or not accessible`); } else if (response status === 404) { throw new error(`order ${draftorderid}${templateid ? ` or template ${templateid}` ''} not found`); } else if (response status === 403 && templateid) { throw new error(`template '${templateid}' requires approval or higher permissions`); } else { throw new error(`generation failed ${response status} ${errortext}`); } } const result = await response json(); if (!result magiclink) { throw new error('magic link not returned in response'); } return { success true, magiclink result magiclink, orderid draftorderid, templateid templateid || 'standard' }; } catch (error) { console error(`magic link generation failed `, error); return { success false, orderid draftorderid, templateid templateid, error error message }; } } best practices template selection use appropriate templates based on customer segment and deal value implement approval workflows for premium templates track template performance and customer engagement regular template updates to maintain brand consistency link management track link generation for analytics and follow up set appropriate expiration times for quotes monitor link usage to gauge customer engagement provide clear instructions to customers about link usage customer experience select templates that match customer expectations personalize communication about template features and branding highlight value proposition in branded presentations provide template options for important deals performance and security generate links efficiently using batch processing validate template permissions before generation monitor template usage for compliance implement fallback to standard for error scenarios this comprehensive guide enables you to efficiently generate both standard and branded magic links using the nue lifecycle management api, supporting everything from simple quote sharing to sophisticated branded customer experiences with intelligent template selection