Vous êtes sur la page 1sur 30

CHAPTER ONE

1. INTRODUCTION

1.1  How M­PESA Works

M­Pesa is Safaricom's  low cost money transfer service that enables users to send and receive 
money through their mobile phones. M­PESA allows users an affordable, fast, convenient, and safe 
way to transfer money through mobile phones anywhere in Kenya. Through M­PESA users are able 
to deposit and withdraw money, send money to another M­PESA customer.

The service works on new generation SIM cards with a SIM Application Tool Kit (STK). For users 
to access this service, all they have to do is register at any authorized M­PESA agent for free, by 
providing them with their Safaricom mobile number and their national Identification Card and once 
registered, customers are given an M­PESA enabled SIM card, which will allow them to put money 
into their account by depositing cash with an authorized agent.

It is of importance to note that the M­PESA Application is a SIM initiated application since the it 
resides within the SIM Card. Authentication Information also resides within the SIM and is 
checked against the Home Location Register (HLR) ­  database at the Service Provider which stores 
data about GSM subscribers, including the Individual Subscriber Authentication Key (Ki) for each 
Subscriber Identity Module (SIM). 

M­Pesa users are be able to withdraw cash after receiving an SMS, informing them of the 
transaction. Users can deposit their money with authorized agents and withdraw from the same 
agents. Users are be allowed a maximum of Kshs 35,000 and a minimum of Kshs 100 for each 
transaction.

Fig 1.1: Cash withdrawal process for M­PESA

1
1.2  M­Pesa System Architecture : Limits and Capabilities
The architecture on which M­PESA application operates provides few possibilities when it comes 
to Transaction Logging.2

Figure 1.2 Data Exchanged between SIM and Phone via STK before request to GSM Network

When a user accesses the M­PESA menu from the mobile phone, they are prompted tho select the 
particular M­PESA Service which they intend to use and information is collected on the transaction 
details. Once sufficient information is gathered including Authentication information, an encrypted 
USSD Session is began between the SIM Card and the GSM Network independent of the Handset.

This means that information gathered is relayed to the GSM network without necessarily being 
accessible to the ME (Mobile Equipment). Once the information request is relayed to the GSM 
Network, a Mobile Service Node (MSN) ­ A network element which provides mobile intelligent 
network (IN) services directs the request to the appropriate server and the session is closed or kept 
open depending on the nature of the service.

Table 1: Technologies Employed in Mobile Money Transfer Services

2
1.3 M­PESA Transaction Logging System Scope and Implementation

The only instance at which the ME gets access to the information of the transaction is when the 
User receives a comfirmatory summarising the transaction that was carried out. If, for instance, one 
had received cash, the summary will contain only critical information regarding the transaction.

“S98GE969 Confirmed. You have received Ksh3000 from JOHN DOE 254700123456 On 8/5/10 at 
10:22 AM New M­Pesa balance is Kshs. 3002.” : ­  SENDER : M­PESA

Where: S98GE969 : Transaction Code


Ksh3000 : Transaction Amount
JOHN DOE : Sender
254700123456: Sender Number
Ksh3002 : New M­PESA Balance

With such information aquired when one receives money via M­PESA it is now possible to extract 
this information for Transaction Logging on a computer through 'Parsing' the Short Message 
confirmation.

It is important to note that this transaction was initiated by the sender and thus the receiver's SIM 
module need not have been within a mobile handset to  receive the confirmatory message. If the 
transaction were a withdrawal, however, first the transactiaon has to be initiated from the STK 
Menu by the user (only accessible via a Mobile Handset) and the SIM Module transferred to a 
GSM Modem so that the transaction can be logged on the PC. This may require the transactions to 
be logged in batches on a daily basis which may be cumbersome.

This project explores Transaction Logging for M­PESA transactions whereby an 
individual/business requires to log received amounts of money from different customers. The 
system goes further to make use of this data in an Online Store where the customer has pre­ordered 
goods/services and reconciles the two records of the Customers Accounts.

3
CHAPTER TWO

2. TECHNOLOGIES EMPLOYED

This chapter summarises all the technologies required to build a database driven M­Pesa Transaction 
Logging System. These technologies, both hardware and software, have been specifically chosen to be 
relatively accessible within a modest budget and offer sustainable effeciency.

2.1 HARDWARE

2.1.1Standard GSM Modem

A GSM modem can be an external device or a PC Card / PCMCIA Card. Typically, an external 
GSM modem is connected to a computer through a serial cable or a USB cable. Like a GSM mobile 
phone, a GSM modem requires a SIM card from a Service Provider in order to operate. A GSM 
modem is the preferred device in comparison to a GSM mobile phone since they have a standard 
interface, have basic required functionality, are comparatively cheaper and connect to a standard 
USB 2.0 port without the need for an external power input.
GSM modems accept the  common set of standard AT commands*1. In addition to the standard AT 
commands, GSM modems support an extended set of AT commands. These extended AT 
commands are defined in the GSM standards. With the extended AT commands, you can do things 
like:
• Reading, writing and deleting SMS messages.
• Sending SMS messages.
• Monitoring the signal strength.
• Monitoring the charging status and charge level of the battery.
• Reading, writing and searching phone book entries.
The number of SMS messages that can be processed by a GSM modem per minute is relatively low 
­­ only about twenty SMS messages per minute. There are however advanced types of GSM 
Moidems that support larger volume transactions designed specifically for this purpose and are the 
type deployed by Premium Rate Service Providers at the server back­end.
2.1.2 Personal Computer or Laptop
A low end PC (Intel Pentium III/IV) that has a Database and Database Management System 
(DBMS) installed is suffecient to collect information from the GSM Modem. It is also important 
that this computer have a fast USB 2.0 port since the data transfer rate is crucial to the effeciency of 
the system. Older USB 1.1 ports are growing obsolete but can be acceptable for prototyping 
purposes.

