B2C Operations

B2C Operations

B2C (Business to Customer) operations allow you to send money from your business account to your customers' M-Pesa accounts. This is useful for scenarios like refunds, salary payments, or any other business-to-customer transfers.

Basic Usage

 
use MesaSDK\PhpMpesa\Config;
use MesaSDK\PhpMpesa\Mpesa;
use MesaSDK\PhpMpesa\Exceptions\MpesaException;
 
// Load configuration from environment variables in production
$config = new Config();
$config->setBaseUrl("https://apisandbox.safaricom.et")
    ->setConsumerKey("7oJ7uWPDp3jwqBzGvxQOn5g8s5rPwJ3qfXvsxwHyAknxAAxi")
    ->setConsumerSecret("zEvvR7yTpNYG1DoH31MKOYOzh0iZ9kdXAK1andjjrqXdnJMTbiUMhnnz5Qf12oNC")
    ->setEnvironment('sandbox')
    ->setVerifySSL(false);  // Note: Always use true in production
 
// Initialize M-Pesa client
$mpesa = new Mpesa($config);
 
try {
    // 1. Authenticate with M-Pesa API
    $mpesa->authenticate();
 
    // 2. Set up B2C payment parameters
    $params = [
        'initiatorName' => 'apitest',  // Your registered initiator name
        'securityCredential' => 'lMhf0UqE4ydeEDwpUskmPgkNDZnA6NLi7z3T1TQuWCkH3/ScW8pRRnobq/AcwFvbC961+zDMgOEYGm8Oivb7L/7Y9ED3lhR7pJvnH8B1wYis5ifdeeWI6XE2NSq8X1Tc7QB9Dg8SlPEud3tgloB2DlT+JIv3ebIl/J/8ihGVrq499bt1pz/EA2nzkCtGeHRNbEDxkqkEnbioV0OM//0bv4K++XyV6jUFlIIgkDkmcK6aOU8mPBHs2um9aP+Y+nTJaa6uHDudRFg0+3G6gt1zRCPs8AYbts2IebseBGfZKv5K6Lqk9/W8657gEkrDZE8Mi78MVianqHdY/8d6D9KKhw==',
        'commandId' => 'BusinessPayment',  // Options: SalaryPayment, BusinessPayment, PromotionPayment
        'amount' => 10,
        'partyA' => '1020',  // Your shortcode
        'partyB' => '251700404709',  // Recipient phone number
        'remarks' => 'Bonus payment',  // Payment description
        'occasion' => 'StallOwner',  // Optional reference
        'queueTimeOutURL' => 'https://testt.tugza.tech/',  // Timeout callback URL
        'resultURL' => 'https://testt.tugza.tech/'  // Success callback URL
    ];
 
    // 3. Initiate the B2C payment using fluent interface
    $result = $mpesa
        ->setInitiatorName($params['initiatorName'])
        ->setSecurityCredential($params['securityCredential'])
        ->setCommandId($params['commandId'])
        ->setAmount($params['amount'])
        ->setPartyA($params['partyA'])
        ->setPartyB($params['partyB'])
        ->setRemarks($params['remarks'])
        ->setOccasion($params['occasion'])
        ->setQueueTimeOutUrl($params['queueTimeOutURL'])
        ->setResultUrl($params['resultURL'])
        ->b2c();
 
    // 4. Handle the response
    if ($result && $result->getResponseMessage()) {
        echo "✅ B2C payment initiated successfully!\n";
        echo "Response: \n";
        print_r($result->getResponseMessage());
 
        // Store these details in your database for reconciliation
        // $conversationId = $result->getConversationId();
        // $originatorConversationId = $result->getOriginatorConversationId();
    }
 
} catch (MpesaException $e) {
    // Handle M-Pesa specific errors
    echo "❌ M-Pesa Error:\n";
    echo "Message: " . $e->getMessage() . "\n";
    echo "Code: " . $e->getCode() . "\n";
 
    // Log the error for debugging
    error_log("M-Pesa B2C Error: " . $e->getMessage());
} catch (Exception $e) {
    // Handle unexpected errors
    echo "❌ Unexpected Error: " . $e->getMessage() . "\n";
    error_log("Unexpected B2C Error: " . $e->getMessage());
}

Configuration

Before using B2C operations, ensure you have configured:

  1. Shortcode: Your M-Pesa shortcode
  2. Initiator Name: Your M-Pesa initiator name
  3. Initiator Password: Your M-Pesa initiator password
  4. Callback URLs: URLs to receive transaction notifications
  5. Environment: Sandbox or Production

Methods

setPhoneNumber(string $phone)

Sets the recipient's phone number.

$mpesa->setPhoneNumber("254712345678");

setAmount(float $amount)

Sets the transaction amount.

$mpesa->setAmount(1000.00);

setCallbackUrl(string $url)

Sets the callback URL for transaction notifications.

$mpesa->setCallbackUrl("https://your-domain.com/callback");

setQueueTimeOutUrl(string $url)

Sets the queue timeout URL.

$mpesa->setQueueTimeOutUrl("https://your-domain.com/timeout");

setResultUrl(string $url)

Sets the result URL.

$mpesa->setResultUrl("https://your-domain.com/result");

setRemarks(string $remarks)

Sets transaction remarks.

$mpesa->setRemarks("Salary Payment");

setOccasion(string $occasion)

Sets the transaction occasion.

$mpesa->setOccasion("Monthly Salary");

send()

Initiates the B2C payment request.

$result = $mpesa->send();

Response Handling

The B2C response includes:

  • TransactionID: Unique identifier for the transaction
  • ConversationID: Unique identifier for the conversation
  • OriginatorConversationID: Original conversation ID
  • ResponseCode: Response code from M-Pesa
  • ResponseDescription: Description of the response
if ($result->isSuccessful()) {
    echo "Transaction ID: " . $result->getTransactionID();
    echo "Conversation ID: " . $result->getConversationID();
} else {
    echo "Error: " . $result->getErrorMessage();
}

Checking Transaction Status

After initiating a B2C payment, you can check the transaction status:

$status = $mpesa->checkTransactionStatus($result->getTransactionID());
if ($status->isSuccessful()) {
    echo "Transaction Status: " . $status->getTransactionStatus();
}

Best Practices

  1. Error Handling

    • Implement comprehensive error handling
    • Log all transactions
    • Monitor failed transactions
  2. Callback Processing

    • Process callbacks asynchronously
    • Implement retry mechanisms
    • Validate callback data
  3. Security

    • Use HTTPS for all URLs
    • Validate phone numbers
    • Implement proper authentication
    • Secure initiator credentials
  4. Testing

    • Test in sandbox environment first
    • Use test phone numbers
    • Verify callback handling
    • Test with various amounts

Related Topics