Sending texts/SMS from an Xbase++ application

I Love Xbase++ (ILX)
The portal for Xbase++ developers worldwide

Till Warweg

Member
Staff member
I am here to help you!
Feb 1, 2021
38
11
8
Customer Identifier
E074775

Background​

Sending text messages often is a good way of informing users or staff about certain events occuring in an application, especially if the message must reach an addressee who is on the move. Since texts are sent directly to the phone number of the target device, they have a higher probability of being read than e-mails, which may not be configured on a mobile phone.

This article outlines the basic steps required for sending texts from within an Xbase++ application. The code uses the websms Short Message Service (SMS) services provided by link mobility, which allow sending world-wide texts using a REST API. Other services could be used too, of course. The required steps should be similar to those described in this article.

Step 1: Create an account with a SMS service provider​

As a first step, we'll need to sign up for an account with a SMS service provider, which will provide us with a phone number and the required infrastructure for sending texts. For simplicity, we'll use a websms/link mobility demo account here. The account will be valid for 14 days and will allow us to send 50 texts, which should be enough for testing.

Go to this page to sign up for a demo account: https://account.linkmobility.eu/#/

Once you've provided the necessary details, you'll be asked for a phone number to be used as the destination for your texts. This is a requirement for demo accounts only.

Step 2: Create an API/access token​

The client application will need to authenticate itself to the websms service in order to be able to access its infrastructure. It does this by providing an API or access token, which you'll need to set up beforehand in your link mobility account.

1728378680214.png

Note the API/access token. It must be provided when connecting to the "websms" service and hence must be specified in the code below.

Step 3: Construct the text message and send it​

Sending a text message is fairly easy using the WebSmsClient class whose implementation is shown later in this article. The class' interfaces hide the internals of dealing with the REST API and provide an abstract and simple to use interface for sending texts.
Xbase++:
// PUT YOUR API TOKEN HERE!
// See websms admin interface -> api management -> api tokens
#define API_TOKEN    "5d434b88-..."

PROCEDURE Main()
 LOCAL oC

   oC := WebSmsClient():new( API_TOKEN )

   // Enable test mode to instruct the system to process the
   // request but refrain from actually sending messages.
   // Useful for saving credits while testing
   // oC:setTestMode( .T. )

   // Provide the addressee's phone number in international format
   oC:addRecipient( "+49......." )
   lSuccess := oC:sendSMS( "Test message" )
   IF !lSuccess
      // See the implementation section for error code definitions
      nError := oC:getLastError()
      ? "An error occured: ", nError
      ...
   ENDIF
   ...
RETURN

That's it! If all went well, you should receive a text on your mobile phone when executing the above code with your phone number. Remember that this number must be registered with the websms/link mobility service when using a trial account!

Implementation of the "WebSmsClient" class​

Xbase++:
#define SERVICE_URI  "https://api.linkmobility.eu/rest/"

CLASS WebSmsClient
 PROTECTED:
   VAR    _client
   VAR    _recipients
   VAR    _testMode
   VAR    _lastError

 EXPORTED:
   METHOD init()

   METHOD addRecipient()
   METHOD clearRecipients()

   METHOD setTestMode()
   METHOD getLastError()

   METHOD sendSMS()
ENDCLASS

/// <summary>Initialize the websms client</summary>
/// <param name="cAPIToken">
/// API/access token created in the "websms" admin interface
/// </param>
METHOD WebSmsClient:init( cAPIToken )
   ::_client := HttpClient():new( SERVICE_URI + "smsmessaging/text" )
   ::_client:setMethod( "POST" )
   ::_client:httpRequest:setContentType( "application/json" )
   ::_client:httpRequest:setAcceptType( "application/json" )
   ::_client:httpRequest:setHeader( "Authorization", "Bearer " + cAPIToken )

   ::_testMode   := .F.
   ::_recipients := {}
   ::_lastError  := 0
RETURN self

/// <summary>Add a recipient for the text message</summary>
/// <param name="cRecipient">
/// The recipient's phone number
/// </param>
METHOD WebSmsClient:addRecipient( cRecipient )
   AAdd( ::_recipients, cRecipient )
RETURN self

/// <summary>Clear the list of recipients</summary>
METHOD WebSmsClient:clearRecipients()
   ::_recipients := {}
RETURN self

/// <summary>Send a text message to the list of recipients</summary>
/// <param name="cText">
/// The message text
/// </param>
/// <returns>.T. if the message was sent. .F. otherwise</returns>
METHOD WebSmsClient:sendSMS( cText )
 LOCAL msg

   // Construct a SMS message and transfer it with the request as
   // a JSON object. Only the required properties are set here.
   // Additional message properties may optionally be specified,
   // such as the validation period, sender address (type), content
   // category etc.
   IF Empty(cText) .OR. Len(::_recipients) == 0
      RETURN .F.
   ENDIF

   msg := DataObject():new()
   msg:messageContent := Char2UTF8( cText )
   msg:recipientAddressList := ::_recipients
   msg:test := ::_testMode

   cContent := Var2JSON( msg )
   ::_client:httpRequest:setContent( cContent )
   ::_lastError := 0
   cResult := ::_client:send()

   IF ::_client:getStatusCode() != 200
      // Infrastructure/protocol error
      RETURN .F.
   ENDIF

   // Check and store the status code of the operation for retrieval
   // via :getLastError(). See https://developer.websms.com/rest-api/smsmessaging_simple_get/
   // for the defined status/error codes. Here, we'll just check
   // whether the operation succeeded.
   oResult := JSON2Var( cResult )
   IF .NOT. oResult:statusCode $ {2000, 2001}
      ::_lastError := oResult:statusCode
      RETURN .F.
   ENDIF
RETURN .T.

/// <summary>Get the error code of the last operation, if any</summary>
/// <returns>0 for "no error", or one of the defined error/status codes
/// >= 4000 from https://developer.websms.com/rest-api/smsmessaging_simple_get/
/// </returns>
METHOD WebSmsClient:getLastError()
RETURN ::_lastError

/// <summary>Enable or disable test mode. If enabled, requests are
/// processed, but no text message is actually sent.</summary>
/// <param name="lMode">
/// .T. for enabling text mode, .F. to disable it
/// </param>
METHOD WebSmsClient:setTestMode( lMode )
   ::_testMode := lMode
RETURN self
 
Last edited:

Osvaldo Luis Aoki

New member
I am using always the latest Xbase++ build
Oct 20, 2022
2
0
1
Brazil
Customer Identifier
A088009
HI,
I just attempt to register Free trial for tests but it cause an erro on confirmation....Look for image attached
 

Attachments

  • 2024-10-10 19_20_07-LINK Mobility Registration e mais 1 página - Pessoal — Microsoft​ Edge.png
    2024-10-10 19_20_07-LINK Mobility Registration e mais 1 página - Pessoal — Microsoft​ Edge.png
    110 KB · Views: 77

Till Warweg

Member
Staff member
I am here to help you!
Feb 1, 2021
38
11
8
Customer Identifier
E074775
Dear Osvaldo,

Please check with link mobility to find out what's going wrong. Perhaps they want you to use a different login site or use a different procedure for your country?