Frequently Asked Questions
Integrate the Sinch Batch SMS API into your RedwoodJS application. This involves setting up environment variables for your Sinch credentials, creating database models for campaigns and contacts, and implementing RedwoodJS services to manage these entities and interact with the Sinch API. This guide provides a step-by-step tutorial for this integration process.
The Sinch Batch SMS API allows you to send bulk SMS messages programmatically within your RedwoodJS app, making it suitable for marketing campaigns. This guide focuses on integrating with the `/xms/v1/{SERVICE_PLAN_ID}/batches` endpoint, enabling automated campaign creation and targeted sending. Note that Sinch may offer dedicated Marketing Campaign APIs with additional features.
You can create a dedicated Sinch API client within your `api/src/lib` directory to handle the API interaction logic. Then import and call the client functions from your RedwoodJS services, specifically within the service responsible for managing and sending campaigns.
Prisma acts as an ORM (Object-Relational Mapper), simplifying database interactions within your RedwoodJS application. It allows you to define data models (like Contacts and Campaigns) and easily perform CRUD operations without writing raw SQL queries.
You primarily need services for managing campaigns and contacts. The campaign service handles creating, updating, and sending campaigns, while the contact service manages your contact list. These services interact with Prisma for database access and the Sinch client for sending SMS messages.
Create a `.env` file in the root of your RedwoodJS project. Add your `SINCH_SERVICE_PLAN_ID`, `SINCH_API_TOKEN`, `SINCH_SENDER_ID`, and `SINCH_API_BASE_URL` obtained from your Sinch dashboard to this file. Your `.env` file should already be in `.gitignore` for security.
GraphQL serves as the communication layer between the RedwoodJS frontend (web side) and backend (api side). You define GraphQL schemas (SDL) to specify data types and queries/mutations. RedwoodJS automatically generates resolvers that map these to your service functions.
Use the command `yarn create redwood-app --typescript` in your terminal. The `--typescript` flag is recommended for better type safety. Then, navigate into the project directory using `cd `.
While Node.js has a built-in `fetch`, using `node-fetch@^2` explicitly ensures better CommonJS compatibility, particularly with the RedwoodJS api side. Install it with `yarn workspace api add node-fetch@^2` and its types with `yarn workspace api add -D @types/node-fetch@^2`.
The example uses SQLite for simplicity, but you can configure PostgreSQL or MySQL in your `schema.prisma` file. The `DATABASE_URL` in your `.env` file controls the database connection. For local SQLite, use `DATABASE_URL="file:./dev.db"`.
The provided `sinchRequest` helper function in the Sinch client includes basic error handling and logging. It attempts to parse error responses from Sinch to provide more detailed messages for debugging. Always avoid exposing raw Sinch errors to the frontend if possible.
Yes, you can use a registered phone number, short code, or alphanumeric sender ID approved by Sinch. Set the `SINCH_SENDER_ID` environment variable in your `.env` file. This value is then used in the `from` field of the API request.
The Sinch Service Plan ID is a unique identifier that specifies the service plan you're using within the Sinch platform. It's required to make authenticated requests to the Sinch API and is included in the API endpoint URL.
Integrate Sinch Batch SMS API with RedwoodJS for Marketing Campaigns
This guide provides a comprehensive, step-by-step tutorial for integrating the Sinch Batch SMS API into a RedwoodJS application to facilitate marketing campaigns. We will build a system enabling users to define campaign messages, manage contacts, and send SMS batches via Sinch directly from a RedwoodJS app.
This integration addresses the need for programmatic control over SMS marketing efforts, allowing for automated campaign creation, targeted sending based on application data, and centralized management within your existing RedwoodJS project. While this guide focuses on using the common Sinch Batch SMS API (
/xms/v1/{SERVICE_PLAN_ID}/batches
) as a practical way to send campaign messages, please note that Sinch may offer dedicated ""Marketing Campaign"" APIs with additional features (like advanced list management or specific campaign tracking). You should consult the official Sinch documentation to determine the best API for your specific marketing requirements.Technologies Used:
System Architecture:
Final Outcome:
By the end of this guide, you will have:
Campaign
andContact
data.Prerequisites:
(Note: This guide assumes you are starting a new RedwoodJS project. Adapt steps accordingly if integrating into an existing one.)
1. Setting up the Project
This section covers creating a new RedwoodJS project and configuring the necessary environment.
Create RedwoodJS App: Open your terminal and run the RedwoodJS creation command. We'll name our project
redwood-sinch-campaigns
.--typescript
: Initializes the project with TypeScript for enhanced type safety.Navigate to Project Directory:
Environment Variables Setup: RedwoodJS uses
.env
files for environment variables. Create a.env
file in the project root for your Sinch credentials.touch .env
Explanation:
SINCH_SERVICE_PLAN_ID
: Your unique identifier for the Sinch service plan.SINCH_API_TOKEN
: Your secret token for authenticating API requests. Treat this like a password.SINCH_SENDER_ID
: Your registered phone number, short code, or alphanumeric sender ID approved by Sinch for sending messages. This is required in thefrom
field of the SMS request.SINCH_API_BASE_URL
: The base URL for the Sinch REST API endpoints relevant to SMS. Adjust if your account is homed in a different region (e.g., EU).DATABASE_URL
: Connection string for your database (adjust provider inschema.prisma
accordingly).Security: Ensure
.env
is added to your.gitignore
file (RedwoodJS usually adds it by default) to prevent accidentally committing secrets.Install Dependencies (Optional but Recommended): We'll use
node-fetch
for making HTTP requests to the Sinch API from our Node.js backend. While Node.js has a built-in fetch (experimental in older versions, stable in newer ones), explicitly addingnode-fetch
ensures compatibility and consistent behavior.yarn workspace api add ...
: Installs the package specifically for theapi
side of your RedwoodJS project.node-fetch@^2
: Version 2 is generally recommended for CommonJS environments like the default Redwood API side.@types/node-fetch@^2
: Adds TypeScript typings fornode-fetch
.Project Structure Overview: RedwoodJS has a conventional structure:
api/
: Backend code (GraphQL API, services, database, Node.js logic).api/db/schema.prisma
: Database schema definition.api/src/functions/
: Serverless function handlers (GraphQL endpoint).api/src/graphql/
: GraphQL schema definitions (*.sdl.ts
).api/src/services/
: Business logic implementations.api/src/lib/
: Utility functions, third-party clients (like our Sinch client).web/
: Frontend code (React components, pages, layouts).web/src/pages/
: Page components.web/src/components/
: Reusable UI components (including Cells).web/src/layouts/
: Layout components wrapping pages.web/src/Routes.tsx
: Frontend routing definitions..env
: Environment variables (ignored by Git).redwood.toml
: Project configuration.2. Implementing Core Functionality (Database and Services)
We'll define our data models, apply migrations, and create RedwoodJS services to manage them.
Define Database Schema: Open
api/db/schema.prisma
and define models forContact
andCampaign
.Contact
with essential fields likephoneNumber
. Storing in E.164 format (e.g.,+15551234567
) is highly recommended.Campaign
with a name, message body, status, andsinchBatchId
to store the ID returned by the Sinch Batch SMS API for tracking.Campaign.status
for performance.Apply Database Migrations: Use the Redwood CLI to create and apply a database migration based on the schema changes.
api/db/migrations/
.Generate Services: Use the Redwood CLI to generate boilerplate code for services that will handle the business logic for contacts and campaigns.
api/src/services/contacts/contacts.ts
,api/src/services/campaigns/campaigns.ts
, and corresponding test/scenario files.Implement Service Logic (Basic CRUD): Open the generated service files and add basic CRUD (Create, Read, Update, Delete) operations.
api/src/services/contacts/contacts.ts
:api/src/services/campaigns/campaigns.ts
:Data Layer Summary:
ERD (Simplified):
Data Access: Handled by Prisma Client via Redwood services (
db.campaign.findMany()
,db.contact.create()
, etc.). Redwood'sdb
object is an instance ofPrismaClient
.Migrations: Managed by
yarn rw prisma migrate dev
. For production, useyarn rw prisma migrate deploy
.Seed Sample Data (Optional): Use Prisma seeds to populate your development database.
Create seed file:
touch api/db/seed.ts
Add seed logic:
Add seed script to
api/package.json
(check if Redwood added it first):And ensure
prisma.seed
is set inapi/db/schema.prisma
generator block:Check your
api/package.json
first, Redwood often configuresprisma db seed
.Configure the seed command in
prisma
section of rootpackage.json
if not present:Run seeding:
yarn rw prisma db seed
3. Building the API Layer (GraphQL SDL)
RedwoodJS automatically maps service functions to GraphQL resolvers. We just need to define the schema.
Generate GraphQL SDL: Use the Redwood CLI to generate SDL files based on your Prisma schema models.
--crud
: Generates standard GraphQL types, queries (for reading), and mutations (for creating, updating, deleting) based on the model and corresponding service functions.Review and Customize SDL: Inspect the generated files (
api/src/graphql/contacts.sdl.ts
andapi/src/graphql/campaigns.sdl.ts
). They should look similar to this (customize as needed):api/src/graphql/contacts.sdl.ts
:api/src/graphql/campaigns.sdl.ts
:Testing API Endpoints (GraphQL Playground):
Start the development server:
yarn rw dev
Open your browser to
http://localhost:8910/graphql
(or the port specified in the console output).You can now test your queries and mutations.
Example Query (Get Campaigns):
Example Mutation (Create Campaign):
(Note:
@requireAuth
might block requests if auth isn't configured. Remove it from the SDL temporarily for testing if needed, but ensure it's present for production.)4. Integrating with Sinch API
Now, let's build the client to communicate with the actual Sinch Batch SMS API.
Create Sinch Client Library: Create a new file for our Sinch API interaction logic.
mkdir -p api/src/lib/sinchClient
touch api/src/lib/sinchClient/index.ts
Implement Sinch API Client Logic: Open
api/src/lib/sinchClient/index.ts
and add the code to interact with Sinch.process.env
.sinchRequest
helper function to handle authentication, headers, request/response logging, and basic error handling for all Sinch API calls. It usesnode-fetch
.sendSinchSmsBatch
to interact with the/batches
endpoint, suitable for sending messages to multiple recipients.Obtaining Sinch Credentials:
.env
file.us.sms.api.sinch.com
,eu.sms.api.sinch.com
).Connect Sinch Client to Campaign Service: Now, update the
sendCampaign
function inapi/src/services/campaigns/campaigns.ts
to use the Sinch client.