Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • Start Building
    • 5-Minute Guide
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Validate JWT in your application server
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
  • How-To Guides
    • Authenticate
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Add authentication to any web page
      • Enable Two-Factor Authentication (2FA)
      • Reauthentication
      • Passwordless Login for Apple App Store Review
      • Change Forgot/Reset Password settings
      • Adjust Phone Number Validation
      • Set Password Expiry
      • Use the OAuth 2.0 State Parameter
      • Setup local development environment for Cookie-based authentication
      • Use Social/Enterprise Login Providers Without AuthUI
    • Single Sign-on
      • App2App Login
      • Pre-authenticated URLs
      • SSO between Mobile Apps / Websites
      • Force Authgear to Show Login Page
      • Single Sign-On with OIDC
      • Single Sign-On with SAML
        • Use Authgear as SAML Identity Provider for Salesforce
        • Use Authgear as SAML Identity Provider for Dropbox
        • SAML Attribute Mapping
    • Social Login / Enterprise Login Providers
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
    • Integrate
      • Add custom fields to a JWT Access Token
      • User Analytics by Google Tag Manager
      • Track User Before and After Signup
      • Custom domain
      • Custom Email Provider
      • Custom SMS Provider
        • Twilio
        • Webhook/Custom Script
      • Integrate Authgear with Firebase
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Example: Only Allow Signups from Inside the Corporate Network using Hooks
    • Mobile Apps
      • Use SDK to make authorized API calls to backend
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Directly accessing Authgear Endpoint
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Design
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Languages and Localization
    • Custom Email and SMS Templates
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Authgear ONCE
    • What is Authgear ONCE
    • Install Authgear ONCE on a VM
    • Install Authgear ONCE on Vultr
    • Install Authgear ONCE on Amazon Web Services (AWS)
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • Admin API Examples
        • Using global node IDs
        • Retrieving users using Admin API
        • User Management Examples
          • Search for users
          • Update user's standard attributes
          • Update user's picture
          • Generate OTP code
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • UserInfo
        • Supported Scopes
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Glossary
    • Billing FAQ
    • Rate Limits
      • Account Lockout
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deploy on your Cloud
    • Running locally with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configurations
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Reference Architecture Diagrams
      • Google Cloud Reference Architecture
      • Azure Reference Architecture
      • AWS Reference Architecture
      • Throughput Scaling Reference
Powered by GitBook
On this page
  • Prerequisites
  • Step 1: Enable Custom SMS Gateway
  • Step 2: Select SMS Gateway Provider
  • Step 3: Set up Webhook or Implement Custom Script
  • Step 4: Save and Test the Custom SMS Provider

Was this helpful?

Edit on GitHub
Export as PDF
  1. How-To Guides
  2. Integrate
  3. Custom SMS Provider

Webhook/Custom Script

Connect with any SMS providers with webhook or custom scripts for communication with the users.

PreviousTwilioNextIntegrate Authgear with Firebase

Last updated 2 months ago

Was this helpful?

Webhook and Custom JavaScript/TypeScript are some of the ways you can configure your Authgear project to .

In this guide, you'll learn how to switch from the default SMS provider to just about any third-party SMS provider.

Prerequisites

  • An SMS provider with an API endpoint that accepts external HTTPS requests.

  • An Authgear project with the Custom SMS Gateway feature enabled.

Note: Your project must be on an enterprise plan to use the Custom SMS Provider feature. for more details.

Step 1: Enable Custom SMS Gateway

To enable Custom SMS Gateway, log in to Authgear Portal, and navigate to Advanced > Custom SMS Gateway.

Toggle the Enable Custom SMS Gateway switch on to enable Custom SMS Provider.

Step 2: Select SMS Gateway Provider

Select Webhook under SMS Gateway Provider to set up a custom SMS provider using Webhook.

Alternatively, select Custom JS/TS to set up a custom SMS provider using custom JavaScript/TypeScript code in your Authgear project.

Step 3: Set up Webhook or Implement Custom Script

A key thing to consider before implementing your webhook or custom script is the structure of the payload your Authgear application will send to your endpoint.

Payload

The following is the structure of the JSON payload for custom SMS webhook and custom JS/TS (CustomSMSGatewayPayload).

