TaCode Tuesdays:  How to Use Zang to Create Automated SMS Alerts & Prevent Credit Card Fraud

TaCode Tuesdays:  How to Use Zang to Create Automated SMS Alerts & Prevent Credit Card Fraud

Welcome back to TaCode Tuesdays! This is the only place you can find snippets of code for use in your very own text/voice apps, along with a weekly dose of taco puns. I’m a developer here at Zang and not only am I a big fan of tacos (if that wasn’t already apparent), I’m also a fan of open source. My goal is to share a new app idea each week that you’re free to use “as is” or modify and use as the basis for your next app.
If you follow this series, you know I’m dedicated to preventing fraud. If you want to protect your users from fraud, my articles are great resources. Here’s one I wrote a few weeks ago about fraud control in voice and SMS apps that you can use to prevent.

Let’s Taco ’bout Fraud

In 2014, credit card fraud affected 12.7 million customers, with losses exceeding $16 billion. Forty-five percent of this fraud occurs online; 37 percent from counterfeit cards and 14 percent due to lost or stolen cards. Fraudsters’ main targets are students, call centers, and mobile transactions. They usually target transactions that occur on mobile devices between 2AM and 6AM, and fraud peaks during the Christmas season. In fact, credit card fraud soars by more than 200 percent during the holiday season.

Types of Credit Card Fraud

Credit card fraud is classified to be either theft/counterfeit or behavioral. The former happens when somebody uses credit that is not theirs – criminals steal information and use the card until it runs out of money or gets blocked. This normally happens in online transactions where no signatures nor physical cards are required. Banks lose money due to “charge backs” – a process where customers are refunded the amount from unauthorized transactions.
The other type of fraud is known as behavioral; it is much the same as theft/counterfeit, except the fraudster makes the transaction looks legitimate. Behavioral fraud can be done online or in a “cardholder present” basis. Since the identity of the customer has been flawlessly copied – neither the bank nor the merchant would suspect that it’s a fake.

How Do Banks Detect Fraud?

Studies suggest that there are a couple ways banks detect fraud. It could be through a simple decision tree or a complex algorithm using artificial intelligence techniques such as genetic programming.
Decision tree techniques work by picturing a literal tree with nodes, edges, and leaves. First you create nodes labeled with attribute names and edges containing attribute values that satisfy a certain condition. Consequently, the leaves contain an intensity factor or ratio of transactions satisfying the conditions set in the nodes and edges over the total number of legitimate transactions.
The more sophisticated method uses genetic algorithm- a logic where all credit card transactions can be simultaneously identified to belong in either suspicious or non-suspicious classes. The algorithm will analyze huge data sets based on certain rules and identify rules with the highest predictability that will tell if transactions are suspicious.

Preventing Fraud Through SMS Alerts

Preventing credit card fraud through SMS complements an already existing fraud prevention model: making banks act faster. This works by having the system push a message to the customer informing them of a suspected transaction so it can be immediately acted on. Through SMS alerts, banks can create a two-way interaction making users participate in their own account monitoring thereby having them more involved in the prevention process.
To trigger an SMS alert, a simple decision tree model can be adopted based on certain patterns such as:

  • Changes in purchase location
  • Types of commonly bought products
  • Average amount spent
  • Spending frequency
  • Purchase patterns
  • Digital transaction patterns

Pattern changes will be analyzed per customer and once a threshold outlier comes up, it will trigger the SMS sending of alerts making the customer act immediately to confirm the suspected fraud.

Creating Your Own SMS Fraud Alert

In this blog, we will teach you how to create your own SMS alert using Zang APIs. Before we start, you should create a business rule that will trigger the SMS notification. It could be anything like the patterns mentioned earlier; but for the purpose of this tutorial we will start with a simple one – an average minimum and maximum spend of a customer based on previous transactions for the past 12 months.
Using customer data for the past 12 months seems more appropriate, as purchase patterns may change through time as the customer ages or reaches certain life milestones like graduating from college, getting a new job, moving to a different state, getting married, retiring, etc.
Here are the basic programming requirements:

  • Intermediate skills of any .NET framework. For this tutorial, we used Mono.
  • Intermediate knowledge of SQLite. You can download it for free here.
  • Knowledge of JSON data format and RESTful API connectivity.
  • Zang subscription. Don’t have one yet? It’s free, get one here.
  • A phone number that will send out the message. You can also get one through Zang.
  • Working knowledge of Zang APIs.


Let’s start coding!

Step 1: We need to install SQLite for OSX to create a database. Here are the steps:

  • At a terminal window or DOS prompt, enter: “sqlite3 SqliteTest.db”.
  • This will create a new database named “SqliteTest.db”. (You can use a different name if you like.) To create a table, the following attributes need to be specified:  
    • table name
    • the database to which the table belongs
    • the name of each column
    • its data type
    • a column constraint
    • the primary key of the table
    • the WITHOUT ROWID table
  • After this, enter SQL commands at the prompt to create and populate the new database.