1 AT commands are instructions used to control a modem. AT is the abbreviation of ATtention. Every command line starts 
with "AT" or "at". That's why modem commands are called AT commands. These are discussed in the appendix.

4
2.2 SOFTWARE
2.2.1 Database Management System
A relational database management system (RDBMS) is an essential tool in many environments, 
from traditional uses in business, research, and educational contexts. However, despite the 
importance of a good database system for managing and accessing information resources, many 
organizations have found them to be out of reach of their financial resources.
Small desktop systems and servers are inexpensive but powerful, and there is a thriving movement 
devoted to writing high­performance operating systems for them.These operating systems such as 
the one used for this Project are available free over the Internet or at the cost of an inexpensive CD.
Database software has become more accessible, too, and Open Source database systems are freely 
available. One of these is MySQL, a SQL client/server relational database management system 
originating from Scandinavia. MySQL includes an SQL server, client programs for accessing the 
server, administrative tools, and a programming interface for writing programs. 
2.2.2 The LAMP Environment
Linux, Apache WebServer, MySQL and PHP, and Cascading Style Sheets
PHP is a programming language designed to generate web pages interactively on the computer 
serving them, which is called a web server. Unlike HTML, where the web browser uses tags and 
markup to generate a page, PHP code runs between the requested page and the web server, adding to 
and changing the basic HTML output. These provide the main interface for the user to view 
information from the database.
Apache is a web server that turns browser requests into resulting web pages and knows how to 
process PHP code. PHP is only a programming language, so without the power of a web server like 
Apache behind it, there would be no way for web users to reach pages containing the PHP language 
code. 
While PHP is great for web application development, it doesn’t store information by itself. For that, 
one need a database. The database of choice for PHP developers is MySQL, which acts like a filing 
clerk for PHP­processed user information. MySQL automates the most common tasks related to 
storing and retrieving specific user information based on the supplied criteria. 
Cascading Style Sheets (CSS) pull presentation information out of  HTML and into a single spot so 
that one can make formatting changes across an entire set of pages all at once .
Since the M­PESA Transaction Logging System can be extended to an Online M­PESA Transaction 
Logging System, this environment is most appropriate to develop the first prototype of the system 
on an off­line machine.
2.2.3 Gnokii Application Programming Interface
Gnokii is a free and open source Application Programming Interface that provides tools and a user 
space driver for use with GSM mobile phones and/or GSM modems under various operating 

5
systems.
Gnokii provides source code written in C and employs the use of AT Commands. Once installed and 
configured, Gnokii is used to set up polling between the computer and the GSM modem. The 
computer is said to 'listen' for requests from the modem and send requests via the AT Command Set.
2.2.4 CronTab
Cron is a Unix Deamon*2 used to execute scheduled tasks. Cron searches its spool  area  (/var/spool/
cron/crontabs) for crontab files (which are named after accounts in /etc/passwd) crontabs found are 
loaded into memory. 
A Crontab basically contains information about an event which is scheduled to occur at a given time 
on a Unix Machine. In our case crontab is used to schedule how often the database is checked for 
updates and how often the updates are parsed. This scheduled task is however different to polling 
which is done to check whether an SMS has been received by the GSM Modem and so that it can be 
inserted into the databse. This polling is already taken care of by the Gnokii API. 

2 (From the mythological meaning, later rationalised as the acronym "Disk And Execution MONitor") A program that is 
not invoked explicitly, but lies dormant waiting for some condition(s) to occur. ­­ www.dictionary.net/daemon

6
CHAPTER THREE

3. TRANSACTION LOGGING
Once all the technologies described in chapter two above are set up, the project implementation.
3.1 Setting Up the Database
A database named 'mpesa' with the first table as 'inbox' was created database to store incoming 
messages and to parse them. Parsing means sorting variables with a particular criteria. The figure 
below shows the 'inbox' table and the respective fields and attributes

Fig3.1 'inbox' table with attributed fields

As the first table is required to collect information about incoming SMS messages, there is a 
second table created to recover the parsed values named 'tbl_accounts'.

Fig3.2 'tbl_accounts' table with attributed fields

Extra tables were created for further information manipulation and the attributes are laid out in the 
printed code SQL Dump File. The Entitry Relationship Diagram looks as shown in fig 3.3.

7
Fig3.3 An Entity Relationship Diagram for tables in 'mpesa' database.

The tables created are the basic ones needed to log an incoming SMS Message. A General 
description of each field with the attributes given above is given in the table 3.1 below.

Field Description of content
Table1 'inbox'
Id (index) This is a unique incremental value to distinguish each incoming SMS
number This gathers information on source of SMS,should always be M­PESA
smsdate This is the date when the SMS was received by GSM Modem
insertdate This is date when SMS was inserted into the Database
text This is the actual content of SMS that is to be parsed
phone This is the device through which SMS is received
processed This is a flag showing that the SMS data has been parsed to information
Account (primary) This is account number of sender parsed from 'text' field
amount This is the amount of money received parsed from 'text' field
Table2 'tbl_accounts' 
Account (primary) This is account number of sender stored in database
balance This is the monetary balance of sender's account
names These are names of the Sender, either parsed or retrieved from dBase
od_id (index) This is transaction id field if payment was due

