Purchasing a Number, Assigning a Webhook, and Assigning it to a Campaign
Updated
- product:messaging - language: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? -- Full code example: Purchase a Number, Assign Webhook, and Assign to Campaign python from signalwire.rest import Client as signalwire_client import requests from requests.auth import HTTPBasicAuth import pandas as pd SpaceURL = example.signalwire.com ProjectID = AuthToken = WebhookPath = https://example.com/message_handler CampaignSID = numberToPurchase = +1206xxxxxxx client = signalwire_client(ProjectID, AuthToken, signalwire_space_url=SpaceURL) formattedNumber = + + numberToPurchase if + not in numberToPurchase else numberToPurchase # buy phone numbers response = requests.post(fhttps://{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] # assign webhook response = requests.put(fhttps://{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 campaign response = requests.post(fhttps://{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 response = requests.get(fhttps://{SpaceURL}/api/relay/rest/registry/beta/campaigns/{CampaignSID}, headers = {Accept: application/json}, auth=HTTPBasicAuth(ProjectID, AuthToken)) campaignRef = response.json()[csp_campaign_reference] # read in 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) - You will need your API credentials to authenticate the requests. You can [find your API credentials](/guides/navigating-your-space#api) 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](/rest/signalwire-rest/endpoints/space/search-available-phone-numbers)! - 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: text 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! python 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 doesnt already. python 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](/rest/signalwire-rest/endpoints/space/purchase-phone-number) 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. python # buy phone numbers response = requests.post(fhttps://{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](/rest/signalwire-rest/endpoints/space/update-phone-number) to assign a webhook that will handle any inbound message requests. If you dont want the number to handle inbound messages, you can comment this part out! ### Assign Webhook to Number python # assign webhook response = requests.put(fhttps://{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](/rest/signalwire-rest/endpoints/space/create-order) 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 its not connected. Watch for a status of complete to confirm youre good to begin messaging! python response = requests.post(fhttps://{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 thats a little more legible) as well to store in our records. To do this, we will use the [Retrieve Campaign API](/rest/signalwire-rest/endpoints/space/retrieve-brand) and store the campaign reference ID in a variable. python # retrieve campaign response = requests.get(fhttps://{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!** python # 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 youre 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](https://m.signalwire.com/signups/new?s=1). Please feel free to reach out to us on our [Community Slack](https://signalwire.community/) or create a Support ticket if you need guidance!