Friday, July 4, 2008

Vonage calling from ObjectPascal

Last week, a customer asked if he could call using his Vonage phone to call from an application I developed some time ago. After searching for a way to do this, I stumbled upon this tutorial, then adapted the examples to ObjectPascal.

The results

The first problem I found was how to connect to an HTTPS site. Of course the answer was Synapse with the help of OpenSSL libraries.

I created couple of small functions that first log in to a Vonage account, then place the call. The functions are contained in this unit:

unit vonagecall;

interface

(* Calls to Vonage phone *)
function CallToVonage(AUserName, APassword, AFromNumber, AToNumber: string): string;

implementation

uses
Classes,
ssl_openssl,
httpsend;

function GetVonageNumbers(AUserName, APassword: string): string;
(* This function must be allways called from CallToVonage *)
var
lHttp: THTTPSend;
lParams: string;
lResponse: TStringStream;
begin
Result := '';
lHttp := THTTPSend.Create;
lResponse := TStringStream.Create('');
try
lParams := 'username=' + AUserName;
lParams := lParams + '&password=' + APassword;
(* Get Phone numbers *)
lHttp.HTTPMethod('GET', 'https://secure.click2callu.com/tpcc/getnumbers?' + lParams);
lHttp.Document.SaveToStream(lResponse);
Result := lResponse.DataString;
if Pos(':', Result) > 0 then
Result := 'Failed to retrieve Vonage phone numbers. Check your username and password.';
finally
lResponse.Free;
lHttp.Free;
end;
end;

function CallToVonage(AUserName, APassword, AFromNumber, AToNumber: string): string;
(* This makes the real call *)
var
lHttp: THTTPSend;
lParams: string;
lResponse: TStringStream;
begin
Result := '';
lHttp := THTTPSend.Create;
lResponse := TStringStream.Create('');
try
lParams := 'username=' + AUserName;
lParams := lParams + '&password=' + APassword;
lParams := lParams + '&fromnumber=' + AFromNumber;
lParams := lParams + '&tonumber=' + AToNumber;
GetVonageNumbers(AUserName, APassword);
lHttp.HTTPMethod('GET', 'https://secure.click2callu.com/tpcc/makecall?' + lParams);
lHttp.Document.SaveToStream(lResponse);
Result := lResponse.DataString;
finally
lResponse.Free;
lHttp.Free;
end;
end;
end.


The unit requires you to deploy libeay32.dll and ssleay32.dll, you can download these files from OpenSSL.org project. There are Windows and Linux versions.

To use it, just include the vonagecall unit in the uses of your program and call the function CallToVonage passing UserName, Password, FromNumber and ToNumber parameters.

In this zip file, I packaged everything you need to test the function.

Hasta la próxima!

No comments: