unit com.freesmsgateway.api_send;
interface
uses
Service.SmsGateway;
type
TSmsGateway =
class( TInterfacedObject, ISmsGateway )
// Keine Magic Numbers/Values im Code
// sondern als Konstanten definieren
private const
C_APIURL = '
http://www.freesmsgateway.com/api_send';
C_ACCESSTOKEN = '
access_token';
C_MESSAGE = '
message';
C_MESSAGE_MAXLENGTH = 160;
C_SENDTO = '
send_to';
C_CONTACTS_EXISTING = '
existing_contacts';
C_CONTACTS_POST = '
post_contacts';
C_RESPONSE_OK = '
Message sent';
private
FAccessToken :
string;
public
constructor Create(
const AAccessToken :
string );
procedure SendMessage(
const APhoneNumber, AMessage :
string );
overload;
procedure SendMessage(
const APhoneNumbers :
array of string;
const AMessage :
string );
overload;
end;
implementation
uses
System.Classes, System.SysUtils,
Data.DBXJSON,
IdException, IdHTTP;
function JSONStrArray(
const AStrArray :
array of string ) :
string;
var
LIdx : Integer;
LResult : TJSONArray;
begin
LResult := TJSONArray.Create;
try
for LIdx := Low( AStrArray )
to High( AStrArray )
do
begin
LResult.Add( AStrArray[LIdx] );
end;
Result := LResult.ToString;
finally
LResult.Free;
end;
end;
{ TSmsGateway }
constructor TSmsGateway.Create(
const AAccessToken :
string );
begin
inherited Create;
{ TODO :
Validierung AAccessToken
sonst EArgumentException werfen }
if ( AAccessToken = '
' )
then
raise EArgumentException.Create( '
AccessToken muss angegeben werden' );
FAccessToken := AAccessToken;
end;
procedure TSmsGateway.SendMessage(
const APhoneNumber, AMessage :
string );
begin
SendMessage( [APhoneNumber], AMessage );
end;
procedure TSmsGateway.SendMessage(
const APhoneNumbers :
array of string;
const AMessage :
string );
var
LParams : TStringList;
LHttp : TIdHttp;
LResponse :
string;
begin
{ TODO :
Validierung APhoneNumbers:
- gültige Telefon-Nummern
sonst EArgumentException werfen }
if Length( APhoneNumbers ) = 0
then
raise EArgumentOutOfRangeException.Create( '
Telefonnummer fehlt' );
{ TODO : alternativ in mehrere Nachrichten aufteilen }
if Length( AMessage ) > C_MESSAGE_MAXLENGTH
then
raise EArgumentException.CreateFmt( '
Nachrioht darf max. %d Zeichen beinhalten', [C_MESSAGE_MAXLENGTH] );
LParams :=
nil;
LHttp :=
nil;
try
LParams := TStringList.Create;
LParams.Values[C_ACCESSTOKEN] := FAccessToken;
LParams.Values[C_MESSAGE] := AMessage;
LParams.Values[C_SENDTO] := C_CONTACTS_POST;
LParams.Values[C_CONTACTS_POST] := JSONStrArray( APhoneNumbers );
LHttp := TIdHttp.Create(
nil );
try
LResponse := LHttp.Post( C_APIURL, LParams );
except
on E : EIdException
do
raise ESmsGatewayProtocolException.CreateFmt( '
FreeSMSGateway.com: (%s) %s', [E.ClassName, E.
Message] );
end;
if not LResponse.EndsWith( C_RESPONSE_OK )
then
raise ESmsGatewayApiException.CreateFmt( '
FreeSMSGateway.com: %s', [LResponse] );
finally
LHttp.Free;
LParams.Free;
end;
end;
end.