Purchasing a Number, Assigning a Webhook, and Assigning it to a Campaign
Updated
---title: Purchasing a Number, Assigning a Webhook, and Assigning it to a Campaignslug: /guides/how-to-purchase-a-number-assign-a-webhook-and-assign-it-to-a-campaignsidebar_position: 6x-custom: ported_from_readme: true needs_review: true---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 Campaignpythonfrom signalwire.rest import Client as signalwire_clientimport requestsfrom requests.auth import HTTPBasicAuthimport pandas as pdSpaceURL = example.signalwire.comProjectID = AuthToken = WebhookPath = https://example.com/message_handlerCampaignSID = 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 webhookresponse = 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 campaignresponse = 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 campaignresponse = 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 datenumberAssociations = 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](pathname:///rest/search-for-available-phone-numbers-to-purchase)! - 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: textPhone 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!pythonfrom signalwire.rest import Client as signalwire_clientimport requestsfrom requests.auth import HTTPBasicAuthimport pandas as pd# define variables SpaceURL = example.signalwire.comProjectID = AuthToken = WebhookPath = https://example.com/message_handlerCampaignSID = # number should be in E164 format - no dashes, no spaces, country code includednumberToPurchase = +1206xxxxxxx Next, we will authenticate the SignalWire client and format the phone number to include the + if it doesnt already. pythonclient = signalwire_client(ProjectID, AuthToken, signalwire_space_url=SpaceURL)formattedNumber = + + numberToPurchase if + not in numberToPurchase else numberToPurchase### Purchase NumberWe will purchase the number we want to buy using the [Purchase Numbers API](pathname:///rest/purchase-a-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](pathname:///rest/update-a-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 Numberpython# assign webhookresponse = 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 CampaignHere we will use the [Create Phone Number Assignment Order API](pathname:///rest/create-a-phone-number-assignment-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!pythonresponse = 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 CampaignWe 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](pathname:///rest/retrieve-a-campaign) and store the campaign reference ID in a variable.python# retrieve campaignresponse = 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 CSVHere 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 datenumberAssociations = 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!