Skip to main content

Installable django moncash

Project description

moncash

Digicel Moncash API SDK for DJANGO

Digicel MonCash - MonCash is a mobile wallet that facilitates reliable, safe and convenient financial transactions to reduce the distance between people regardless of their location in Haiti. While providing its services to its customer base of over 1.5 million people, MonCash maintains its goal of expanding its range of available services.

Define: SDK

SDK stands for “Software Development Kit”, which is a great way to think about it — a kit. Think about putting together a model car or plane. When constructing this model, a whole kit of items is needed, including the kit pieces themselves, the tools needed to put them together, assembly instructions, and so forth.

Features

  • Create payment
  • Consume payment
  • Verify payment

Installation

Moncash requires DJANGO v2.2+ to run. Install the the SDK and start using it.

Install using pip with:

    pip install  django_moncash

Add django_moncash app to INSTALLED_APPS in your django settings.py:

    INSTALLED_APPS = (
        ...,
        'django_moncash',
    )

Run the migrations:

    python manage.py makemigrations
    python manage.py migrate

Configuring the client

Digicel Moncash API Dashboard. Each business has it's own clientId clientSecret pairs.

Add credentials in your django settings.py:

    MONCASH = {
        'CLIENT_ID':'YOUR_CLIENT_ID',
        'SECRET_KEY':'YOUR_SECRET_KEY',
        'ENVIRONMENT':'sandbox or production'
    }

Include django_moncash.urls in your django project urls.py:

    from django.contrib import admin
    from django.urls import path,include

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('payment/',include('django_moncash.urls')),

        path('',include('test_app.urls'))
    ]

On the Digicel Moncash API Dashboard setup the business return url to be "https://yoursite.com/payment/moncash"

Note that "payment" is the base route you chose when your urls.py (path('payment/',include('django_moncash.urls')))

Create Payment

The only supported currency is 'HTG'. With the configue above.

    from django.shortcuts import redirect

    from django_moncash.utils import init_payment

    #views
    def buy(request):

        """ 
        params:

            request,                  # django views request
            amount: float,            # amount to pay
            return_url: str = None,   # custom return_url, default to current view
            order_id: str = None,     # unique order_id, default uuidV4
            meta_data: dict = None    # meta_data associated to the request
        """
        payment = init_payment(request,50)
        

        print(payment)

        return redirect(payment['payment_url'])

    """ output:
        {
            "payment_url":https://'<sandbox|"">'.moncashbutton.digicelgroup.com/Moncash-middleware/Payment/Redirect?token='<token>',
            "transaction":Transaction<object>
        }
    """

Verify Payment

Two way to do so. By moncash_transaction_id or request if on the "return_url" view.

    from django.http import HttpResponse

    from django_moncash.utils import verify_payment

    #views
    def verify(request):
    
        """ 
        params:

            request,                             # django views request
            moncash_transaction_id: str = None   # custom moncash_transaction_id, default to "request.GET.get("transactionId",None)"
        """

        payment = verify_payment(request)

        print(payment)

        return HttpResponse("payment succeed.")

    """ output:
        {
            "transaction": Transaction<object>,
            "transactionId":"XXXXXXXXXX"
        }
    """

Consume Payment

Two way to do so. By moncash_transaction_id or request if on the "return_url" view.

    from django.http import HttpResponse

    from django_moncash.utils import consume_payment

    #views
    def consume(request):
    
        """ 
        params:

            request,                             # django views request
            moncash_transaction_id: str = None   # custom moncash_transaction_id, default to "request.GET.get("transactionId",None)"
        """

        result = consume_payment(request)

        print(result)

        if result["success"]:

            return HttpResponse("payment successfuly consume.")
        
        return HttpResponse("payment failed to be consumed.")

    """ output:
        # if already consume
        {
            "success":False,
            "error":"USED",
            "payment":{
                "transaction": Transaction<object>,
                "transactionId":"XXXXXXXXXX"
            }
        }

        # if not found
        {
            "success":False,
            "error":"NOT_FOUND"
        }

        # if consume successfuly
        {
            "success":True,
            "payment":{
                "transaction": Transaction<object>,
                "transactionId":"XXXXXXXXXX"
            }
        }
    """

The difference between verify_payment and consume is that verify_payment didn't change the status of the transaction

    #Possible transaction status

    from django_moncash.models import Transaction

    Transaction.Status.PENDING      # before payment
    Transaction.Status.COMPLETE     # after payment
    Transaction.Status.CONSUME      # after consume

Error handling

List of errors in moncash.exceptions

    from moncash.exceptions import  NotFoundError

    from django.db import IntegrityError 

    from django_moncash.models import Transaction

List of errors

From moncash

  • AuthenticationError
  • AuthorizationError
  • GatewayTimeoutError
  • ConnectionError
  • InvalidResponseError
  • ConnectTimeoutError
  • ReadTimeoutError
  • TimeoutError
  • NotFoundError
  • RequestTimeoutError
  • ServerError
  • ServiceUnavailableError
  • TooManyRequestsError
  • UnexpectedError
  • UpgradeRequiredError

From django

  • IntegrityError
  • Transaction.DoesNotExist

Current Transaction model

    class Transaction(models.Model):

        class Status(models.TextChoices):
            PENDING = 'PENDING', _("Pending")
            COMPLETE = 'COMPLETE', _("Complete")
            CONSUME = 'CONSUME', _("Consume")


        user = models.ForeignKey(
            User,
            on_delete=models.SET_NULL,
            null=True,
            blank=True
        )

        order_id = models.CharField(_("Order id"), max_length=50,default=uuid.uuid4,unique=True, editable=False)
        amount   = models.DecimalField(_("Amount"), max_digits=11, decimal_places=2,blank=False,null=False)
        status = models.CharField(_('Status'),max_length=25,choices=Status.choices,default=Status.PENDING,blank=False)

        return_url = models.TextField(_("Return URL"),blank=False,null=False)

        meta_data = models.JSONField(_("Meta data"),null=True,blank=True)
        
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)

Development

Run all tests.

    python load_tests.py

Donate to support us

Scan and donate using the Moncash App Moncash_QR

Or Tranfer to:

(+509) 48-02-0151

License

GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007

Useful links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_moncash-2.6.0.tar.gz (46.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_moncash-2.6.0-py3-none-any.whl (34.6 kB view details)

Uploaded Python 3

File details

Details for the file django_moncash-2.6.0.tar.gz.

File metadata

  • Download URL: django_moncash-2.6.0.tar.gz
  • Upload date:
  • Size: 46.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.10.7

File hashes

Hashes for django_moncash-2.6.0.tar.gz
Algorithm Hash digest
SHA256 523cbaf85b03da6ba184d265e70dcc01397b1fe1a78135d3d6d8c10bac544e87
MD5 988c3980a8140c5a0928fce7cca4378f
BLAKE2b-256 016c3722a14f6581b8b0adb93d327930b58b96fc30365754a82f37983b2357b5

See more details on using hashes here.

File details

Details for the file django_moncash-2.6.0-py3-none-any.whl.

File metadata

  • Download URL: django_moncash-2.6.0-py3-none-any.whl
  • Upload date:
  • Size: 34.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.10.7

File hashes

Hashes for django_moncash-2.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dd264467fd1046bfd7f84f4da498ebbe798906ea8453eac32b8bdf6de2d9ea2c
MD5 38b92b280e978d613736b8c58a90ad2c
BLAKE2b-256 6ef502cd2e02a420ec72b163031cfc9e4e4d6fa2d3917ec55286137ae00dd612

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page