The Sendblue API allows you to send iMessages (and SMS) to groups of people. This is a great way to send messages to your clients, customers, friends, or family. In this article, we’ll take a look at how to use Sendblue’s Group iMessaging Beta to notify system administrators when a Stripe subscription is created.

What is Sendblue?

Sendblue is a messaging platform that allows you to send iMessage and SMS. It’s a great way to send messages on behalf of your business. Because iMessage is internet-based, all messages have a flat rate and aren’t priced by segment. This means that the length of your message does not impact how much it costs to send, and you also don’t need to deal with formatting issues on the receiving side.

iMessage also has a much higher media size limit than SMS, which means you can send larger files & high-res images to your recipients, all for the same price as a single message.

Setting up the Sendblue Notifier

We’ll start by setting up a Sendblue client in our workspace. This will allow us to send arbitrary messages from anywhere in our codebase. We’ll also set up a webhook to receive status updates for Stripe Subscriptions.

1. Configuring the Sendblue Client

To send Sendblue group iMessages, make sure that you have signed up for an account. Once you’ve signed up, you can find your Sendblue API key in your api settings. Then you can use the Sendblue client to send messages to groups of people:

in sendblue_client.py:

from sendblue import Sendblue

client = Sendblue(api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET")
client.send_group_message(
    numbers=["+19998887777", "+19998887778"],
    content="Testing a group message!",
    media_url="https://picsum.photos/200/300.jpg",
)

Of course, you will want to replace the api key and secret with your own. You can also replace the numbers and message content.

Once you are able to verify that the messages are coming through with this simple script, you can move on to the next step.

2. Configuring the Stripe Webhook

Assuming you have followed Stripe’s basic subscription payments tutorial, you should have a Stripe workflow setup. Now we just need to add a notification to the workflow to send a message to our group when a subscription is created.

First, make sure that the webhook is configured to send a notification to Sendblue. You can do this by going to the webhook settings and adding a new webhook endpoint. The endpoint should be the URL of your backend server. It should look something like this:

Stripe webhooks

Correctly Configured Stripe Webhook

3. Inserting a Notification for Stripe Subscriptions

Once you’ve added the webhook, you can add the Sendblue code from before into your Stripe webhook handler. This will send a message to your webhook when a subscription is created. This is what your webhook handler should look like before adding Sendblue:

import json
import os
import stripe

from flask import Flask, jsonify, request

# This is your Stripe CLI webhook secret for testing your endpoint locally.
endpoint_secret = 'whsec_YOUR-WEBHOOK-SECRET'

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    event = None
    payload = request.data
    sig_header = request.headers['STRIPE_SIGNATURE']

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, endpoint_secret
        )
    except ValueError as e:
        # Invalid payload
        raise e
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        raise e

    # Handle the event
    if event['type'] == 'customer.subscription.created':
      subscription = event['data']['object']
    # ... your custom handler for new subscriptions
    else:
      print('Unhandled event type {}'.format(event['type']))

    return jsonify(success=True)

Next, add an import to the Sendblue client at the top of this module like so:

from sendblue_client import client

ADMIN_NUMBERS = ["+19998887777", "+19998887778"] # replace with your own numbers

Then, add the following code to the customer.subscription.created handler:

...
  if event['type'] == 'customer.subscription.created':
      subscription = event['data']['object']
    # ... your custom handler for new subscriptions
    client.send_group_message(
        numbers=ADMIN_NUMBERS,
        content="There was a new subscription! " + subscription["id"],
        media_url="https://picsum.photos/200/300.jpg",
    )
...

Conclusion

Violà! You should now be able to send group messages to your admins when a new subscription is created.

Keep in mind that this implementation is just an example and is only scratching the surface of what you can do with iMessage. You could add texts whenever someone cancels, or you could event start a texting cadence when a customer is about to cancel. The possibilities are endless!

If you have any questions, feel free to reach out to us on Twitter.