Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for sending Twilio Template #751

Merged
merged 1 commit into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 101 additions & 22 deletions handlers/twiml/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"github.com/nyaruka/courier/utils"
"github.com/nyaruka/gocommon/httpx"
"github.com/nyaruka/gocommon/i18n"
"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/urns"
)

Expand Down Expand Up @@ -235,36 +236,31 @@
return err
}

parts := handlers.SplitMsgByChannel(msg.Channel(), msg.Text(), maxMsgLength)
for i, part := range parts {
// build our request
// do we have a template and support whatsapp scheme?
if msg.Templating() != nil && channel.IsScheme(urns.WhatsApp) {
if msg.Templating().ExternalID == "" {
return courier.ErrMessageInvalid
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@norkans7 please have a think about places in other handlers where we should use this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

}

form := url.Values{
"To": []string{msg.URN().Path()},
"Body": []string{part},
"To": []string{fmt.Sprintf("%s:+%s", urns.WhatsApp.Prefix, msg.URN().Path())},
"StatusCallback": []string{callbackURL},
"ContentSid": []string{msg.Templating().ExternalID},
"From": []string{fmt.Sprintf("%s:%s", urns.WhatsApp.Prefix, channel.Address())},
}

// add any attachments to the first part
if i == 0 {
for _, a := range attachments {
form.Add("MediaUrl", a.URL)
}
}
contentVariables := make(map[string]string, len(msg.Templating().Variables))

// set our from, either as a messaging service or from our address
serviceSID := channel.StringConfigForKey(configMessagingServiceSID, "")
if serviceSID != "" {
form["MessagingServiceSid"] = []string{serviceSID}
} else {
form["From"] = []string{channel.Address()}
for _, comp := range msg.Templating().Components {
for varKey, varIndex := range comp.Variables {
contentVariables[varKey] = msg.Templating().Variables[varIndex].Value
}
}

// for whatsapp channels, we have to prepend whatsapp to the To and From
if channel.IsScheme(urns.WhatsApp) {
form["To"][0] = fmt.Sprintf("%s:+%s", urns.WhatsApp.Prefix, form["To"][0])
form["From"][0] = fmt.Sprintf("%s:%s", urns.WhatsApp.Prefix, form["From"][0])
contentVariablesJson := jsonx.MustMarshal(contentVariables)
if len(contentVariables) > 0 {
form["ContentVariables"] = []string{string(contentVariablesJson)}
}

// build our URL
baseURL := h.baseURL(channel)
if baseURL == "" {
Expand Down Expand Up @@ -315,6 +311,89 @@
res.AddExternalID(externalID)
}

} else {

parts := handlers.SplitMsgByChannel(msg.Channel(), msg.Text(), maxMsgLength)
for i, part := range parts {
// build our request
form := url.Values{
"To": []string{msg.URN().Path()},
"Body": []string{part},
"StatusCallback": []string{callbackURL},
}

// add any attachments to the first part
if i == 0 {
for _, a := range attachments {
form.Add("MediaUrl", a.URL)
}
}

// set our from, either as a messaging service or from our address
serviceSID := channel.StringConfigForKey(configMessagingServiceSID, "")
if serviceSID != "" {
form["MessagingServiceSid"] = []string{serviceSID}
} else {
form["From"] = []string{channel.Address()}
}

// for whatsapp channels, we have to prepend whatsapp to the To and From
if channel.IsScheme(urns.WhatsApp) {
form["To"][0] = fmt.Sprintf("%s:+%s", urns.WhatsApp.Prefix, form["To"][0])
form["From"][0] = fmt.Sprintf("%s:%s", urns.WhatsApp.Prefix, form["From"][0])
}

// build our URL
baseURL := h.baseURL(channel)
if baseURL == "" {
return courier.ErrChannelConfig

Check warning on line 349 in handlers/twiml/handlers.go

View check run for this annotation

Codecov / codecov/patch

handlers/twiml/handlers.go#L349

Added line #L349 was not covered by tests
}

sendURL, err := utils.AddURLPath(baseURL, "2010-04-01", "Accounts", accountSID, "Messages.json")
if err != nil {
return err

Check warning on line 354 in handlers/twiml/handlers.go

View check run for this annotation

Codecov / codecov/patch

handlers/twiml/handlers.go#L354

Added line #L354 was not covered by tests
}

req, err := http.NewRequest(http.MethodPost, sendURL, strings.NewReader(form.Encode()))
if err != nil {
return err

Check warning on line 359 in handlers/twiml/handlers.go

View check run for this annotation

Codecov / codecov/patch

handlers/twiml/handlers.go#L359

Added line #L359 was not covered by tests
}
req.SetBasicAuth(accountSID, accountToken)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")

resp, respBody, err := h.RequestHTTP(req, clog)
if err != nil || resp.StatusCode/100 == 5 {
return courier.ErrConnectionFailed

Check warning on line 367 in handlers/twiml/handlers.go

View check run for this annotation

Codecov / codecov/patch

handlers/twiml/handlers.go#L367

Added line #L367 was not covered by tests
}

// see if we can parse the error if we have one
if resp.StatusCode/100 != 2 && len(respBody) > 0 {
errorCode, _ := jsonparser.GetInt(respBody, "code")
if errorCode != 0 {
if errorCode == errorStopped {
return courier.ErrContactStopped
}
codeAsStr := strconv.Itoa(int(errorCode))
errMsg, err := jsonparser.GetString(errorCodes, codeAsStr)
if err != nil {
errMsg = fmt.Sprintf("Service specific error: %s.", codeAsStr)
}
return courier.ErrFailedWithReason(codeAsStr, errMsg)
}

return courier.ErrResponseStatus
}

// grab the external id
externalID, err := jsonparser.GetString(respBody, "sid")
if err != nil {
clog.Error(courier.ErrorResponseValueMissing("sid"))
} else {
res.AddExternalID(externalID)
}
}

}

return nil
Expand Down
187 changes: 187 additions & 0 deletions handlers/twiml/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1069,6 +1069,35 @@ var waSendTestCases = []OutgoingTestCase{
}},
ExpectedExtIDs: []string{"1002"},
},
{
Label: "Template Send",
MsgText: "templated message",
MsgURN: "whatsapp:250788383383",
MsgLocale: "eng",
MsgTemplating: `{
"template": {"uuid": "171f8a4d-f725-46d7-85a6-11aceff0bfe3", "name": "revive_issue"},
"components": [
{"type": "body", "name": "body", "variables": {"1": 0, "2": 1}}
],
"variables": [
{"type": "text", "value": "Chef"},
{"type": "text" , "value": "tomorrow"}
],
"external_id": "ext_id_revive_issue",
"language": "en_US"
}`,
MockResponses: map[string][]*httpx.MockResponse{
"http://example.com/sigware_api/2010-04-01/Accounts/accountSID/Messages.json": {
httpx.NewMockResponse(200, nil, []byte(`{ "sid": "1002" }`)),
},
},

ExpectedRequests: []ExpectedRequest{{
Form: url.Values{"To": {"whatsapp:+250788383383"}, "From": {"whatsapp:+12065551212"}, "StatusCallback": {"https://localhost/c/t/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/status?id=10&action=callback"}, "ContentSid": {"ext_id_revive_issue"}, "ContentVariables": {"{\"1\":\"Chef\",\"2\":\"tomorrow\"}"}},
Headers: map[string]string{"Authorization": "Basic YWNjb3VudFNJRDphdXRoVG9rZW4="},
}},
ExpectedExtIDs: []string{"1002"},
},
}

