Campaign Management
Targeting
Targeting is a core concept of the Ads API. Targeting is set at the line item level and options vary across placements. To set new targeting criteria you need to use POST accounts/:account_id/targeting_criteria and PUT accounts/:account_id/targeting_criteria to update them.
Use GET accounts/:account_id/line_items for a list of all line items and GET accounts/:account_id/line_items/:line_item_id to retrieve a specific line item.
Targeting options by placement
Promoted Tweets and Promoted Accounts products can be made available on a variety of placements. Promoted Trends (PTr) are not available via the API.
For possible placement combinations, refer to the GET line_items/placements endpoint. Each placement has different options for targeting. Location, Platform and Gender are available for all. The other options are contextual to the type of placement.
- Twitter Search: Age Targeting, Devices, Events, Gender, Keyword Types (All), Language, Locations, Network Activation, Network Operators, Platform, Platform Version, Tailored Audiences, WiFi Only
- Twitter Timeline: Age Targeting, Devices, Events, Followers Of, Similar to Followers Of, Gender, Interest, Language, Locations, Network Activation, Network Operators, Non-exact Keyword Types, Partner Audience Types, Platform, Platform Version, Retargeting Types, Tailored Audiences, TV Targeting Types, WiFi Only
- Twitter Profiles & Tweet Details: Age Targeting, Devices, Events, Followers Of, Similar to Followers Of, Gender, Interest, Language, Locations, Network Activation, Network Operators, Non-exact Keyword Types, Partner Audience Types, Platform, Platform Version, Retargeting Types, Tailored Audiences, TV Targeting Types, WiFi Only
Understanding targeting types
Age Targeting: Target users based on specific age buckets. A list of age bucket enums can be found on the Enumerations page.
Behaviors: use this targeting type to target pre-made audiences from select partners. See GET targeting_criteria/behaviors.
Events: Specify an event for targeting. Only one event can be used for targeting (per line item). Use the GET targeting_criteria/events endpoint to find events available for targeting.
Gender: Target males (1) or females (2). Leave null to target all.
Installed App Store Categories: use this targeting type to target users based on the categories of apps they have installed or have indicated interest in. See GET targeting_criteria/app_store_categories.
Interests: Target users by interest. Get the interests list from GET targeting_criteria/interests. You can target up to 100 interests.
Followers Of: Target the followers of any fully promotable users for the current account (note, currently the primary account holder is the only fully-promotable user of that account). GET accounts/:account_id/promotable_users to get a list of promotable users.
Similar to Followers Of: Target people with the same interests as followers of specific users. You can use up to 100 Users.
Locations: Specify up to 250 locations to target. Get list from GET targeting_criteria/locations. There are additional requirements for ads that target certain countries. See Country Targeting and Display Requirements for more information.
Keywords: Keyword targeting options are specific by type of placement. You can use up to 1000 keywords for targeting (per line item). See the Keyword Types section for options.
Language Targeting: Target users who understand specific languages.
Mobile Network Operator Targeting: Enables advertisers to target users based on mobile carrier, using the targeting type NETWORK_OPERATOR from GET targeting_criteria/network_operators.
New Mobile Device Targeting: Reach users based on the date that they first accessed Twitter via their device, using the targeting types NETWORK_ACTIVATION_DURATION_LT and NETWORK_ACTIVATION_DURATION_GTE.
Platforms, Platform Versions, Devices, and Wifi-Only: Allows targeting of mobile devices across a variety of vectors. Platforms is a high-level targeting type that can hit broad categories of phone. Example values are iOS and Android. Devices allow you to target users of specific mobile devices, for example the iPhone 5s, Nexus 4, or Samsung Galaxy Note. Platform versions allow you to target users of versions of specific mobile operating systems, down to the point release. Examples include iOS 7.1 and Android 4.4. Wifi-Only allows you to target only those users who are using their devices on a WiFi network; if this is not set, users using the carrier connection as well as WiFi will be targeted.
- Users can target platforms and devices if there is no overlap. I can target Blackberry as a platform and iPad Air as a device simultaneously.
- Users can target devices and os versions simultaneously. I can target iPad Air and iOS >= 7.0.
- Users cannot target platforms that are broader than devices. I cannot target iOS and iPad Air.
Tailored Audiences: Reach users through an approved ads partner to target groups of customers and connect with them on Twitter.
TV Targeting
TV Show Targeting: reach people that engage with specific TV programs. This targeting criteria can be configured to continuously target while a campaign is active with the TV_SHOW targeting type. Use the GET targeting_criteria/tv_markets and GET targeting_criteria/tv_shows endpoints to determine TV shows available.
Tweet Engager Retargeting
Tweet engager retargeting enables advertisers to target audiences across devices who have previously been exposed to or engaged with their promoted or organic Tweets on Twitter. With this targeting advertisers can follow up with people who saw or engaged with an advertiser’s content on Twitter and are most likely to further engage or convert with subsequent messaging or offers. Users will be eligible for targeting within minutes of exposure or engagement and will remain eligible for up to 90 days afterwards for engagements and 30 days for exposures.
Tweet Engager Targeting Types:
ENGAGEMENT_TYPEwhich accepts eitherIMPRESSIONorENGAGEMENTas a targeting value. This specifies whether you wish to target exposed users (IMPRESSION) or engaged users (ENGAGEMENT).CAMPAIGN_ENGAGEMENTuses a campaign ID as the targeting value. Users who engaged with or were exposed to this campaign (depending onENGAGEMENT_TYPE) are the ones who will be targeted.USER_ENGAGEMENTwhich uses the promoted user ID as the targeting value to target users who were exposed to or engaged with an advertiser’s organic content (depending onENGAGEMENT_TYPE). This must be the promoted user ID associated with the Ads account.
Note: ENGAGEMENT_TYPE is required in addition to at least one valid CAMPAIGN_ENGAGEMENT or USER_ENGAGEMENT value. Both tweet engager targeting types may be present and multiple campaigns may be targeted on a given line item.
Video Viewer Targeting: Video viewer targeting builds on Tweet engager targeting to enable advertisers to target audiences who have previously watched part or all of a video on Twitter. Advertisers can target organic videos, promoted videos, or both. Promoted videos are not limited to video view objective campaigns or line items.
Video Viewer Targeting Types:
VIDEO_VIEWfor users who have clicked to play the video or have viewed 3 seconds of autoplayVIDEO_VIEW_PARTIALfor users who have viewed 50% of the videoVIDEO_VIEW_COMPLETEfor users who have viewed at least 95% of the video
As with Tweet engager targeting, one or both of the following must also be present in targeting criteria for the line item when ENGAGEMENT_TYPE is used:
CAMPAIGN_ENGAGEMENTuses a campaign ID as the targeting value. Users who watched a video (based onENGAGEMENT_TYPE) in this campaign are the ones who will be targeted.USER_ENGAGEMENTwhich uses the promoted user ID as the targeting value to target users who watched a video (based onENGAGEMENT_TYPE) in an advertiser’s organic content. This must be the promoted user ID associated with the Ads account.
Keyword Types
See our support document on keyword targeting for a conceptual overview.
- Broad (default value): match all words, independent of order. Not sensitive to capitalization, plurals or tense. Will automatically be expanded when possible (i.e. “car repair” would also match “automobile fix”). If you want to target without expansion, you need to add a + sign before the keywords, like “+boat +jet”. Using keywords without the + will default to Broad Match.
- Unordered (deprecated): match all words, independent of order. Not sensitive to capitalization, plurals or tense.
- Phrase: match the exact keywords string, other keywords can be present.
- Exact: match exactly the keywords string, not any others.
- Negative: avoid matching searches that include all of these keywords somewhere in the query, regardless of the order in which they are written, even if other words are present.
- Negative Phrase: avoid matching searches that include this exact keywords string somewhere in the query, even if other words are present.
- Negative Exact: avoid matching searches that exactly match these keywords and contain no other words.
Emoji targeting
Emoji targeting is supported via keyword targeting. To use emoji targeting, simply create keyword targeting for Unicode codepoints representing that emoji such as U+1F602 (xF0x9Fx98x82 in UTF-8) for the ‘face with tears of joy’ emoji (😂). Emoji which we accept can be confirmed with the twemoji list. Targeting an emoji targets all variations.
For a summary of all values with required/optional and specific details for each, see PUT accounts/:account_id/targeting_criteria.
Targeting Criteria Combinations
Updated Campaign Workflow
Create campaigns which target broadly with geo, gender, language, and device/platform criteria. Advertisers can then combine the broad targeting with additional targeting criteria (e.g. interests, keywords, followers, tailored audiences, TV). If no targeting criteria is specified for a line item, the line item will target all users worldwide.
| “Primary” Types | Other Types |
|---|---|
| Followers | Locations |
| Tailored Audiences | Gender |
| Interests | Languages |
| Keywords | Devices and platforms |
| TV | Age |
Targeting criteria will be combined for your ad group such that:
- “Primary” Targeting Types will get ∪‘d (i.e. put in a logical union).
- Other Targeting Types will get AND‘d.
- Same types will get OR‘d.
Some examples
At a glance: [(Followers) ∪ (Tailored Audiences) ∪ (Interests) ∪ (Keywords)] AND (Location) AND (Gender) AND (Languages) AND (Devices and Platforms)
A Geo example:
Let’s say we want an ad group for our campaign to serve targeting:
- Twitter users in the U.S., England, and Canada (Location)
- who are Women (Gender)
- derived from Tailored Audiences list (“Primary”)
- with Keywords (“Primary”)
The targeting criteria will be:
[US OR GB OR CA] AND [Female] AND [Tailored Audiences ∪ Keyword]
Additional examples
- Select Gender and Geo but no primary: (Male) AND (US OR GB)
- Select Gender, Geo, Interest: (Female) AND (CA) AND (Computers OR Technology OR Startups)
- Select Gender, Geo, Interest, Tailored Audiences, Keywords: (Male) AND (GB) AND (Cars ∪ Tailored Audiences for CRM ∪ autocross)
Securing webhooks
Twitter's webhook-based APIs provide two methods for confirming the security of your webhook server:
- The challenge-response checks enable Twitter to confirm the ownership of the web app receiving webhook events.
- The signature header in each POST request enables you to confirm that Twitter is the source of the incoming webhooks.
Challenge-Response Checks
In order to verify that you are both the owner of the app and the webhook URL, Twitter will perform a Challenge-Response Check (CRC), which is not to be confused with a cyclic redundancy check. When a CRC is sent, Twitter will make a GET request of your web app with a ;crc_token parameter. When that request is received, your web app needs to build an encrypted response_token based on the crc_token parameter and your app's Consumer Secret (details below). The response_token must be encoded in JSON (see example below) and returned within three seconds. When successful, a webhook id will be returned.
A CRC will be sent when you register your webhook URL, so implementing your CRC response code is a fundamental first step. Once your webhook is established, Twitter will trigger a CRC on an hourly basis. Your app can also trigger a CRC when needed by making a PUT request with your webhook id. Triggering a CRC is useful as you develop your webhook application, after deploying new code and restarting your service.
The crc_token should be expected to change for each incoming CRC request and should be used as the message in the calculation, where your Consumer Secret is the key.
In the event that the response is not posted within 3 seconds or becomes invalid, events will cease to be sent to the registered webhook.
The CRC request will occur:
- When a webhook URL is registered.
- Approximately hourly to validate your webhook URL.
- You can manually trigger a CRC by making a PUT request. As you develop your webhook client, you should plan on manually triggering the CRC as you develop your CRC response.
Response requirements:
- A base64 encoded HMAC SHA-256 hash created from the
crc_tokenand your app Consumer Secret - Valid response_token and JSON format.
- Latency less than 3 seconds.
- 200 HTTP response code.
Language-specific HMAC libraries:
Example response token generation in Python:
The following defines a route in a Python 2.7 Flask webapp that will respond to the challenge response check correctly.
import base64
import hashlib
import hmac
import json
# Defines a route for the GET request
@app.route('/webhooks/twitter', methods=['GET'])
def webhook_challenge():
# creates HMAC SHA-256 hash from incomming token and your consumer secret
sha256_hash_digest = hmac.new(TWITTER_CONSUMER_SECRET, msg=request.args.get('crc_token'), digestmod=hashlib.sha256).digest()
# construct response data with base64 encoded hash
response = {
'response_token': 'sha256=' + base64.b64encode(sha256_hash_digest)
}
# returns properly formatted json response
return json.dumps(response)
Example JSON response:
With the route defined as above your webapp should return a response similar to below when navigating to https://your-app-domain/webhooks/twitter?crc_token=foo in your web browser.
{
"response_token": "sha256=x0mYd8hz2goCTfcNAaMqENy2BFgJJfJOb4PdvTffpwg="
}
Other examples:
- HERE is an example CRC response method written in Node/JS.
- HERE is an example CRC response method written in Ruby (see the generate_crc_response and the /GET route that receives CRC events).
Optional signature header validation
With each incoming POST request from Twitter, a hash signature will be passed in the headers as x-twitter-webhooks-signature. This signature can be used to validate the source of the data is Twitter. The hash signature starts with sha256=indicating the use of HMAC SHA-256 to encrypt your Twitter app Consumer Secret and payload.
Steps to validate a request
- Create a hash using your consumer secret and incoming payload body.
- Compare created hash with the base64 encoded x-twitter-webhooks-signature value. Use a method like compare_digest to reduce the vulnerability to timing attacks.
Additional security guidelines
The following are additional security guidelines to consider for your web application. Not having these guidelines implemented will not prevent your webhook from functioning, but are highly reccomended by the Twitter Information Security team. If you are unfamilair with the below recommendations consult with your server administrator.
Twitter aggregate network blocks
For added security you may wish to whitelist the following aggregate network blocks:
- 199.59.148.0/22
- 199.16.156.0/22
Recommended server configurations
- A- rating on ssllabs.com test.
- Enable TLS 1.2
- Enable Forward Secrecy
- Disable SSLv2
- Disable SSLv3 (because of POODLE)
- Disable TLS 1.0
- Disable TLS Compression
- Disable Session Tickets unless you rotate session ticket keys.
- Set the “ssl_prefer_server_ciphers” or “SSLHonorCipherOrder” option in the SSL Configuration “on”.
- Ensure the list of ciphers is a modern list such as:
ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA
Next steps
- Once you have secured your webhook app, the next step is adding user subscriptions.
- Learn more about these topics:
- See Account Activity API references.
- See example code:
- Premium Account Activity API dashboard, a node web app that displays webhook events.
- The SnowBot chatbot, a Ruby web app built with the Account Activity and Direct Message APIs. This code base includes a script to help set up Account Activity API webhooks.