Integrate SMS Service with Yeastar P-Series Cloud Edition using SMS API

Yeastar P-Series Cloud Edition allows Service Providers to integrate their SMS service with the PBX system using SMS API. This topic describes how Service Provider can achieve the interaction of SMS service with Yeastar PBX using API, and introduces how PBX administrators can set up an SMS channel for the Service Provider on PBX system.

Requirements

To implement the SMS service integration with Yeastar P-Series Cloud Edition, Yeastar PBX and Service Provider must meet the following requirements.

Platform Requirement
Yeastar PBX
  • Firmware: Version 84.14.0.24 or later
  • Plan: Enterprise Plan (EP) or Ultimate Plan (UP)
  • Domain Name: Due to the limitation of the third-party platform, the domain name must NOT contain underscore character(s), otherwise the messaging channel will encounter authentication failure, or will fail to receive messages.
  • Domain Certificate: A valid domain certificate is installed.
    Note: If the root domain of your Cloud PBX is NOT the standard Yeastar-provided domains (ycmcloud.com, yeastarcloud.com, or yeastarycm.co.za), you NEED to install a valid domain certificate for the PBX first, otherwise the messaging channel will encounter authentication failure, or will fail to receive messages.
Service Provider
  • API: Service Provider should provide the following API interfaces.
    • HTTPS REST API for verifying authentication
    • HTTPS REST API for sending messages
  • Customer Portal Feature: Service Provider should offer the following features on its customer portal.
    • Provide an API key to authenticate API requests sent from PBX system.
    • Provide a Secret for PBX system to verify webhook requests sent by the Service Provider.
    • Support for configuring Webhook through the customer portal.
  • Number Format: Phone numbers should follow the E.164 format.

Authenticate requests

As the SMS service integration is implemented via API interactions between Service Provider and PBX, the Service Provider should provide an API key and a Secret for the request authentication of APIs and webhooks in the integration.
  • API key

    The API key is used to authenticate the API requests sent from PBX to Service Provider.

    The PBX will pass the API key in the header of each API request under an Authorization field, as shown below:

    Authorization: Bearer {api_key}
    Upon receiving an API request, Service Provider verifies the API key extracted from the request header. If the API key is valid, the Service Provider should execute the corresponding actions as specified in the request. Otherwise, the API request fails.
    For more information about the API request, see the followings:
  • Secret

    The Secret is used to authenticate the webhook requests sent from Service Provider to PBX.

    When sending a message to PBX via webhook, the Service Provider needs to utilize the Secret along with the SHA256 algorithm to generate a signature based on the webhook request body, and pass the signature in the header of each webhook request under an X-Signature-256 field, as shown below:
    Important: The signature included in the request header must be in all lowercase letters.
    X-Signature-256: sha256={signature}
    Upon receiving a webhook request, PBX calculates a signature using the Secret along with SHA256 algorithm based on the received webhook request body, then compares the result with the signature extracted from the request header. If the signatures match, it indicates that the webhook request is valid and PBX will deliver the message retrieved from the request body to the message recipient. Otherwise, the webhook request will be rejected.

    For more information about the webhook request, see Receive messages from Service Provider.

Verify SMS channel connectivity

Once an SMS channel has been established on PBX web portal, the system will periodically send API requests to Service Provider using the API address for verifying authentication and API key to verify the connectivity of the channel.

Interaction flow

The process of channel connectivity verification is shown below:

  1. PBX initiates an API request, containing a randomly generated challenge code.
  2. Upon receiving the API request, Service Provider validates the API key.
  3. If the API key is valid, Service Provider should return a status code 200, and include the challenge code in the response body.
  4. Upon receiving the response, PBX checks if the returned challenge code matches the one it sent.

    If the challenge code matches, it indicates that the channel connection is successful.

API request sent by PBX

Below is the structure and explanation of the API request sent by PBX for channel connectivity verification.

Request method
GET
Request URL
{api_address_for_verifying_authentication}
For example:
https://service-provider.example.com/verify
Headers
Parameter Type Description
Authorization String Pass the API key in the header.

Format: Bearer {api_key}

Query parameter
Parameter Type Description
challenge String Challenge code. A random string that is generated by PBX.
Request example
GET /verify?challenge=mAWpGnyeTZgguOPYlWitGPlRJYIhoLMy HTTP/1.1
Host: service-provider.example.com
Authorization: Bearer {api_key}
API response returned by Service Provider
Service Provider should return the API response in JSON format.
Success response
If the request is successful, Service Provider should return the following information in the response:
  • HTTP status code 200
  • The challenge code that was sent by PBX in the request