8
Table3.1 General description of key fields in 'inbox' and 'tbl_accounts' tables

3.2 Settign Up SMS Polling
SMS Polling is the process of 'listening' for an incoming SMS Message through the modem by a 
computer application. The Gnokii Application Programing Interface written in C was the preferred 
polling technology of use since it has preset methods of retrieving incoming SMS properties and 
loading these properties into a database.
Installing from Gnokii from binary files in unix is done using apt (Ubuntu) configured for the 
system. 
In Ubuntu the command is
$ sudo apt-get install gnokii gnokii-smsd gnokii-smsd-mysql
This command installs the Gnokii API, Gnokii smsd and Gnokii­smsd­mysql modules.
Gnokii Configuration :
Once gnokii was installed, we changed the configuration file (gnokiirc) and checked whether the 
computer can identify the mobile phone. Since a USB cable was used to connect the modem to the 
computer and set the value of port as “/dev/ttyUSB0”. The model was set as as AT since this 
notifies Gnokii that we are using the AT command set to communicate with the GSM Modem. The 
value of connection was set as serial.
Then after executing the command “gnokii –identify” to test proper connection to the modem, the 
output produced is as shown below signifying a successful connection.
GNOKII Version 0.6.18
IMEI : 352955008063785
Manufacturer : Huawei
Model : AT
Product name : Huawei E220 Modem
Revision : V 4.63
Working with smsd 
Once gnokii was configured, smsd (an daemon like crontab for sms) was used to listen for 
messages. This is more like a wrapper for gnokii. After gnokii­smsd was installed, a database 
called SMS was created in the database. To start the smsd server, the command below was ran
$smsd -m [dbms] -u [mysqluser] -p [mysqlpassword] -d [database]
Once smsd is running, any SMS which comes to theGSM modem is taken by the computer, stored 
in the inbox table and then deleted from the SIM. Similarly any entry added in outbox is sent to the 
destination. An very useful field in these two tables is “processed”. Any message which is added to 
the inbox has a default “processed” value of “0″. Once we are done with this message (ie 
parsing), it changes the value to 1. Any message which is inserted in the outbox has a default 
“processed” value of 0 and “error” value ­1. If the message is sent successfully, the value of 
processed and error is changed to 1 and 0 respectively. 

9
3.3 The SMS Parsing Process
When an SMS message is received by the GSM Modem it is immediately inserted into the 'inbox' 
table of the 'mpesa' MySQL database. This is done by the Gnokii API automatically retreiving the 
all the information for the fields in this table except the 'account' and the 'amount'. The next stage, 
SMS Parsing, is done by the CronTab. Before starting the sms daemon, a 'cronjob' was set up using 
the following command in the terminal
$crontab -e
This command is used to edit the crontab file for the logged in user. The crontab file is used to 
schedule a cron job which takes place at a specific time. The format of scheduling a cron job is as 
follows
[minute] [hour] [dayofweek] [month] [year] [command]
In our case the cronjob was scheduled to take place every minute of every hour of every dayofweek 
of every month of every year as shown below
* * * * * mysql -u [msqluser] -p[mysqlpassword] mpesa<upd.sql
The cronjob set above runs a mysql script called 'upd.sql' on the 'mpesa' database that already has 
all the SMS's received. The MySQL script 'upd.sql' is written as below and stored in the user's 
home folder.
use mpesa;
UPDATE inbox SET number= 'MPESA' WHERE NUMBER='+254751340290';
UPDATE inbox SET text= REPLACE(text,',','');
UPDATE inbox SET account=(SELECT SUBSTRING(`inbox`.`text`,(SELECT
LOCATE('254', inbox.text)),12)) WHERE inbox.number='MPESA';
UPDATE inbox SET amount=(SELECT SUBSTRING(`inbox`.`text`,(SELECT
LOCATE('Ksh', inbox.text))+3,6)) WHERE inbox.number='MPESA';
The script above does alterations on the inbox table in five steps, hence the term 'parsing'.
i. Selects the DataBase to edit as the 'mpesa' database
ii. Updates the prototyping number*3 to 'MPESA'
iii. Removes all the comma's in the 'text' field e.g. Ksh5,000 becomes Ksh5000
iv. Extracts the account number from the 'text' field ie next twelve characters from start of '254'. 
These characters are then inserted into the 'account' field of the inbox table.
v. Extracts the amount received from the 'text' field ie next six digits from the start of 'Ksh'. These 
digits are then inserted into the 'amount' field of the inbox table

3 To build the prototype, the MPESA message that is supposed to originate from the Service Provider was originated from 
a regular GSM Mobile Phone since testing with actual transactions would be costly and impractical.

10
Hence for a sample SMS message such as the one below,
“S98GE969 Confirmed. You have received Ksh3,000 from JOHN DOE
254700123456 On 8/5/10 at 10:22 AM New M-Pesa balance is Kshs.
3,002.”

the fields after parsing would have loaded the values '254700123456' into the 'account' field and 
'3000' into the amount field.

3.4 Logged Output

After logging for a couple of transactions the 'inbox' table's data looked as shown in the figure 3.4 
shown below.

Fig3.4 Data from 'inbox' table of 'mpesa' database after SMS Parsing.

