📌 Purchasing a Number, Assigning a Webhook, and Assigning it to a Campaign - Python

Overview

Once you purchase a phone number, you still will need to assign a webhook to handle inbound messages and assign it to a campaign before it can be used for messaging. This script will combine all of those tasks into one and let you knock them all out at the same time!

What do I need to run this code?

To quickly run this code, check out our recipe below and replace the variables with your own!

  • You will need your API credentials to authenticate the requests. You can find your API credentials in the API tab of your SignalWire Space!

  • You will need the number you want to purchase - easily search for available numbers using the Available Number Search API!

  • You will also need the webhook that you would like to assign to the number for handling inbound messages!

  • You will need a CSV in the folder of the script that has headers matching the parameters you are going to track, something like this:

Phone Number,Campaign ID,Campaign SID,Assigned Webhook,Purchase Date
  • Lastly, you will need the Campaign SID in order to assign the number to the campaign. You can find your campaign SID by going to the Messaging Campaigns section of your SignalWire space and clicking the specific campaign whose numbers you need. The SID is the long alphanumeric string at the top as shown here:

How to Run Application

The first step as always will be to import the required libraries and define our variables to be reused throughout the code. We will need our SpaceURL, ProjectID, AuthToken, WebhookPath, CampaignSID, and numberToPurchase. Make sure the number does not have any dashes, parenthesis, or spaces!

from signalwire.rest import Client as signalwire_client
import requests
from requests.auth import HTTPBasicAuth
import pandas as pd

# define variables 
SpaceURL = 'example.signalwire.com'
ProjectID = ""
AuthToken = ''
WebhookPath = 'https://example.com/message_handler'
CampaignSID = ''
# number should be in E164 format - no dashes, no spaces, country code included
numberToPurchase = '+1206xxxxxxx' 

Next, we will authenticate the SignalWire client and format the phone number to include the + if it doesn't already.

client = signalwire_client(ProjectID, AuthToken, signalwire_space_url=SpaceURL)

formattedNumber = "+" + numberToPurchase if "+" not in numberToPurchase else numberToPurchase

Purchase Number

We will purchase the number we want to buy using the Purchase Numbers API and then print the response in case there are any errors we need to correct (unavailable number, invalid format, etc). We will store the SID of the phone number and the purchase date of the phone number in variables to use later.

# buy phone numbers 
response = requests.post(f"https://{SpaceURL}/api/relay/rest/phone_numbers",
                         headers = { "Accept": "application/json",
                             "Content-Type": "application/json"},
                         json = {"number": formattedNumber},
                         auth=HTTPBasicAuth(ProjectID, AuthToken))
print(response.text)
sid = response.json()['id']
purchaseDate = response.json()['created_at']

Here we will use the Update Number API to assign a webhook that will handle any inbound message requests. If you don't want the number to handle inbound messages, you can comment this part out!

Assign Webhook to Number

# assign webhook
response = requests.put(f"https://{SpaceURL}/api/relay/rest/phone_numbers/{sid}",
                               params={'call_handler': 'laml_webhooks',
                                        'message_request_url': WebhookPath,
                                        'name': 'Number Name'},
                         auth=HTTPBasicAuth(ProjectID, AuthToken))
print(response.text)

Assign Phone Number to Campaign

Here we will use the Create Phone Number Assignment Order API to assign the newly purchased phone number to our campaign. Always make sure to wait at least 24 hours after adding a number to a new campaign - the connections take some time to complete upstream and you will not be able to send with these numbers if it's not connected. Watch for a status of 'complete' to confirm you're good to begin messaging!

response = requests.post(f"https://{SpaceURL}/api/relay/rest/registry/beta/campaigns/{CampaignSID}/orders",
                         json = {"phone_numbers": [formattedNumber]},
                         headers = {
                            "Accept": "application/json",
                               "Content-Type": "application/json"},
                         auth=HTTPBasicAuth(ProjectID, AuthToken))
print(response.text)

Retrieve Campaign

We already have the campaign SID, but we want the Campaign ID (the short one that's a little more legible) as well to store in our records. To do this, we will use the Retrieve Campaign API and store the campaign reference ID in a variable.

# retrieve campaign
response = requests.get(f"https://{SpaceURL}/api/relay/rest/registry/beta/campaigns/{CampaignSID}",
                         headers = {"Accept": "application/json"},
                         auth=HTTPBasicAuth(ProjectID, AuthToken))
campaignRef = response.json()['csp_campaign_reference']

Write new row to CSV

Here we will use pandas to read in the existing CSV and add a row containing the new number, campaign ID, campaign SID, webhook, and purchase date. We will then save it back to CSV to reflect the changes.
If you commented out the webhook part above, make sure to remove it from the items being appended to the CSV!

# read in existing csv and append new row with number, campaign, webhook, purchase date
numberAssociations = pd.read_csv('NumberAssociations.csv')
numberAssociations.loc[len(numberAssociations.index)] = [formattedNumber, campaignRef, CampaignSID, WebhookPath, purchaseDate]
numberAssociations.to_csv('NumberAssociations.csv', index=None)

When you're done, the CSV will look like this and you will have a newly purchased number that is assigned to a campaign!

Sign Up Here

If you would like to test this example out, you can create a SignalWire account and space here.

Please feel free to reach out to us on our Community Slack or create a Support ticket if you need guidance!


Did this page help you?