For example:

HTTP/1.1 200 OK 
Body: mAWpGnyeTZgguOPYlWitGPlRJYIhoLMy
If the challenge code in the response body matches the one sent by PBX, it indicates that the channel has successfully connected. In this case, the channel status on PBX web portal is displayed as (Connected).
Error response
If the request fails, Service Provider should return the error information in the response according to the following format.
Parameter Type Description
code String Error code.
title String Error type (Customizable).
detail String Detailed information of the error (Customizable).
The following example shows a response of a failed channel connectivity verification.
HTTP/1.1 401 Unauthorized
{
    "errors": [
        {
            "code": "10004",     
            "title": "Authentication failed",    
            "detail": "No key found matching the ID with the provided secret."
        }
    ]
}
Exceptions and troubleshooting
If channel connectivity verification fails, the channel on PBX web portal will display an abnormal status. Service Provider can troubleshoot the cause of the anomaly by checking the error code and response body.
  • Error code

    The table below lists the error codes defined in the PBX.

    Error Code Error Message Description
    10001 channel.ErrInvalidPhoneNumber Invalid phone number.
    10002 channel.ErrInvalidParam Invalid parameter in the request.
    10003 channel.ErrUnsupportMedia Resource type not supported (MMS).
    10004 channel.ErrAuthFail Authentication failed.
    10005 channel.ErrAuthFail No permission.
    10006 channel.ErrTooManyRequest Too many requests.
    10007 channel.ErrServiceUnavailable Service unavailable on recipient's platform.
    10008 channel.ErrExceedsSizeLimit File size exceeds the limit.
  • Exceptions

    The table below lists the possible abnormal channel statuses and their trigger conditions.

    Channel Status Trigger Condition
    Unauthorized
    • Authentication failed, Service Provider returns HTTP status code 401/403/404.
    • The returned challenge code does not match the one sent by the PBX.
    Services of the recipient platform are unavailable Service Provider returns HTTP status code 500.
    Unknown Service Provider returns HTTP status code except for 401/403/404/500, and returns error information in the response body according to the format defined by the PBX.
    Request Failed
    • Service Provider does not return an HTTP status code, possibly due to TCP connection issues or non-existent domain.
    • Service Provider returns HTTP status code except for 401/403/404/500, and does not return a response body or the returned response body is not in JSON format.

Send messages through Service Provider

When a PBX user sends a message, PBX will send an API request to the Service Provider using the API interface for sending messages and API key, so as to deliver the message to external message recipient through Service Provider.

Interaction flow
The process of sending a message through Service Provider is shown below:

  1. A PBX user sends a message.
  2. PBX initiates an API request to send a message through the Service Provider.
  3. Upon receiving the API request, the Service Provider validates the API key.
  4. If the API key is valid, the Service Provider should return a status code 200 and a data.id to pass the unique ID of the message.
  5. Service Provider delivers the message to the message recipient.
API request sent by PBX
Below is the structure and explanation of the API request sent by PBX for sending a message through Service Provider.
Request method
POST
Request URL
{api_address_for_sending_message}
For example:
https://service-provider.example.com/sendmessage
Headers
Parameter Type Description
Content-Type String Define the content type of the request payload.

Valid value: application/json

Authorization String Pass the API key in the header.

Format: Bearer {api_key}

Request body
PBX will pass the outbound message in the request body.
Parameter Type Description
from String Phone number of the message sender.
Note: This parameter should be in E.164 format. For example, +8618012121222.
to String Phone number of the message recipient.
Note: This parameter should be in E.164 format. For example, +8618012121222.
text String The textual content of the message.
media_urls Array<String> The URL(s) pointing to the media content of the message.
Request example
Here are examples of sending SMS/MMS messages to a phone number through Service Provider.
  • Send an SMS message
    POST /sendmessage HTTP/1.1
    Host: service-provider.example.com
    Content-Type: application/json
    Authorization: Bearer {api_key}
    
    {
        "from": "+8618012121222",  
        "text": "Hello, World!",   
        "to": "+8618012121223"     
    }
  • Send an MMS message
    POST /sendmessage HTTP/1.1
    Host: service-provider.example.com
    Content-Type: application/json
    Authorization: Bearer {api_key}
    
    {
        "from":"+8618012121222",
        "to":"+8618012121223",
        "media_urls":["docs.example.yeastarcloud.com/api/chat/70dee7e2f95041ca890f222ace06c2dc"]
    }