3.5 Account Reconciliation and Synchronization
The data in the 'inbox' table was then ready for use by other tables and could be related to the 
customer register. The 'accounts' table has more information concerning the customer and is related 
to the 'inbox' table by the Primary Key field which is the 'account' field present in both tables. 
Every time the 'accounts' table is accessed by another application a MySQL trigger is run and the 
data is confirmed to be in­sync with that of the 'inbox' table as at the time of access.
Accessing the 'accounts' table had the result below.

Fig3.5 Data from 'tbl_accounts' table of 'mpesa' database after reconciliation.
The new field 'od_id' is a field denoting the identification key of a pre­ordered item by the M­
PESA sender collated with his accoint information. This is discussed further in the next section 
which discusses the implementation of the logging system for a small business.

11
CHAPTER FOUR
4. IMPLEMENTATION
So far, the transaction logging system has not been fully exploited since logging just involves gathering 
data. The organization of this data and making use of it to produce meaningful information is the crux 
of the matter and thus this section explores a possible implementation of the logged information.
Since it employs a MySQL Database that is accessible through PHP, a web­based interface was the best 
way to implement some sort of interaction with the back­end, server­side logging. The implementation 
used is an M­Pesa driven shopping cart, that takes information from the M­Pesa Transaction Logs to 
update customer accounts once the customer has ordered a purchase through the website.

4.1 M­PESA Shopping Cart
The M­PESA online shop that implemented is a basic one without any sophisticated features. The 
shop has administrator pages (where the shop admin can create categories, add products, etc) and 
the shopper pages ( i.e. the shop itself ) where all the shopping process takes place. 
The shopping cart is just part of the shop which can be offline. But because the term 'shopping cart' 
is already common to define an online shop solution it is just used since it could work online, where 
shoppers buy goods online, or offline where shoppers can just call the shop or have a standing order 
for goods and pay for the order through the logging system.
The basic flow of the shop as implemented online is as follows:
1. A customer visits the site 
2. They browse the pages, clicking their way between categories 
3. View the product details that they want to buy.
4. Add products to shopping cart 
5. Checkout ( entering the shipping address and payment information).
6. Leave ( hopefully to return another time).
The customer doesn't need to register for an accountsince the shippin and payment information 
collected during checkout is sufficient. This is the information used to reconcile payments collected 
through the 'table'.

12
4.2 File Organization

The files in the M­PESA Shop are organised as shown in Figure 4.1 below

Fig4.1 M­PESA Shop File Organization

The plaincart/library directory contain :
• config.php : this is the main configuration file for the shop 
• category­functions.php :functions required for fetching the categories 
• product­functions.php : contain product related functions 
• cart­functions.php : shopping cart specific functions 
• checkout­functions.php : checkout processes are in here 
• common.php : common functions required for the shop and admin pages 
• database.php : contain the database abstraction functions 

13
4.3 M­PESA Shopping Cart Database Design
The database design for the M­PESA shopping cart is explained in this section. Below is the 
summary of what tables are needed for this shopping cart plus the short description of each table. 
You can see the complete SQL needed to build the database here
Table Name   Description
tbl_category   Storing all product categories
tbl_product   The products ( what else )
When the shopper decided to put an item 
tbl_cart   into the shopping cart we'll add the item 
here 
tbl_order   This is where we save all orders
tbl_order_item   The items ordered 
tbl_user   Store all shop admin user account
tbl_shop_confi Contain the shop configuration like name, 
 
g address, phone number, email, etc 
Table 4.1 M­PESA Shopping Cart Database Tables Description

The ER ( Entity Relationship ) diagram is shown below.

Fig4.2 ERD Diagram for M­PESA Shopping Cart Database

14
4.4 M­PESA Shop Administration

Administration of the M­PESA Shop accounts and subsequently the Transaction Logs is a secure 
process. All user account information is saved in 'tbl_user'. For simplicity it only contains the bare 
necessities such as user id and password.

This is how the login works

1. The administrator enters username and password 
2. The script check whether that username and password combination do exist in the database 
3. If it is set the session then go the admin main page
4. If it's not then show an error message

Fig4.3 Login page screenshot :

4.5 Order Management

All customer order will be shown under the orders tab in the administration page. The administrator 
can see the orders and take appropriate action. For example all orders initially have the status "New". 
When you pack the product and ship it to the customer after payment has been received via M­PESA 
one can then change the order status to "Shipped". 
The order status are :
• New : All orders initially have this status
• Paid : An order's status is changed from "New" to "Paid" after completing the payment 
process.
• Shipped : After packing ordered items and shipping one can change the order status to 
"Shipped"
• Completed : After the customer receveived the goods that means the order is completed
• Cancelled : Orders that have taken too long to be paid for or cancelled by customer.
Here is what the order page looks like :

15
Figure4.4 Order Management Page

4.6 Payment Processing and Accounts Reconciliation

Using the combo box on the top right corner  one can view the orders with a certain status. Clicking 
on an order number take one to the order detail page. On this page one can also modify the order 
status.

Fig4.5 Order Status Form for Modifying

16
Once a particular order is paid for, the logging system extracts the relevant information from the 
inbox table and reconciles it with the information from the order table. The balance is then fed to the 
accounts table after processing and the processed flag is changed from zero to one.

This process is done by the PHP Script in (/var/www/mpesashop/admin/processMpesa.php) below: 

<?php
//Query to fetch unpaid orders and match accounts
$sql_topay = "SELECT account, o.od_id, SUM(pd_price * od_qty) +
od_shipping_cost AS topay
FROM inbox, tbl_order o, tbl_order_item oi, tbl_product p
WHERE account = od_payment_phone and oi.pd_id = p.pd_id and
o.od_id = oi.od_id
AND od_status = 'new' and processed='0'
GROUP BY o.od_id ORDER BY o.od_id DESC";
$result_topay = dbQuery($sql_topay);

