PHP code example of gantry-motion / ussd-monkey

1. Go to this page and download the library: Download gantry-motion/ussd-monkey library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gantry-motion / ussd-monkey example snippets


use GantryMotion\USSDMonkey\USSDMonkey;

class USSDController
{
    private $ussd;

    public function __construct()
    {
        $this->ussd = new USSDMonkey([
            'ussd_menu_file' => ROOTPATH . 'ussdMenu.json',
            'sanitization' => [
                'enabled' => true,
                'country_code' => '256',
                'local_number_length' => 9,
            ],
        ], $this); // $this is the handler: the object whose methods execute_func names call
    }

    public function index()
    {
        // Which gateways this endpoint accepts, checked in order
        $this->ussd->setAdapters(['africastalking', 'uconnect']);

        try {
            $response = $this->ussd->run($this->request->getPost(), 'default_menu');

            return $this->response
                ->setContentType($this->ussd->getContentType()) // adapter decides plain/JSON/XML
                ->setBody($response);
        } catch (\Exception $e) {
            log_message('error', '[USSD Error] ' . $e->getMessage());
            return $this->response->setStatusCode(400)->setBody('Service unavailable.');
        }
    }

    // Called when a menu node's "execute_func" matches this method name
    public function say_hello($path, $ussd)
    {
        $name = end($path);
        return "Hello $name";
    }
}

public function my_func(array $path, USSDMonkey $ussd)
{
    // $path is the breadcrumb of every input entered so far in this session,
    // e.g. ['customer_menu', '1', '3', '2']
    // $ussd->session_data has sessionId, phoneNumber, text, and adapter (the resolved adapter's getName())
}

use GantryMotion\USSDMonkey\Adapters\AdapterInterface;

class MyGatewayAdapter implements AdapterInterface
{
    public function validate(array $data): bool
    {
        return !empty($data['session_id']) && !empty($data['phone_number']);
    }

    public function parseRequest(array $data): array
    {
        return [
            'sessionId'   => $data['session_id'],
            'phoneNumber' => $data['phone_number'],
            'text'        => $data['request_string'] ?? '',
        ];
    }

    public function formatResponse(string $message, bool $isTerminal): mixed
    {
        return json_encode(['response' => $message, 'end' => $isTerminal]);
    }

    public function getName(): string
    {
        return 'my_gateway'; // unique — used to partition Redis session keys per gateway
    }

    public function getContentType(): string
    {
        return 'application/json';
    }
}