This SDK allows you to easily integrate Yabetoo’s secure payment system into your Python applications. Whether you want to accept online payments, manage payment sessions, or check completed transactions, this SDK provides a simple and intuitive interface to interact with the Yabetoo API.
Installation
Prerequisites
- Python 3.7 or higher
- pip (Python package manager)
- Access to Yabetoo API (API keys)
- An active Yabetoo account
Installation via pip
To install the SDK, use pip. Run the following command in your project:
Configuration
SDK Initialization
Before using the SDK, you must initialize an instance of the Yabetoo class. Simply provide your API key during initialization. The SDK automatically detects whether you are in test or production mode based on your key prefix.
from yabetoo import Yabetoo
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX") # Use your API key
Advanced Configuration
You can customize the SDK behavior with additional options:
from yabetoo import Yabetoo
from yabetoo.models.common import HttpClientOptions
yabetoo = Yabetoo(
secret_key="sk_test_XXXXXXXXXXXXXXXXXXXXXXXX",
options=HttpClientOptions(
timeout=30, # Request timeout in seconds (default: 30)
max_retries=3, # Number of retry attempts (default: 3)
retry_delay=1, # Delay between retries in seconds (default: 1)
verify_ssl=True, # SSL verification (default: True)
follow_redirects=True, # Follow HTTP redirects (default: True)
custom_headers={} # Additional custom headers
)
)
Payment Management with Yabetoo
You can create payments, retrieve information about specific payments, and manage payments using the payments resource.
Yabetoo operates on a two-step payment model. This means that to process a payment, you must first create a payment intent and then confirm that intent to capture the amount.
This approach offers increased flexibility, allowing you, for example, to verify available funds or obtain user authorization before finalizing a transaction. Here’s how it works step by step:
- Create a payment intent: You create a payment intent specifying the amount, currency, and other relevant details.
- Confirm the payment intent: Once you’ve created the intent, you can confirm it to capture the amount. This can be done immediately or at a later date, depending on your needs.
- Manage payments: You can retrieve payment information, cancel payments, or handle other transaction-related aspects.
Create a Payment Intent
A payment intent is a resource that represents your wish to receive a payment for a specific amount. When you create a payment intent, you don’t immediately capture the amount; it’s a preparatory step.
from yabetoo import Yabetoo, CreateIntentRequest
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
payment = yabetoo.payments.create(CreateIntentRequest(
amount=5000,
currency="xaf",
description="Purchase of Yabetoo services",
metadata={
"order_id": "6735",
"customer_id": "12345"
}
))
print(f"Payment Intent ID: {payment.id}")
print(f"Client Secret: {payment.client_secret}")
This code creates a payment intent for 5000 XAF. The API response contains a unique identifier (id) for the payment intent that you’ll use during confirmation.
Confirm a Payment Intent
After creating the payment intent, you must confirm it to capture the amount. This typically occurs when the end user has completed all necessary steps (such as providing payment information or accepting terms and conditions).
from yabetoo import (
Yabetoo,
ConfirmIntentRequest,
PaymentMethodData,
MomoData
)
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
payment_confirmation = yabetoo.payments.confirm(
payment_id=payment.id,
data=ConfirmIntentRequest(
client_secret=payment.client_secret,
first_name="John",
last_name="Doe",
receipt_email="[email protected]",
payment_method_data=PaymentMethodData(
type="momo",
momo=MomoData(
country="cg",
msisdn="242123456789",
operator_name="mtn"
)
)
)
)
print(f"Charge ID: {payment_confirmation.charge_id}")
print(f"Status: {payment_confirmation.status}")
By calling this method, the amount associated with the payment intent will be captured, and the payment will be considered successful if everything goes well.
With this two-step model, developers can have better control over the payment process while providing a smooth user experience. You can adapt these two steps to your specific needs (for example, pre-authorization or deferred payment).
Error Handling During Confirmation
It’s important to handle errors because confirming a payment intent can fail for various reasons (insufficient funds, incorrect payment information, etc.).
Here’s an example of error handling during confirmation:
from yabetoo import Yabetoo, YabetooError
from yabetoo.errors import ValidationError, APIError, NetworkError
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
try:
payment_confirmation = yabetoo.payments.confirm(payment.id, confirm_data)
print(f"Payment confirmed: {payment_confirmation.charge_id}")
except ValidationError as e:
print("Validation error:")
for error in e.errors:
print(f" - Field '{error.get('field')}': {error.get('message')}")
except APIError as e:
print(f"API Error: {e.message}")
if e.code:
print(f"Error code: {e.code}")
except NetworkError as e:
print(f"Network Error: {e.message}")
except YabetooError as e:
print(f"General Error: {e}")
In this example, if the confirmation fails, an error message will be displayed instead of crashing the application. You can also log these errors for later analysis or display a user-friendly message.
Retrieve Payment Details
To retrieve information about an existing payment, use the payment ID as a parameter:
from yabetoo import Yabetoo
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
payment_details = yabetoo.payments.retrieve("pi_XXXXXXXXXXXX")
print(f"Payment ID: {payment_details.id}")
print(f"Amount: {payment_details.amount}")
print(f"Status: {payment_details.status}")
This code allows you to obtain detailed information about a specific payment, including its status, amount, and other associated metadata.
List All Your Payments
To retrieve a list of all your payments, use the all method. You can also filter payments by status or other criteria if needed.
from yabetoo import Yabetoo
from yabetoo.models.payment import PaymentFiltersRequest, Sorting
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
# Simple pagination
payments = yabetoo.payments.get_page(page=1, per_page=10)
print(f"Total payments: {payments.total_count}")
print(f"Current page items: {len(payments.items)}")
print(f"Has more pages: {payments.has_more}")
for payment in payments.items:
print(f" - {payment.id}: {payment.amount} {payment.currency}")
Advanced Filtering and Sorting
from yabetoo.models.payment import PaymentFiltersRequest, Sorting
# With sorting
sorted_payments = yabetoo.payments.get_page(
page=1,
per_page=10,
sorting=[{"id": "createdAt", "desc": True}] # Most recent first
)
# Using filter request object
filters = PaymentFiltersRequest(
page=1,
per_page=10,
sorting=[
Sorting(id="amount", desc=True), # Highest amounts first
Sorting(id="createdAt", desc=False) # Then oldest first
]
)
filtered_payments = yabetoo.payments.all(filters)
Using Payment Sessions with Yabetoo
With Yabetoo, you can create payment sessions that allow your users to go through a hosted payment page. This page is fully managed and secured by Yabetoo, simplifying online payment integration while ensuring transaction compliance and security.
What is a Payment Session?
A payment session is an instance that generates a unique URL pointing to a payment page hosted by Yabetoo. This page allows your customers to complete their payment simply and securely, without you having to directly manage sensitive details like credit card or mobile money information.
Advantages of Using a Payment Session
Using a hosted payment page offers several advantages for you as a developer or merchant:
- Security: Yabetoo handles payment security, allowing you to focus on your application.
- Compliance: By using a hosted payment page, you reduce your PCI compliance burden since Yabetoo manages sensitive information.
- User Experience: The payment page is optimized to provide a smooth and fast user experience.
- Customization: You can customize the payment page appearance to match your brand.
Create a Payment Session
Payment sessions allow you to create a secure and smooth payment process for your users. This session redirects the user to a hosted payment page to finalize the transaction.
from yabetoo import Yabetoo, CreateCheckoutSession, CheckoutItem
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
# Create checkout items
items = [
CheckoutItem(
product_id="prod_12345",
product_name="HD Screen",
quantity=1,
price=200000
),
CheckoutItem(
product_id="prod_67890",
product_name="Wireless Keyboard",
quantity=2,
price=35000
)
]
# Create the checkout session
session = yabetoo.sessions.create(CreateCheckoutSession(
account_id="acct_xxxxxxxx", # Your account ID
total=270000, # Total amount
currency="xaf",
success_url="https://your-site.com/checkout-success",
cancel_url="https://your-site.com/checkout-cancel",
items=items,
metadata={"order_id": "ORD-1234"}
))
print(f"Session ID: {session.session_id}")
print(f"Checkout URL: {session.url}")
print(f"Expires at: {session.expires_at}")
How the Payment Session Works
Session Creation
When you create a session, you send information about the items, total amount, currency, and redirect URLs (for success or cancellation).
Hosted Payment Page
Yabetoo returns a unique URL that you can use to redirect your users to the hosted payment page.
Payment Confirmation
Once the payment is successfully completed, the user is redirected to the URL you defined in success_url, with transaction details. If the user cancels, they will be redirected to the URL defined in cancel_url.
Redirect After Payment
When the payment is made via the payment page hosted by Yabetoo, you will be redirected to the URL you defined in the success_url field. Yabetoo automatically adds a parameter to this URL: the payment ID. This payment ID is crucial for verifying payment details and performing a double verification of the payment status.
# In your success URL handler (e.g., Flask or Django)
from yabetoo import Yabetoo
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
def checkout_success(request):
payment_id = request.GET.get('payment_id')
if payment_id:
# Retrieve payment details
payment_details = yabetoo.payments.retrieve(payment_id)
# Double verification of payment status
if payment_details.status == 'succeeded':
# Payment confirmed, process the order
print("Payment successful. You can now process the order.")
return {"status": "success", "payment": payment_details}
else:
# Payment not finalized or failed
print("Payment pending or failed. Please verify.")
return {"status": "pending", "payment": payment_details}
else:
return {"status": "error", "message": "No payment ID found"}
It’s important to always perform this double verification to ensure the security and integrity of your payment process.
Disbursements
Disbursements allow you to send money to recipients (customers, partners, etc.) via Mobile Money.
Create a Disbursement
from yabetoo import (
Yabetoo,
CreateDisbursementRequest,
PaymentMethodData,
MomoData
)
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
disbursement = yabetoo.disbursements.create(CreateDisbursementRequest(
amount=5000,
currency="xaf",
first_name="John",
last_name="Doe",
payment_method_data=PaymentMethodData(
type="momo",
momo=MomoData(
country="cg",
msisdn="+242123456789",
operator_name="mtn"
)
)
))
print(f"Disbursement ID: {disbursement.id}")
print(f"Status: {disbursement.status}")
Retrieve Disbursement Status
# Check disbursement status
status = yabetoo.disbursements.retrieve(disbursement.id)
print(f"Disbursement Status: {status.status}")
print(f"Amount: {status.amount} {status.currency}")
print(f"Recipient: {status.first_name} {status.last_name}")
Remittances (Transfers)
Remittances allow you to create transfer transactions.
Create a Remittance
from yabetoo import (
Yabetoo,
CreateRemittanceRequest,
PaymentMethodData,
MomoData
)
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
remittance = yabetoo.remittances.create(CreateRemittanceRequest(
amount=10000,
currency="xaf",
first_name="Jane",
last_name="Smith",
payment_method_data=PaymentMethodData(
type="momo",
momo=MomoData(
country="cg",
msisdn="+242987654321",
operator_name="airtel"
)
),
metadata={"reference": "REM-2024-001"}
))
print(f"Remittance ID: {remittance.id}")
print(f"Status: {remittance.status}")
Retrieve Remittance Status
# Check remittance status
status = yabetoo.remittances.retrieve(remittance.id)
print(f"Remittance Status: {status.status}")
print(f"Amount: {status.amount} {status.currency}")
Error Handling
The SDK provides a hierarchy of specific exceptions for different error scenarios:
| Exception | Description |
|---|
YabetooError | Base exception for all SDK errors |
ValidationError | Request validation failures |
APIError | API returned an error response |
NetworkError | Network or connection failures |
AuthenticationError | Authentication failures |
Complete Error Handling Example
from yabetoo import Yabetoo, YabetooError
from yabetoo.errors import ValidationError, APIError, NetworkError, AuthenticationError
yabetoo = Yabetoo("sk_test_XXXXXXXXXXXXXXXXXXXXXXXX")
try:
payment = yabetoo.payments.retrieve("pi_invalid_id")
except AuthenticationError as e:
print(f"Authentication failed: {e.message}")
# Check your API key
except ValidationError as e:
print("Validation errors:")
for error in e.errors:
field = error.get('field', 'unknown')
message = error.get('message', 'Unknown error')
print(f" - {field}: {message}")
except APIError as e:
print(f"API Error: {e.message}")
if e.code:
print(f"Error code: {e.code}")
# Handle specific error codes
if e.code == "payment_not_found":
print("The payment does not exist")
except NetworkError as e:
print(f"Network Error: {e.message}")
# Retry the request or notify the user
except YabetooError as e:
print(f"Unexpected error: {e}")
Supported Payment Methods
| Method | Type | Countries | Operators |
|---|
| Mobile Money | momo | cg (Congo), fr (France) | mtn, airtel |
Data Models Reference
Payment Method Data
from yabetoo import PaymentMethodData, MomoData
payment_method = PaymentMethodData(
type="momo", # Payment method type
momo=MomoData(
country="cg", # Country code: 'cg' or 'fr'
msisdn="242123456789", # Phone number
operator_name="mtn" # Operator: 'mtn' or 'airtel'
)
)
# The PaginatedResponse object provides these properties:
response = yabetoo.payments.get_page(page=1, per_page=10)
response.items # List of items (payments)
response.total_count # Total number of items
response.page # Current page number
response.per_page # Items per page
response.has_more # Whether more pages exist
response.raw_data # Raw API response data
Conclusion
The Yabetoo Python SDK allows you to easily integrate Yabetoo’s secure payment system into your applications. With its ease of use and advanced features, you can manage online payments efficiently and securely.
Whether you’re a beginner or experienced developer, this SDK provides all the tools you need to create a smooth and secure payment experience for your users.
Additional Resources