if (dbNumRows($result_topay) > 0) {
$i = 0;
$balance = 0;
while($row = dbFetchAssoc($result_topay)) {
extract($row);
//Query to load received unprocessed amounts
$sql_rcvd = "SELECT SUM(amount) AS rcvd
FROM inbox
WHERE account = ".$account;
$result_rcvd = dbQuery($sql_rcvd);
$row_rcvd = dbFetchAssoc($result_rcvd);
extract($row_rcvd);
//Query to change status of paid amounts
$od_id_change = $od_id;
$sql4 = "UPDATE tbl_order,inbox SET tbl_order.od_status =
'Paid' , inbox.processed='1' WHERE od_id=".$od_id_change;
//Query to load status change if balance cleared
$balance = $topay - $rcvd;
if ($balance <= 0) { $result4 = dbquery($sql4);}
?>
<tr class="row">
<td width="60" align="center"><?php echo $account; ?></td>
<td width="60" align="right"><?php echo displayAmount($topay); ?
></td>
<td width="60" align="right"><?php echo displayAmount($rcvd); ?
></td>
<td width="60" align="right"><?php echo displayAmount($balance);
?></td>

17
<td width="60" align="right"><?php echo $od_id; ?></td>
</tr>
<?php
$i += 1;
}//endwhile
}//endif
?>

18
CHAPTER FIVE 
5. DATA FLOW ANALYSIS

The Figure4.5 below is a data flow diagram illustrating the manipulation of data from the Transaction 
Logging Stage to the M­Pesa Shop Reconciliation Stage.

Fig5.1 System Data Flow Diagram

19
CHAPTER SIX
6. CONCLUSIONS AND RECOMMENDATIONS
6.1 Mobile Vs PC Transaction Logging
The M­Pesa transaction Logging System developed in this project has mainly featured on received 
payments due to the tachnical limitations presented by the M­PESA System Architecture. This 
presents a compromise of functionality as regards the type of logs that can be done on a personal 
computer butis comes at a good price since the loggable data can be used diversly once logged on a 
PC. 
The only other option that would make two­way transactions possible would only be if the logging 
was done on the mobile phone. This is due only to the capability of the mobile phone to access 
both the incoming/outgoing messages and the SIM Application Toolkit, a feature not available to 
the GSM Modem. The disadvantage of logging the information on a mobile phone is that it limits 
the ways in which this data can be accessed and used for different systems e.g. a small business.
6.2 M­PESA Application Programming Interface
As discussed earlier in the abstract of this report, the M­PESA Application runs from the 
Subscriber Identity Module and is initiated from it for security reasons. Safaricom who own this 
application have sole access to the source code of this JavaCard Program and own sole propriety 
rights to it. They offer Premium Rate Service Provider services to parastatals and charge them 
premium amounts for this service leaving out Small and Medium Enterprises who cannot afford to 
pay for premium M­Pesa numbers.
Such a solution as implemented in this project could be far more scalable if Safaricom had 
provided Third Party developers with the STK's source code or even as much as an Application 
Programming Interface to write applications that could pass variables to the STK Application. This 
would enable them to access all of Safaricoms M­Pesa Services and innovate further, the use to 
which these are put without a compromise in security..
6.3 Further Work
Since it was concluded through this project that Transaction Logging can only be completely done 
for Mobile Phone Logging, further work would include developing a mobile phone resident 
application for logging M­Pesa Transactions. This will be limiting use of Logging information to 
Personal use for the account holder, and will still use SMS Parsing as the primary mode of 
gathering information about the account.

20
APPENDICES

APPENDIX A : AT COMMAND SET
The following text lists part of the Hayes command set (also called the AT commands: "AT" meaning 
attention).
The ETSI GSM 07.07 (3GPP TS 27.007) specifies AT style commands for controlling a GSM phone or 
modem. The ETSI GSM 07.05 (3GPP TS 27.005) specifies AT style commands for managing the SMS 
feature of GSM.
Examples of GSM commands:
Command Description
AT+CPIN=1234 Enter PIN code
AT+CPWD="SC","old","new" Change PIN code from 'old' to 'new'
AT+CLCK="SC",0,"1234" Remove PIN code
AT&V Status
ATI Status (Manufacturer, Model, Revision, IMEI, capabilities)
List available networks 0­Unknown/2­Current/3­Forbidden, 
AT+COPS=?
Longname, Shortname, Numerical­ID, "AcT"
Get signal strength. Answer: +CSQ: <rssi (more=better)>, <ber, 
AT+CSQ
less=better>
ATD*99# Dial access point
AT+CGDCONT=1,"IP","access.p
Defines PDP context. [4]
oint.name"

APPENDIX B : GSM SECURITY AND TERMS
Global System for Mobile Communications (GSM) ­ originally from Groupe Spécial Mobile) is the 
most popular standard for mobile telephony systems in the world.
Home Location Register (HLR) ­ A database which stores data about GSM subscribers, including the 
Individual Subscriber Authentication Key (Ki) for each Subscriber Identity Module (SIM). 
Mobile Services Switching Center (MSC) ­ The network element which performs the telephony 
switching functions of the GSM network. The MSC is responsible for toll ticketing, network 
interfacing, common channel signaling. 
Visitor Location Register (VLR) ­ A database which stores temporary information about roaming GSM 
subscribers. 
Authentication Center (AUC) ­ A database which contains the International Mobile Subscriber Identity 
(IMSI), the Subscriber Authentication key (Ki), and the

