Reputation: 535
I am using a single twilio number to trigger an sms being sent through a django function.
If a person accesses my app through my website then the app will parse sendphonenum
from a post request from the website.
If a person accesses my app by sending sms to twilio number, it will parse sendphonenum
from text message.
The problem occurs after Twilio has sent a message to sendphonenum
.
If a message was triggered from the website it should redirect to dashboard page for user who sent message. But don't do this if message was triggered through an initial sms.
@csrf_exempt
def sms_response(request):
if request.method == "POST":
# parse sendphonenum from text message sent from mobile phone to twilio number +14545552222
# or parse sendphonenum from a post request from website
message_body = request.POST['Body']
sendnum_ary = re.findall('[0-9]+', message_body)
sendnum = "".join(sendnum_ary)
sendphonenum = "+1" + sendnum
mytwilionum = "+14545552222"
# put your own credentials here
ACCOUNT_SID = "123434234234"
AUTH_TOKEN = "abcsdasda"
client = Client(ACCOUNT_SID, AUTH_TOKEN)
client.messages.create(
to= sendphonenum,
from_= mytwilionum,
body='someone told me to message you'
)
## there is no platform variable, just doing some mock code to show you what I'd want to happen
## note sms_response function url must be same for both website and mobile phone, as both are using same webhook A MESSAGE COMES IN for +14545552222
if platform == 'web':
return HttpResponseRedirect(reverse('dashboard'))
return HttpResponse('')
Upvotes: 0
Views: 96
Reputation: 73057
Twilio developer evangelist here.
Twilio will send a bunch of headers along with the request which you could check for. For example, all requests are signed and include an X-Twilio-Signature
header. So you can check the request.META
dictionary for the existence of that header. To be extra sure it was a request from Twilio, you can verify that the signature is correct.
if ‘HTTP_X_TWILIO_SIGNATURE’ in request.META:
# An XML response with an empty `<Response/>` element
resp = MessagingResponse()
return HttpResponse(str(resp))
else:
return HttpResponseRedirect(reverse('dashboard'))
Let me know if that helps at all.
Upvotes: 1