API response returned by Service Provider

Service Provider should return the API response in JSON format.

Success response
If the request is successful, Service Provider should return the following information in the response:
  • HTTP status code 200
  • A parameter data.id to pass the unique ID of the message

For example:

HTTP/1.1 200 OK 
{
    "data": {
        "id":"b301ed3f-1490-491f-995f-6e64e69674d4",  // Message ID (Required)
        "from": {                                     // Message sender's information
            "carrier": "PBX",                      
            "line_type": "VoIP",                   
            "phone_number": "+8618012121222"       
        },
        "text": "Hello world!",                       // Textual content of the message
        "media": [                                    // Media content of the message
            {
                "content_type": null,                 // Media type
                "sha256": null,                       // SHA256 value of the media content
                "size": null,                         // Media file size
                "url": "https://docs.example.yeastarcloud.com/profile_images/1142168442042118144/AW3F4fFD_400x400.png"  // URL pointing to the media content
            }
        ],
        "to": [                                       // Message recipient's information
            {
                "carrier": "T-MOBILE USA, INC.",     
                "line_type": "Wireless",            
                "phone_number": "+8618012121223",    
                "status": "queued"                  
            }
         ],
        ...
        } 
}
Error response
If the API request fails, Service Provider should return the error information in the response according to the following format.
Parameter Type Description
code String Error code.
title String Error type (Customizable).
detail String Detailed information of the error (Customizable).
The following example shows a response of a failed message sending request.
HTTP/1.1 400 Bad Request
{
    "errors": [
        {
            "code": "10001",     
            "title": "Invalid 'to' address",    
            "detail": "The 'to' address should be a single valid number."
        }
    ]
}
Exceptions and troubleshooting
If message delivery fails, an error prompt will be displayed on the PBX user's Linkus client. Service Provider can troubleshoot the cause of the anomaly by checking the error code and response body.
  • Error code

    The table below lists the error codes defined in the PBX.

    Error Code Error Message Description
    10001 channel.ErrInvalidPhoneNumber Invalid phone number.
    10002 channel.ErrInvalidParam Invalid parameter in the request.
    10003 channel.ErrUnsupportMedia Resource type not supported (MMS).
    10004 channel.ErrAuthFail Authentication failed.
    10005 channel.ErrAuthFail No permission.
    10006 channel.ErrTooManyRequest Too many requests.
    10007 channel.ErrServiceUnavailable Service unavailable on recipient's platform.
    10008 channel.ErrExceedsSizeLimit File size exceeds the limit.
  • Exceptions

    The table below lists the possible error prompts and their trigger conditions.

    Error Prompt Trigger Condition
    Failed to send
    • Service Provider does not return a data.id.
    • Service Provider returns HTTP status code 404, prompting service not found.
    • Message delivery fails, and Service Provider returns error information according to the format defined by the PBX, which will be displayed in the error prompt.
    • Message delivery fails, and Service Provider does not return error information or the returned response body is not in JSON format.
    Authentication Failed
    • Service Provider returns HTTP status code 401.
    • Service Provider returns error code 10004 or 10005.
    Recipient Platform Service Unavailable
    • Service Provider returns HTTP status code 403.
    • Service Provider returns error code 10007.
    Invalid Phone Number Service Provider returns error code 10001.
    Invalid Parameter Service Provider returns error code 10002.
    This type of message is not supported due to the restriction of the recipient platform. Service Provider returns error code 10003.
    Too frequent operations. Please try again later. Service Provider returns error code 10006.
    The file size exceeds the limit of the recipient's platform. Service Provider returns error code 10008.

Receive messages from Service Provider

PBX can receive messages from external message sender via a phone number provided by the Service Provider. When an external message sender sends a message to the phone number, Service Provider can send a request to PBX's webhook URL, so as to deliver this message to PBX.