21
 defined algorithms for encryption.

Authentication key (Ki) ­ The Ki is a 128­bit value used in authenticating the SIMs on the mobile 
network. Each SIM holds a unique Ki assigned to it by the operator during the personalization process.

Equipment Identity Register (EIR) ­ A database which contains information about the identity of 
mobile equipment in order to prevent calls from stolen, unauthorized, or defective mobile stations. 
Message Center (MXE) ­ A network element which provides Short Message Service (SMS), voice 
mail, fax mail, email, and paging. 
Mobile Service Node (MSN) ­ A network element which provides mobile intelligent network (IN) 
services. 
Gateway Mobile Services Switching Center (GMSC) ­ A network element used to interconnect two 
GSM networks. 
GSM Interworking Unit (GIWU) ­ The network element which interfaces to various data networks. 

APPENDIX C : MYSQL DATABASE CREATION SCRIPTS
SMS LOGGING TABLES – smsd.sql
USE mpesa;
CREATE TABLE inbox (
  id int(10) unsigned NOT NULL auto_increment,
  number varchar(20) NOT NULL default '',
  smsdate datetime NOT NULL default '0000­00­00 00:00:00',
  insertdate timestamp DEFAULT CURRENT_TIMESTAMP,
  text text,
  phone tinyint(4),
  processed tinyint(4) NOT NULL default '0',
  PRIMARY KEY  (id)
);
CREATE TABLE outbox (
  id int(10) unsigned NOT NULL auto_increment,
  number varchar(20) NOT NULL default '',
  processed_date timestamp DEFAULT 0,
  insertdate timestamp DEFAULT CURRENT_TIMESTAMP,
  text varchar(160) default NULL,
  phone tinyint(4),
  processed tinyint(4) NOT NULL default '0',

22
  error tinyint(4) NOT NULL default '­1',
  dreport tinyint(4) NOT NULL default '0',
  not_before time NOT NULL default '00:00:00',
  not_after time  NOT NULL default '23:59:59',
  PRIMARY KEY  (id)
);
CREATE TABLE multipartinbox (
  id int(10) unsigned NOT NULL auto_increment,
  number varchar(20) NOT NULL default '',
  smsdate datetime NOT NULL default '0000­00­00 00:00:00',
  insertdate timestamp DEFAULT CURRENT_TIMESTAMP,
  text text,
  phone tinyint(4),
  processed tinyint(4) NOT NULL default '0',
  refnum int(8) default NULL,
  maxnum int(8) default NULL,
  curnum int(8) default NULL,
  PRIMARY KEY  (id)
);