Step 2: Using SQLite create an “average customer-spend” tablein your existing database that will store the minimum and maximum spend of each customer and its corresponding threshold. Your table should look something like this:

Step 3: Create a program that will look at the “average customer-spend”
table every time a request to validate credit card transaction is made.

using System;

using System.Collections.Generic;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Data;

using Mono.Data.SqliteClient; //include SQLite


namespace ZangConsoleProgram


   public class DataObject

   { //set your getter and setter

       public string Name { get; set; }



   public class ClassZang


//example rest api url for getting information         

private const string URL     = “{https://your.domain.com/api/record}”; // listen to trigger from the credit card transaction API

       private string urlParameters = “{?api_key=xYzvBnMkLo}”; //security authentication

// initialize the c# command line

       static void Main(string[] args)


//instantiate your api client via the HttpClient class

           HttpClient client = new HttpClient();

           client.BaseAddress = new Uri(URL);


           // Add an Accept header for JSON format.


           new MediaTypeWithQualityHeaderValue(“application/json”));


           // List data response.

           HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call!

           if (response.IsSuccessStatusCode)


               // Parse the response body. Blocking!

               // get the value and

               var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;

               foreach (var d in dataObjects)


                   //Console.WriteLine(“{0}”, d.Name);






               Console.WriteLine(“{0} ({1})”, (int)response.StatusCode, response.ReasonPhrase);



//implementation of function RecordCheck

       private static void RecordCheck(int id, int amount)

       {  //initiliase calle to SQLite database

           const string connectionString = “URI=file:SqliteTest.db”;

           IDbConnection dbcon = new SqliteConnection(connectionString);


           IDbCommand dbcmd = dbcon.CreateCommand();

    //create your sql string

           const string sql =

               “SELECT *  ” +

               “FROM table_customer” +

               “WHERE table_customer.id=” + id ;

//assign sql

           dbcmd.CommandText = sql;

//execute sql call

           IDataReader reader = dbcmd.ExecuteReader();

 //if record not empty

           if (reader.Read()) {

               for (int i = 0; i < reader.FieldCount; i++) {

//iterate into the database table field

                  int transactionAmt = SqlReader.GetInt32(‘MAX_SPEND’) ;

                  if (amount > transactionAmt) {


                  } else {





           } else {




      // clean up








Step 4: If the transaction is beyond the maximum spend, trigger the SMS notification by invoking the Zang Send SMS API.


       private static void transactionLimitReach()


//build HttpWebRequest url           

var httpWebRequest = (HttpWebRequest)WebRequest.Create(“{https://api.zang.io/v2/Accounts/:AccountSid/SMS/Messages.json}”);

//set data format content type in our case its JSON

           httpWebRequest.ContentType = “application/json”;

//set HTTP POST method

           httpWebRequest.Method = “POST”;

//invoke the streamWriter class to instantiate and initialize the Zang JSON string

           using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))


               string json = “{“api_version”:”v2″,” +

                 “”sid”:”{SmsSid}”}” +

                 “”account_sid””:”{AccountSid}”}” +

                 “”date_created”:”Tue, 24 Jul 2012 14:08:23 +0000″}” +

                 “”date_updated”:”Tue, 24 Jul 2012 14:08:24 +0000″}” +

                 “”date_sent”:”Tue, 24 Jul 2012 14:08:24 +0000″”}” +

                 “”to”:”+17325551234″}” +

                 “”from”:”+14245551234″}” +


                 “”status”:”sent”}” +

                 “”price”:”0.070000″}” +



               streamWriter.Write(json); //build the json

               streamWriter.Flush(); //cleanup and exit



//get response from the Zang server

           var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

           using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))


               var result = streamReader.ReadToEnd();

// values from the ‘result’ are set




Step 5: Allow the customer to authorize or block the transaction by replying YES or NO.
The user can reply through their mobile a simple YES or NO to have a flagged transaction push through or stopped.  The user will send the message to the number you initially purchased from Zang. To find out how to set-up your phone number, contact us for free assistance.
Step 6: Process the customer response by sending an authorize or block transaction status to the application module handling payment validations. Note that in order for you to process the customer response of YES or NO, you must be able to set-up your own SMS filtering solution.  This API feature of Zang allows developers to set behaviors to pre-defined user replies. Recipient answers are initially limited to: STOP, QUIT, UNSUBSCRIBE, START, YES, SUBSCRIBE, and HELP until yours has been set-up. If you need further information how to use Zang’s SMS filtering solution, just send us a quick message or subscribe so that we can inform you once that tutorial is out.
Some Things to Remember

Zang APIs are technology agnostic, so if your system is not built on .NET you can still use the same API to send an SMS alert. You can also develop more sophisticated business rules using genetic algorithm analyzing big data. This is more appropriate in scaled-up fraud prevention efforts and are generally faster than decision trees.  So, that’s it for our tutorial this week. If you need help implementing the code to your specific project, you can always email us at support@zang.io or reach out to us on chat.


Views All Time
Views All Time
Views Today
Views Today