Interaction flow
The process of receiving a message from Service Provider is shown below:

  1. An external message sender sends a message.
  2. The Service Provider should initiate a request to the PBX's webhook URL, with the inbound message attached in the request body and a SHA256 signature included in the request header.
  3. Upon receiving the webhook request, PBX verifies the signature by using the secret provided by Service Provider to calculate a SHA256 signature based on the received webhook request body, then compares the result with the signature extracted from the request header.

    If the signatures match, it indicates that the webhook request is valid, and PBX will return a status code 204 to the Service Provider.

  4. PBX delivers the message to the PBX user.
Webhook request sent by Service Provider

Below is the structure and explanation of the webhook request that Service Provider should send for message delivery.

Request method
POST
Request URL
{webhook_url_provided_by_pbx}
For example:
https://docs.example.yeastarcloud.com/api/v1.0/webhook/general/429ced149ff9437695be795aff38407b
Headers
Parameter Type Description
Content-Type String Define the content type of the request payload.

Valid value: application/json

X-Signature-256 String Pass the signature for webhook authentication, where {signature} is the lowercase result generated by encrypting the body content with the Secret using the SHA256 algorithm.

Format: sha256={signature}

Request body
The Service Provider should pass the inbound messages in the request body.
Note: Here only lists the mandatory parameters. Service Provider may extend this message with other data if needed.
Parameter Required Type Description
data.event_type Yes String Event type.

Valid value: message.received.

data.payload.id Yes String Message ID.
Note: The maximum character length is 255.
data.payload.from.phone_number Yes String Phone number of the message sender.
Note: This parameter should be in E.164 format. For example, +8618012121222.
data.payload.to.phone_number Yes String Phone number of the message recipient.
Note: This parameter should be in E.164 format. For example, +8618012121222.
data.payload.text Yes String Textual content of the message.
Important: Either data.payload.text or data.payload.media must be provided.
data.payload.media Yes Array<media> The information and URL pointing to the media content of the message.
Important: Either data.payload.text or data.payload.media must be provided.
data.payload.received_at Yes String The time when the message was received (ISO 8601 format).

Format: YYYY-MM-DDTHH:MM:SS.mmm+/-HH:MM.

Example: 2019-12-09T20:16:07.588+08:00.

data.payload.record_type Yes String Record type.

Valid value: message.

media
Parameter Required Type Description
content_type No String The type of the media file.
Tip: Refer to the Media Types for the corresponding value.
sha256 No String The SHA256 value of the media file.
size No Integer File size.
url Yes String The URL that points to the media file.
Request example

The following example shows a webhook request for Service Provider to send a message to the PBX.

POST /api/v1.0/webhook/general/429ced149ff9437695be795aff38407b HTTP/1.1
Host: docs.example.yeastarcloud.com
Content-Type: application/json
X-Signature-256: sha256={signature}

{
    "data": {
        "event_type": "message.received",
        "id": "b301ed3f-1490-491f-995f-6e64e69674d4",             //Event ID
        "occurred_at": "2019-12-09T20:16:07.588+00:00",
        "payload": {
            "completed_at": null,
            "cost": null,
            "direction": "inbound",
            "encoding": "GSM-7",
            "errors": [],
            "from": {                                             //Sender information
                "carrier": "T-Mobile USA",
                "line_type": "long_code",
                "phone_number": "+8618012121222",
                "status": "webhook_delivered"
            },
            "id": "84cca175-9755-4859-b67f-4730d7f58aa3",         //Message ID
            "media": [{                                           //Media content of the message
                    "content_type": null,
                    "sha256": null,
                    "size": null,
                    "url": "https://pbs.twimg.com/profile_images/1142168442042118144/AW3F4fFD_400x400.png"
                }],
            "messaging_profile_id": "740572b6-099c-44a1-89b9-6c92163bc68d",
            "organization_id": "47a530f8-4362-4526-829b-bcee17fd9f7a",
            "parts": 1,
            "received_at": "2019-12-09T20:16:07.503+00:00",        //The time when the message is received
            "record_type": "message",                              //Record type
            "sent_at": null,
            "tags": [],
            "text": "Hello from PBX!",                             //Textual content of the message
            "to": [                                                //Recipient information
                {
                    "carrier": "PBX",
                    "line_type": "Wireless",
                    "phone_number": "+8618012121223",
                    "status": "webhook_delivered"
                }
            ],
            "type": "SMS/MMS",
            "valid_until": null,
            "webhook_failover_url": null,
            "webhook_url": "http://webhook.site/04bbd2e3-09b5-4c9e-95de-a1debeb9e675"
        },
        "record_type": "event"
    },
    "meta": {
        "attempt": 1,
        "delivered_to": "http://webhook.site/04bbd2e3-09b5-4c9e-95de-a1debeb9e675"
    }
}
Webhook response returned by PBX
The PBX system will return an HTTP status code in the response.
Status Code Description
204 Success.
400 Bad request, returned when the signature is incorrect.