M­PESA SHOP TABLES – plaincart,sql
CREATE DATABASE IF NOT EXISTS mpesa;
USE mpesa;
DROP TABLE IF EXISTS `tbl_cart`;
CREATE TABLE `tbl_cart` (
  `ct_id` int(10) unsigned NOT NULL auto_increment,
  `pd_id` int(10) unsigned NOT NULL default '0',
  `ct_qty` mediumint(8) unsigned NOT NULL default '1',
  `ct_session_id` char(32) NOT NULL default '',
  `ct_date` datetime NOT NULL default '0000­00­00 00:00:00',
  PRIMARY KEY  (`ct_id`),
  KEY `pd_id` (`pd_id`),
  KEY `ct_session_id` (`ct_session_id`)
) TYPE=MyISAM AUTO_INCREMENT=58 ;
DROP TABLE IF EXISTS `tbl_category`;
CREATE TABLE `tbl_category` (

23
  `cat_id` int(10) unsigned NOT NULL auto_increment,
  `cat_parent_id` int(11) NOT NULL default '0',
  `cat_name` varchar(50) NOT NULL default '',
  `cat_description` varchar(200) NOT NULL default '',
  `cat_image` varchar(255) NOT NULL default '',
  PRIMARY KEY  (`cat_id`),
  KEY `cat_parent_id` (`cat_parent_id`),
  KEY `cat_name` (`cat_name`)
) TYPE=MyISAM AUTO_INCREMENT=18 ;
INSERT INTO `tbl_category` (`cat_id`, `cat_parent_id`, `cat_name`, `cat_description`, `cat_image`) VALUES (17, 13, 
'Hunter X Hunter', 'Story about hunter and combat', '');
INSERT INTO `tbl_category` (`cat_id`, `cat_parent_id`, `cat_name`, `cat_description`, `cat_image`) VALUES (12, 0, 'Cars', 
'Expensive and luxurious cars', 'dce08605333d805106217aaab7f93b95.jpg');
INSERT INTO `tbl_category` (`cat_id`, `cat_parent_id`, `cat_name`, `cat_description`, `cat_image`) VALUES (13, 0, 
'Manga', 'It''s all about manga, yay....', '2a5d7eb60c1625144b3bd785bf70342c.jpg');
INSERT INTO `tbl_category` (`cat_id`, `cat_parent_id`, `cat_name`, `cat_description`, `cat_image`) VALUES (14, 12, 
'Volvo', 'Swedish luxury car', '');
INSERT INTO `tbl_category` (`cat_id`, `cat_parent_id`, `cat_name`, `cat_description`, `cat_image`) VALUES (15, 12, 
'Mercedes­Benz', 'Expensive but real good', '');
INSERT INTO `tbl_category` (`cat_id`, `cat_parent_id`, `cat_name`, `cat_description`, `cat_image`) VALUES (16, 13, 
'Naruto', 'This is the story of Naruto and all his gang', '');
DROP TABLE IF EXISTS `tbl_currency`;
CREATE TABLE `tbl_currency` (
  `cy_id` int(10) unsigned NOT NULL auto_increment,
  `cy_code` char(3) NOT NULL default '',
  `cy_symbol` varchar(8) NOT NULL default '',
  PRIMARY KEY  (`cy_id`)
) TYPE=MyISAM AUTO_INCREMENT=5 ;
INSERT INTO `tbl_currency` (`cy_id`, `cy_code`, `cy_symbol`) VALUES (1, 'KSH', 'KSh;');
INSERT INTO `tbl_currency` (`cy_id`, `cy_code`, `cy_symbol`) VALUES (2, 'EUR', '&#8364;');
INSERT INTO `tbl_currency` (`cy_id`, `cy_code`, `cy_symbol`) VALUES (3, 'GBP', '&pound;');
INSERT INTO `tbl_currency` (`cy_id`, `cy_code`, `cy_symbol`) VALUES (4, 'JPY', '&yen;');
INSERT INTO `tbl_currency` (`cy_id`, `cy_code`, `cy_symbol`) VALUES (5, 'USD', '$');
DROP TABLE IF EXISTS `tbl_order`;
CREATE TABLE `tbl_order` (
  `od_id` int(10) unsigned NOT NULL auto_increment,
  `od_date` datetime default NULL,
  `od_last_update` datetime NOT NULL default '0000­00­00 00:00:00',

24
  `od_status` enum('New', 'Paid', 'Shipped','Completed','Cancelled') NOT NULL default 'New',
  `od_memo` varchar(255) NOT NULL default '',
  `od_shipping_first_name` varchar(50) NOT NULL default '',
  `od_shipping_last_name` varchar(50) NOT NULL default '',
  `od_shipping_address1` varchar(100) NOT NULL default '',
  `od_shipping_address2` varchar(100) NOT NULL default '',
  `od_shipping_phone` varchar(32) NOT NULL default '',
  `od_shipping_city` varchar(100) NOT NULL default '',
  `od_shipping_state` varchar(32) NOT NULL default '',
  `od_shipping_postal_code` varchar(10) NOT NULL default '',
  `od_shipping_cost` decimal(5,2) default '0.00',
  `od_payment_first_name` varchar(50) NOT NULL default '',
  `od_payment_last_name` varchar(50) NOT NULL default '',
  `od_payment_address1` varchar(100) NOT NULL default '',
  `od_payment_address2` varchar(100) NOT NULL default '',
  `od_payment_phone` varchar(32) NOT NULL default '',
  `od_payment_city` varchar(100) NOT NULL default '',
  `od_payment_state` varchar(32) NOT NULL default '',
  `od_payment_postal_code` varchar(10) NOT NULL default '',
  PRIMARY KEY  (`od_id`)
) TYPE=MyISAM AUTO_INCREMENT=1001 ;
DROP TABLE IF EXISTS `tbl_order_item`;
CREATE TABLE `tbl_order_item` (
  `od_id` int(10) unsigned NOT NULL default '0',
  `pd_id` int(10) unsigned NOT NULL default '0',
  `od_qty` int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`od_id`,`pd_id`)
) TYPE=MyISAM;
DROP TABLE IF EXISTS `tbl_product`;
CREATE TABLE `tbl_product` (
  `pd_id` int(10) unsigned NOT NULL auto_increment,
  `cat_id` int(10) unsigned NOT NULL default '0',
  `pd_name` varchar(100) NOT NULL default '',
  `pd_description` text NOT NULL,
  `pd_price` decimal(9,2) NOT NULL default '0.00',
  `pd_qty` smallint(5) unsigned NOT NULL default '0',

25
  `pd_image` varchar(200) default NULL,
  `pd_thumbnail` varchar(200) default NULL,
  `pd_date` datetime NOT NULL default '0000­00­00 00:00:00',
  `pd_last_update` datetime NOT NULL default '0000­00­00 00:00:00',
  PRIMARY KEY  (`pd_id`),
  KEY `cat_id` (`cat_id`),
  KEY `pd_name` (`pd_name`)
) TYPE=MyISAM AUTO_INCREMENT=22 ;
DROP TABLE IF EXISTS `tbl_shop_config`;
CREATE TABLE `tbl_shop_config` (
  `sc_name` varchar(50) NOT NULL default '',
  `sc_address` varchar(100) NOT NULL default '',
  `sc_phone` varchar(30) NOT NULL default '',
  `sc_email` varchar(30) NOT NULL default '',
  `sc_shipping_cost` decimal(5,2) NOT NULL default '0.00',
  `sc_currency` int(10) unsigned NOT NULL default '1',
  `sc_order_email` enum('y','n') NOT NULL default 'n'
) TYPE=MyISAM;
DROP TABLE IF EXISTS `tbl_user`;
CREATE TABLE `tbl_user` (
  `user_id` int(10) unsigned NOT NULL auto_increment,
  `user_name` varchar(20) NOT NULL default '',
  `user_password` varchar(32) NOT NULL default '',
  `user_regdate` datetime NOT NULL default '0000­00­00 00:00:00',
  `user_last_login` datetime NOT NULL default '0000­00­00 00:00:00',
  PRIMARY KEY  (`user_id`),
  UNIQUE KEY `user_name` (`user_name`)
) TYPE=MyISAM AUTO_INCREMENT=4 ;
INSERT INTO `tbl_user` (`user_id`, `user_name`, `user_password`, `user_regdate`, `user_last_login`) VALUES (1, 'admin', 
'43e9a4ab75570f5b', '2005­02­20 17:35:44', '2005­03­02 21:00:14');
INSERT INTO `tbl_user` (`user_id`, `user_name`, `user_password`, `user_regdate`, `user_last_login`) VALUES (3, 
'webmaster', '026cf3fc6e903caf', '2005­03­02 17:52:51', '0000­00­00 00:00:00');

