Code Monkey home page Code Monkey logo

async-paystack-python's Introduction

Async Paystack Python

Unofficial asynchronous python wrapper for paystack payment.

Features

Quickstart

Example

Code

async def initiate_transaction(
    self, user_email: str, amount: int, reference: str = None
) -> Tuple[bool, Union[Dict, str]]:
    """
    This function initiates a transaction for a user

    :param user_email: The email of the user you want to initiate a transaction for
    :type user_email: str
    :param amount: The amount to be charged
    :type amount: int
    :param amount: The reference of the transaction
    :type reference: str

    :return::return:  A tuple of the status and the data.
    """

    async with httpx.AsyncClient() as client:
        data = {"email": f"{user_email}", "amount": int(amount)}
        url = self.base_url + "transaction/initialize"
        
        if reference:
            data["reference"] = reference
        
        response = await client.post(
            url, headers=self.headers(), data=json.dumps(data)
        )

        if response.status_code == 200:
            response_data = response.json()
            return response_data["status"], response_data["data"]

        response_data = response.json()
        return response_data["status"], response_data["messsage"]

In action

  • To see the code in action, run the following to command to start your python shell: python or python -i if you are in the same directory of the codebase.

  • Write the following codes inside the shell:

    >>> import asyncio
    >>> from async_paystack.paystack.transactions import Transactions
    >>>
    >>>
    >>> trx = Transactions()
    >>> status, data = asyncio.run(trx.initiate_transaction("youremailaddress.com", 50000 * 100, "refrenceisdmik")) # we need to convert naira to kobo before sending to paystack
    >>>
    >>>
    >>> status
    True
    >>> data
    {'authorization_url': 'https://checkout.paystack.com/access_code', 'access_code': 'gibberish', 'reference': 'refrenceisdmik'}

It is important that when run this code in Django without the asynchronous support, be sure to call the it with the asyncio.run(...) method.

Mock Testing (Explanation)

In the test_initiate_transaction example, I:

  • Imported the necessary modules and defined the test function using the @pytest.mark.asyncio decorator to indicate it's an asynchronous test case.
  • Created an instance of the class (Transactions) that contains the initiate_transaction method to be tested.
  • Mocked the httpx.AsyncClient class and its post method using mock.AsyncMock() and mock.MagicMock(), respectively. I set the status_code of the response to 200 and define the JSON response to match the expected behavior.
  • Set the mocked client as the client used in the Transactions instance by assigning it to the client attribute of the instance.
  • Call the initiate_transaction method with test data (user_email and amount).
  • Asserted that the returned result matches the expected result.
  • Finally, I asserted that the post method of the mocked client was called with the expected parameters.

Ensure that the necessary modules (pytest, pytest-asyncio, mock) are installed in your environment for running the test.

Contribute

All contributions are welcome:

  • Read the issues, Fork the project and do a Pull Request.
  • Request a new topic creating a New issue with the enhancement tag.
  • Find any kind of errors in the README and create a New issue with the details or fork the project and do a Pull Request.
  • Suggest a better or more pythonic way for existing examples.

async-paystack-python's People

Contributors

aybruhm avatar

Stargazers

 avatar  avatar

Watchers

 avatar

async-paystack-python's Issues

Thumb up

This is super

I admire your strengths

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.