Request offers from Twilio Studio¶
A Twilio Studio flow can send Offer Manager offers over SMS. A Twilio Function calls the Fetch API and returns the offer's text, and the flow sends it with a Send Message widget. This document describes how to create the function and add it to a flow. For the request in general, see Request an offer.
Before you begin¶
- Create a moment, such as
after-check-in, and a rule with at least one offer for it. - Get an API key from API Keys in the Advertising.chat console's account menu, and the ID of the agent your moments belong to.
- You need a Twilio account with a Studio flow that handles incoming SMS.
Create the function¶
- In the Twilio Console, open Functions and Assets, and create a
service, such as
adchat. -
Add a function with the path
/offer-fetch, and replace its code with the following:const axios = require('axios'); const crypto = require('crypto'); exports.handler = async function (context, event, callback) { try { const response = await axios.post( 'https://ads.advertising.chat/v1/fetch/v2', {}, { params: { key: context.ADCHAT_API_KEY, application: context.ADCHAT_APPLICATION, adUnit: event.moment, format: 'sms', subscriber: crypto.createHash('sha256').update(event.from || '').digest('hex'), }, validateStatus: status => status === 200 || status === 204, } ); if (response.status !== 200) return callback(null, { text: '' }); return callback(null, { text: response.data.payload.text, messageId: response.data.messageId, }); } catch (err) { return callback(null, { text: '' }); } }; -
In the service's environment variables, add
ADCHAT_API_KEYwith your API key as the value, andADCHAT_APPLICATIONwith the agent's ID. - In the service's dependencies, add
axios. - Deploy the service.
The function hashes the sender's phone number, so Advertising.chat receives
an opaque subscriber identifier for frequency caps instead of the number
itself. On any error, the function returns empty text, so the flow
continues without an offer.
Add the function to a flow¶
- In Studio, open the flow, and drag a Run Function widget onto the canvas at the point where an offer could fit.
- In the widget's settings, select your service, its environment, and the
/offer-fetchfunction. - Add two function parameters:
momentwith the moment's code, such asafter-check-in, andfromwith the value{{trigger.message.From}}. - Connect the widget's success transition to a Split Based On...
widget that tests whether
{{widgets.YOUR_WIDGET_NAME.parsed.text}}is empty. - On the not-empty branch, add a Send Message widget whose body is
{{widgets.YOUR_WIDGET_NAME.parsed.text}}. - Publish the flow.
The SMS text is the offer's Alt Text followed by a click-tracking link, so taps are recorded automatically.
What's next¶
- Review performance for the moment.
- Read the
smsformat and the others in Render formats. - Report deliveries and conversions with the returned
messageId, as described in Report what happens.