APPENDIX D – PHP ADMINISTRATION FUNCTIONS
DATA FETCH FUNCTION ­ /var/www/mpesashop/library/database.php
<?php

26
require_once 'config.php';
$dbConn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbName) or die('Cannot select database. ' . mysql_error());
function dbQuery($sql)
{
$result = mysql_query($sql) or die(mysql_error());
return $result;
}
function dbAffectedRows()
global $dbConn;
return mysql_affected_rows($dbConn);
}
function dbFetchArray($result, $resultType = MYSQL_NUM) {
return mysql_fetch_array($result, $resultType);
}
function dbFetchAssoc($result)
{ return mysql_fetch_assoc($result);
}
function dbFetchRow($result) 
{ return mysql_fetch_row($result);
}
function dbFreeResult($result)
{ return mysql_free_result($result);
}
function dbNumRows($result)
{ return mysql_num_rows($result);
}
function dbSelect($dbName)
{ return mysql_select_db($dbName);
}
function dbInsertId()
{ return mysql_insert_id();
}
?>
MPESA ACCOUNT­ORDER RECONCILIATION FUNTION
<?php

27
$sql_topay = "SELECT account, o.od_id, SUM(pd_price * od_qty) + od_shipping_cost AS topay
FROM inbox, tbl_order o, tbl_order_item oi, tbl_product p 
WHERE account = od_payment_phone and oi.pd_id = p.pd_id and o.od_id = oi.od_id 
AND od_status = 'new' and processed='0' 
GROUP BY o.od_id ORDER BY o.od_id DESC";
$result_topay = dbQuery($sql_topay);
if (dbNumRows($result_topay) > 0) {
$i = 0;
$balance = 0;
while($row = dbFetchAssoc($result_topay)) {
extract($row);
//Query to load received unprocessed amounts 
$sql_rcvd = "SELECT SUM(amount) AS rcvd
FROM inbox
WHERE account = ".$account;
$result_rcvd = dbQuery($sql_rcvd);
$row_rcvd = dbFetchAssoc($result_rcvd);
extract($row_rcvd);
//Query to change status of paid amounts 
$od_id_change = $od_id;
$sql4 = "UPDATE tbl_order SET od_status = 'Paid'
WHERE od_id=".$od_id_change;
//Query to load status change if balance cleared 
$balance = $topay ­ $rcvd;
if ($balance <= 0) { $result4 = dbquery($sql4);}
?>
<tr class="row"> 
    <td width="60" align="center"><?php echo $account; ?></td>
   <td width="60" align="right"><?php echo displayAmount($topay); ?></td>
   <td width="60" align="right"><?php echo displayAmount($rcvd); ?></td>
   <td width="60" align="right"><?php echo displayAmount($balance); ?></td>
   <td width="60" align="right"><?php echo $od_id; ?></td>
   </tr>
   <?php
$i += 1;
}//endwhile

28
}//endif
   ?>
ORDER AMOUNT FUNCTION ­ /var/www/mpesashop//library/checkout­functions
function getOrderAmount($orderId)
{
$orderAmount = 0;
$sql = "SELECT SUM(pd_price * od_qty)
        FROM tbl_order_item oi, tbl_product p 
    WHERE oi.pd_id = p.pd_id and oi.od_id = $orderId
UNION
SELECT od_shipping_cost 
FROM tbl_order
WHERE od_id = $orderId";
$result = dbQuery($sql);
if (dbNumRows($result) == 2) {
$row = dbFetchRow($result);
$totalPurchase = $row[0];
$row = dbFetchRow($result);
$shippingCost = $row[0];
$orderAmount = $totalPurchase + $shippingCost;
}
return $orderAmount;
}

?>

29
REFERENCES
[1] Paul Dubois, MySQL Developers Library 4th Edition, Copyright © 2009 by Pearson Education, Inc. 
ISBN­13: 978­0­672­32938­8
[2] Peter Gulutzan, MySQL 5.0 Triggers : MySQL 5.0 New Features Series – Part 2 . A MySQL® 
Technical White Paper , March, 2005 , Copyright © 2005, MySQL AB
[3] Michele E. Davis and Jon A. Phillips, Learning PHP and MySQL 2nd Edition, Copyright © 2007, 
2006 Michele E. Davis and Jon A. Phillips. All rights reserved. Printed in the United States of America. 
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. 
[4] Wilfred Mworia, Mobile Application Development Platforms: The Options , Strathmore Mobile 
BootCamp 2009 . ~ http://www.slideshare.net/wmworia
[5] Paul Leishman, Research Paper, GSMA: Mobile Money for the Unbanked : What Makes a  
Successful Mobile Money Implementation? Learnings from M­PESA in Kenya and Tanzania . ~ 
http://www.gsmworld.com/mmu
[6] Safaricom Resource Centre – Press Releases 2007­2010 ~ http://www.safaricom.co.ke

30

Vous aimerez peut-être aussi