var twaSendTestCases = []OutgoingTestCase{
Expand All @@ -1087,6 +1116,164 @@ var twaSendTestCases = []OutgoingTestCase{
}},
ExpectedExtIDs: []string{"1002"},
},
{
Label: "Template Send",
MsgText: "templated message",
MsgURN: "whatsapp:250788383383",
MsgLocale: "eng",
MsgTemplating: `{
"template": {"uuid": "171f8a4d-f725-46d7-85a6-11aceff0bfe3", "name": "revive_issue"},
"components": [
{"type": "body", "name": "body", "variables": {"1": 0, "2": 1}}
],
"variables": [
{"type": "text", "value": "Chef"},
{"type": "text" , "value": "tomorrow"}
],
"external_id": "ext_id_revive_issue",
"language": "en_US"
}`,
MockResponses: map[string][]*httpx.MockResponse{
"https://api.twilio.com/2010-04-01/Accounts/accountSID/Messages.json": {
httpx.NewMockResponse(200, nil, []byte(`{ "sid": "1002" }`)),
},
},
ExpectedRequests: []ExpectedRequest{{
Form: url.Values{"To": {"whatsapp:+250788383383"}, "From": {"whatsapp:+12065551212"}, "StatusCallback": {"https://localhost/c/twa/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/status?id=10&action=callback"}, "ContentSid": {"ext_id_revive_issue"}, "ContentVariables": {"{\"1\":\"Chef\",\"2\":\"tomorrow\"}"}},
Headers: map[string]string{"Authorization": "Basic YWNjb3VudFNJRDphdXRoVG9rZW4="},
}},
ExpectedExtIDs: []string{"1002"},
},
{
Label: "Template Send missing external ID",
MsgText: "templated message",
MsgURN: "whatsapp:250788383383",
MsgLocale: "eng",
MsgTemplating: `{
"template": {"uuid": "171f8a4d-f725-46d7-85a6-11aceff0bfe3", "name": "revive_issue"},
"components": [
{"type": "body", "name": "body", "variables": {"1": 0, "2": 1}}
],
"variables": [
{"type": "text", "value": "Chef"},
{"type": "text" , "value": "tomorrow"}
],
"language": "en_US"
}`,
ExpectedError: courier.ErrMessageInvalid,
},
{
Label: "Error Code",
MsgText: "Error Code",
MsgURN: "whatsapp:250788383383",
MsgLocale: "eng",
MsgTemplating: `{
"template": {"uuid": "171f8a4d-f725-46d7-85a6-11aceff0bfe3", "name": "revive_issue"},
"components": [
{"type": "body", "name": "body", "variables": {"1": 0, "2": 1}}
],
"variables": [
{"type": "text", "value": "Chef"},
{"type": "text" , "value": "tomorrow"}
],
"external_id": "ext_id_revive_issue",
"language": "en_US"
}`,
MockResponses: map[string][]*httpx.MockResponse{
"https://api.twilio.com/2010-04-01/Accounts/accountSID/Messages.json": {
httpx.NewMockResponse(400, nil, []byte(`{ "code": 1001 }`)),
},
},
ExpectedRequests: []ExpectedRequest{{
Form: url.Values{"To": {"whatsapp:+250788383383"}, "From": {"whatsapp:+12065551212"}, "StatusCallback": {"https://localhost/c/twa/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/status?id=10&action=callback"}, "ContentSid": {"ext_id_revive_issue"}, "ContentVariables": {"{\"1\":\"Chef\",\"2\":\"tomorrow\"}"}},
Headers: map[string]string{"Authorization": "Basic YWNjb3VudFNJRDphdXRoVG9rZW4="},
}},
ExpectedError: courier.ErrFailedWithReason("1001", "Service specific error: 1001."),
},
{
Label: "Stopped Contact Code",
MsgText: "Stopped Contact",
MsgURN: "whatsapp:250788383383",
MsgLocale: "eng",
MsgTemplating: `{
"template": {"uuid": "171f8a4d-f725-46d7-85a6-11aceff0bfe3", "name": "revive_issue"},
"components": [
{"type": "body", "name": "body", "variables": {"1": 0, "2": 1}}
],
"variables": [
{"type": "text", "value": "Chef"},
{"type": "text" , "value": "tomorrow"}
],
"external_id": "ext_id_revive_issue",
"language": "en_US"
}`,
MockResponses: map[string][]*httpx.MockResponse{
"https://api.twilio.com/2010-04-01/Accounts/accountSID/Messages.json": {
httpx.NewMockResponse(400, nil, []byte(`{ "code": 21610 }`)),
},
},
ExpectedRequests: []ExpectedRequest{{
Form: url.Values{"To": {"whatsapp:+250788383383"}, "From": {"whatsapp:+12065551212"}, "StatusCallback": {"https://localhost/c/twa/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/status?id=10&action=callback"}, "ContentSid": {"ext_id_revive_issue"}, "ContentVariables": {"{\"1\":\"Chef\",\"2\":\"tomorrow\"}"}},
Headers: map[string]string{"Authorization": "Basic YWNjb3VudFNJRDphdXRoVG9rZW4="},
}},
ExpectedError: courier.ErrContactStopped,
},
{
Label: "No SID",
MsgText: "No SID",
MsgURN: "whatsapp:250788383383",
MsgLocale: "eng",
MsgTemplating: `{
"template": {"uuid": "171f8a4d-f725-46d7-85a6-11aceff0bfe3", "name": "revive_issue"},
"components": [
{"type": "body", "name": "body", "variables": {"1": 0, "2": 1}}
],
"variables": [
{"type": "text", "value": "Chef"},
{"type": "text" , "value": "tomorrow"}
],
"external_id": "ext_id_revive_issue",
"language": "en_US"
}`,
MockResponses: map[string][]*httpx.MockResponse{
"https://api.twilio.com/2010-04-01/Accounts/accountSID/Messages.json": {
httpx.NewMockResponse(200, nil, []byte(`{ }`)),
},
},
ExpectedRequests: []ExpectedRequest{{
Form: url.Values{"To": {"whatsapp:+250788383383"}, "From": {"whatsapp:+12065551212"}, "StatusCallback": {"https://localhost/c/twa/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/status?id=10&action=callback"}, "ContentSid": {"ext_id_revive_issue"}, "ContentVariables": {"{\"1\":\"Chef\",\"2\":\"tomorrow\"}"}},
Headers: map[string]string{"Authorization": "Basic YWNjb3VudFNJRDphdXRoVG9rZW4="},
}},
ExpectedLogErrors: []*courier.ChannelError{courier.ErrorResponseValueMissing("sid")},
},
{
Label: "Error Sending",
MsgText: "Error Message",
MsgURN: "whatsapp:250788383383",
MsgLocale: "eng",
MsgTemplating: `{
"template": {"uuid": "171f8a4d-f725-46d7-85a6-11aceff0bfe3", "name": "revive_issue"},
"components": [
{"type": "body", "name": "body", "variables": {"1": 0, "2": 1}}
],
"variables": [
{"type": "text", "value": "Chef"},
{"type": "text" , "value": "tomorrow"}
],
"external_id": "ext_id_revive_issue",
"language": "en_US"
}`,
MockResponses: map[string][]*httpx.MockResponse{
"https://api.twilio.com/2010-04-01/Accounts/accountSID/Messages.json": {
httpx.NewMockResponse(401, nil, []byte(`{ "error": "out of credits" }`)),
},
},
ExpectedRequests: []ExpectedRequest{{
Form: url.Values{"To": {"whatsapp:+250788383383"}, "From": {"whatsapp:+12065551212"}, "StatusCallback": {"https://localhost/c/twa/8eb23e93-5ecb-45ba-b726-3b064e0c56ab/status?id=10&action=callback"}, "ContentSid": {"ext_id_revive_issue"}, "ContentVariables": {"{\"1\":\"Chef\",\"2\":\"tomorrow\"}"}},
Headers: map[string]string{"Authorization": "Basic YWNjb3VudFNJRDphdXRoVG9rZW4="},
}},
ExpectedError: courier.ErrResponseStatus,
},
}

func TestOutgoing(t *testing.T) {
Expand Down
9 changes: 9 additions & 0 deletions sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ var ErrConnectionThrottled error = &SendError{
clogMsg: "Connection to server has been rate limited.",
}

// ErrMessageInvalid should be returned by a handler send method when the message it has received is invalid
var ErrMessageInvalid error = &SendError{
msg: "message invalid",
retryable: false,
loggable: true,
clogCode: "message_invalid",
clogMsg: "Message is missing required values.",
}

// ErrResponseStatus should be returned when channel the response has a non-success status code
var ErrResponseStatus error = &SendError{
msg: "response status code",
Expand Down
Loading