{
  "to": "+44123456789",
  "body": "420240 is your french verification code.\n\nDon't share it with anyone.\n",
  "app_id": "demo-enterprise",
  "template_name": "verification_sms.txt",
  "language_tag": "en",
  "template_variables": {
    "app_name": "french",
    "client_id": "tester",
    "code": "420240",
    "host": "your-app.example.com",
    "phone": "+447549293826",
    "state": "eyK1b2hjjnI6IkdaI1qwwe5KVlMySEU7Ghhjsjs"
  }
}
  • to is the phone number of the receiver.

  • The body field contains the actual message.

  • app_id: is the identifier for the Authgear project sending the SMS.

  • language_tag: a tag specifying the language of the message.

  • template_variables: this is an object with all the variables that are used to add dynamic content such as OTP code, the app_name of your app, etc, to the SMS template.

Webhook

For Webhook, follow these steps to configure the options:

  • Webhook Endpoint: enter the full URL for the page in your application that will receive the payload from Authgear's webhook request and use it to send the SMS.

  • JSON Payload Sample: this section shows the structure of the JSON payload. The key payload includes a to and a body field.

  • Timeout: enter a value between 1 to 60. Use a number close to the maximum if your webhook requires more time to respond.

Custom JS/TS

Implement the logic for sending an HTTPS request to your custom SMS provider in the Custom script editor.

The default sample code can be used as a good base for starting out:

import { CustomSMSGatewayPayload, CustomSMSGatewayResponse } from "https://deno.land/x/authgear_deno_hook@v1.5.0/mod.ts";

export default async function (e: CustomSMSGatewayPayload): Promise<CustomSMSGatewayResponse> {
  const body = JSON.stringify(e);
  const response = await fetch("https://some.sms.gateway", {
    method: "POST",
    body: body,
  });

  if (!response.ok) {
    return {
      code: "delivery_rejected",
    }
  }

  return {
    code: "ok",
  }
}

Replace https://some.sms.gateway with the actual endpoint for your SMS provider.

The following example shows how to send SMS via Custom JS/TS:

import { CustomSMSGatewayPayload, CustomSMSGatewayResponse } from "https://deno.land/x/authgear_deno_hook@v1.5.0/mod.ts";

export default async function (e: CustomSMSGatewayPayload): Promise<CustomSMSGatewayResponse> {
  const gatewayJson =  {
    "SMS": {
        "auth": {
            "username": "user@example.com",
            "apikey": "abc13de25fgh46"
        },
        "message": {
            "sender": "AG Test",
            "messagetext": e.body,
            "flash": "0"
        },
        "recipients":
        {
            "gsm": [
                {
                    "msidn": e.to
                }
            ]
        }
      }
    };
  const response = await fetch("https://api.example.com/sendsms.json", {
    method: "POST",
    body: JSON.stringify(gatewayJson),
    headers: {
      "Content-Type": "application/json"
    },
  });

  if (!response.ok) {
    return {
      code: "delivery_rejected",
    }
  }

  return {
    code: "ok",
  }
}

In the above example, we read the values of to and body from Authgear's CustomSMSGatewayPayload (e) and used it to build the format of JSON data our custom SMS gateway expects.

See the official documentation for your SMS gateway to learn more about how to structure your HTTPS request.

Response

Both the Webhook and JavaScript/TypeScript share the same response. The following shows the schema of the response your webhook or custom script should send to Authgear for better user experience and error handling:

{
  "code":  "ok",
  "provider_error_code": ""
}
  • code: this field is required, and the value can be one of the following strings:

    • ok: return this code if the sms is delivered successfully.

    • invalid_phone_number: return this code if the receiver's phone number is invalid.

    • rate_limited: return this code if some rate limit is reached, and the user should retry the request.

    • authentication_failed: return this code if some form of authentication has failed, and the developer should check the current configurations.

    • delivery_rejected: return this code if the sms delivery service rejected the request for any reason the user cannot fix by retrying.

  • provider_error_code: this is an optional field to include an error code that could appear on Authgear Portal and assist debugging. A good way to use this field is to put the error code returned by your custom SMS provider (e.g., Twilio). The value should be a string.

Step 4: Save and Test the Custom SMS Provider

Finally, click on the Save button to save your new custom provider settings.

To test your work, click on the Test button next to the Save button, enter your phone number, and then click Send to test your new SMS provider.

template_name: the value shows the specific sms template type that is used for composing the message body. For example, verification_sms.txt when a verification SMS is sent using the verification template set in in Authgear portal.

Webhook Signature Secret Key: this field displays your project's Webhook Signature Secret Key. Each webhook event request includes a signature to confirm it comes from Authgear. We recommend that you verify this signature to confirm that the request is actually from your Authgear project before proceeding. See .

e contains the payload (CustomSMSGatewayPayload) with details such as the body and to (the receiver's phone number). See the example of a .

Email/SMS Templates
complete payload above
use Custom SMS Providers
Contact us
Verifying Signature
authgear custom sms gateway