Set up an SMS channel for Service Provider

After Service Provider implements the SMS service integration with Yeastar PBX, PBX administrator can set up an SMS channel on PBX web portal for the Service Provider.

Limitations
Item Limitation
Supported message types The supported message types are determined by the Service Provider.
Important: When sending multimedia messages (such as images), the SMS service provider downloads the files from a link provided by the PBX. Therefore, if you have set Allowed Country/Region IP Access Protection rule, make sure that you have allowed the IP access from the country where the SMS service provider is located, otherwise the file transmission would fail.
File size Max. 100 MB
File retention period 24 hours
Prerequisites
  • Obtain the following information from the Service Provider:
    • API address for verifying authentication
    • API address for sending messages
    • Message sending rate limit
  • Obtain the following information from the Service Provider's customer portal:
    • API key
    • Secret
    • Phone number used for message sending and receiving
      Note: If business needs to communicate with US-based customers, make sure that the phone number has been completed with 10DLC registration to avoid disruption in message delivery.
Procedure
  1. Log in to PBX web portal, go to Messaging > Message Channel.
  2. Click Add > SMS.
  3. In the Authentication tab, complete the following settings.

    • Name: Enter a name to help you identify the channel.
    • ITSP: Select General.
    • API Key: Enter the API key obtained from the Service Provider's customer portal.
    • Secret: Enter the Secret obtained from the Service Provider's customer portal.
    • API Address for Sending Messages: Enter the corresponding API address provided by the Service Provider. For example, https://service-provider.example.com/sendmessage.
    • API Address for Verifying Authentication: Enter the corresponding API address provided by the Service Provider. For example, https://service-provider.example.com/verify.
    • Webhook URL: Copy the webhook URL and paste it in the Service Provider's customer portal.
  4. In the Messaging Settings tab, configure the channel.
    1. In the Message Sending Rate drop-down list, specify the number of messages that PBX can send per second.
      Note:
      • If the number of messages to send exceeds the set value, PBX will arrange the messages in queue and send them at the sending rate.
      • If the sending rate set in PBX exceeds the limit set by the SMS service provider, it may result in message delivery failures. Contact your SMS service provider to confirm the sending rate limit of your account and increase the limit as needed.
    2. Optional: If you want the system to automatically close the sessions that have been inactive for a specific period of time, select the checkbox of Close Session Automatically, then set the timeout in the Session Timeout (Days) field.

    3. In the Number section, click Add to add a message routing rule.

      • Number: Enter the purchased number in E.164 format ([+][country code][phone number]). For example, +14102161183.
      • Destination for Inbound Messaging: Specify the destination of inbound messages from the number.
        Option Description
        Extension If selected, choose an extension from the Extension drop-down list.

        Only the extension user can receive inbound messages from the number.

        Message Queue If selected, choose a queue from the Message Queue drop-down list.

        All the agents in the selected message queue can receive inbound message(s) of new sessions in the queue. However, only the user who picks up a session will be able to receive and respond to the follow-up inbound messages in the session.

      • Extensions allowed to create messaging sessions: Select the extensions that are allowed to initiate a messaging session with customers.
    4. Click Save.
  5. Click Save.
Result
  • A messaging channel for the Service Provider is created successfully. The channel is displayed in the Messaging list with Status showing .

  • PBX automatically tracks and records the number of messages sent and received on the channel, where the Total column indicates the total number of sent messages, including both successfully sent messages and failed ones.
    Note:
    • For sent messages, PBX only tracks the number of the messages sent from agents' Linkus UC Clients. If you want to calculate the actual cost of sent messages, consult with the SMS service provider for the precise number of messages transmitted, as long text messages (longer than 160 characters) are automatically split into segments and then re-assembled when they are received, increasing the number of sent messages.
    • You can filter the statistics by a time period using the time filter.
What to do next
Send text messages to the phone number added in the channel, and see if the specified PBX user can receive messages on his or her Linkus UC Client.