Skip to content

Commit

Permalink
[FEAT] .env file
Browse files Browse the repository at this point in the history
  • Loading branch information
rivo2302 committed Sep 18, 2022
1 parent 6548822 commit 8dcf1d9
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 71 deletions.
4 changes: 2 additions & 2 deletions .env
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
CONSUMER_KEY=GAQRHpf9DvxqdrkFFfeFwyqQvf4a
SECRET_KEY=7p4pM2f29cQb2CZjeoMheCH8rqka
export CONSUMER_KEY=GAQRHpf9DvxqdrkFFfeFwyqQvf4a
export SECRET_KEY=7p4pM2f29cQb2CZjeoMheCH8rqka
15 changes: 7 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
You can consult the link on pypi.org <a href="https://pypi.org/project/mvola/">here</a> for mode documentation.

```s
pip install mvola==1.0.3
pip install mvola==1.0.4
```

## USAGE
Expand All @@ -42,29 +42,28 @@ pip install mvola==1.0.3

### Start the API
Create your account <a href="https://www.mvola.mg/devportal/">here</a>.
After you create application , you should have Consummer_key and Consummer_secret.
After you create application , you should have Consummer_key and Consummer_secret and add those
variable in .env file(check the env file example).

```python
# Import the module mvola
from mvola import Mvola

# Import environ module to access environment variables
from os import environ
from os import environ as env

# Import and load the dotenv module to get environment variables from a .env file in order to avoid altering system environment variables
from dotenv import load_dotenv
load_dotenv()

# Initiate the api => API(Consummer_key, Consummer_secret)
api = Mvola(environ['CONSUMER_KEY'], environ['SECRET_KEY'])
api = Mvola(env.get('CONSUMER_KEY'), env.get('SECRET_KEY'))
```

### Generate token
Check the documentation <a href="https://www.mvola.mg/devportal/apis/5fb6b560-ef7e-49ad-b3c7-5335b7ca45f6/documents/89b6b1d0-b3c9-4758-a548-47889825bc68"> here</a>

```python
from mvola import Mvola
api = Mvola("{{consummer_key}}","{{consummenr_secret}}")
from os import environ as env
api = Mvola(env.get('CONSUMER_KEY'), env.get('SECRET_KEY'))

res = api.generate_token()
if res.success :
Expand Down
50 changes: 29 additions & 21 deletions demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
from datetime import datetime
import threading
from time import sleep
from dotenv import load_dotenv
from os import environ
from os import environ as env
import sys

load_dotenv()

api = Mvola(environ['CONSUMER_KEY'], environ['SECRET_KEY'])
if env.get("CONSUMER_KEY") and env.get("SECRET_KEY"):
api = Mvola(env.get("CONSUMER_KEY"), env.get("SECRET_KEY"), status="SANDBOX")
else:
print(" Mvola error : Verify if you have .env file <CONSUMER_KEY> and <SECRET_KEY>")
sys.exit()

# GENERATE TOKEN
res = api.generate_token()
Expand All @@ -28,7 +30,7 @@
user_account_identifier="0343500003",
partner_name="Marketbot",
x_callback_url="https://86f5-154-126-121-39.eu.ngrok.io",
amount="5555",
amount="555",
currency="Ar",
original_transaction_reference="orgina",
requesting_organisation_transaction_reference="ozcbajq",
Expand All @@ -38,7 +40,6 @@
credit="0343500004",
)


init = api.init_transaction(transaction)
if init.success:
print(init.response)
Expand All @@ -47,34 +48,41 @@


def notif_status(correlation_id):
# STATUS OF TRANSACTION
"""
A thread that will get the return of the transacation request.
The Mvola api makes a return after 30 seconds. We make a thread here because
we have no web server but the best way is use webserver.
"""
transaction = Transaction(
token=api.token,
user_language="FR",
user_account_identifier="0343500003",
partner_name="Marketbot",
partner_name="Demo",
server_correlation_id=correlation_id,
)

for i in range(15):
res = api.status_transaction(transaction)
if res.response["status"] != "pending":
print(res.response["status"])
break
sleep(3)
print(res.response["status"])


x = threading.Thread(target=notif_status, args=(init.response["serverCorrelationId"],))
x.start()

# DETAILS OF TRANSACTION
# transaction = Transaction(
# token=api.token,
# user_language="FR",
# user_account_identifier="0343500003",
# partner_name="Marketbot",
# transid="636251274",
# )
# res = api.details_transaction(transaction)
# if res.success:
# print(res.response)
# else:
# print(f"Status_code [{res.status_code}] \n {res.error}")
transaction = Transaction(
token=api.token,
user_language="FR",
user_account_identifier="0343500003",
partner_name="Marketbot",
transid="<ID OF TRANSACTION>",
)
res = api.details_transaction(transaction)
if res.success:
print(res.response)
else:
print(f"Status_code [{res.status_code}] \n {res.error}")
40 changes: 17 additions & 23 deletions mvola/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ def __init__(
status: str = "SANDBOX",
token: str = None,
):

"""
An API that will make it easier for you to manage
your Mvola API.
Expand All @@ -36,13 +35,9 @@ def __init__(
)

def generate_token(self):

"""
A function to generate a token for the Mvola API.
"""

url = f"{self.url}/token"
keys = f"{self.key}:{self.secret}"
keys_bytes = keys.encode("ascii")
Expand All @@ -65,57 +60,56 @@ def generate_token(self):
response = req.json()
res.response = response
res.response = response["access_token"]

elif status_code in range(500, 504):
res.error = {
"error_description": "Internal server errors.",
"error": "server errors",
}

res.error = {"description": "Internal Server error", "detail": req.text}
else:
res.error = req.json()

res.status_code = req.status_code
res.status_code = status_code
return res

def init_transaction(self, transaction):

"""
A method to calculate initiate a transaction with your Mvola API.
Args:
transaction ( object : Transaction ): An instance of Transaction class.
"""
url = f"{self.url}/mvola/mm/transactions/type/merchantpay/1.0.0/"
res = ResultAction()
data = transaction.dataJson
if not data.get("amount"):
raise ValueError("[amount] Required fields on action : init_transaction")
raise ValueError(
" Mvola Error : [amount] Required fields on action : init_transaction"
)

if not data.get("descriptionText"):
raise ValueError(
"[description_text] Required fields on action : init_transaction"
" Mvola Error : [description_text] Required fields on action : init_transaction"
)

if not data.get("requestDate"):
raise ValueError(
"[description_text] Required fields on action : init_transaction"
" Mvola Error : [description_text] Required fields on action : init_transaction"
)

if not data["debitParty"][0].get("value"):
raise ValueError("[debit] Required fields on action : init_transaction")
raise ValueError(
" Mvola Error : [debit] Required fields on action : init_transaction"
)

if not data["creditParty"][0].get("value"):
raise ValueError("[credit] Required fields on action : init_transaction")
raise ValueError(
" Mvola Error : [credit] Required fields on action : init_transaction"
)

if not data.get("originalTransactionReference"):
raise ValueError(
"[original_transaction_reference] Required fields on action : init_transaction"
" Mvola Error : [original_transaction_reference] Required fields on action : init_transaction"
)

if not data.get("requestingOrganisationTransactionReference"):
raise ValueError(
"[requesting_organisation_transaction_reference] Required fields on acion : init_transaction"
" Mvola Error : [requesting_organisation_transaction_reference] Required fields on acion : init_transaction"
)

for k, v in dict(data).items():
Expand Down Expand Up @@ -166,7 +160,7 @@ def status_transaction(self, transaction):
data = transaction.dataJson
if not data.get("serverCorrelationId"):
raise ValueError(
"[server_correlation_id] Required fields on action : status_transaction"
" Mvola Error : [server_correlation_id] Required fields on action : status_transaction"
)

url = f"{url}/{data.get('serverCorrelationId')}"
Expand Down Expand Up @@ -208,7 +202,7 @@ def details_transaction(self, transaction):

if not data.get("transid"):
raise ValueError(
"[transid] Required fields on acion : details of transaction"
" Mvola Error : [transid] Required fields on acion : details of transaction"
)

try:
Expand Down
31 changes: 15 additions & 16 deletions mvola/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ class ResultAction:
"""

def __init__(self) -> None:

self.success = False # True if the requests is success
self.error = None # Details if error occurs
self.response = None # Content of the request's response
Expand Down Expand Up @@ -71,33 +70,33 @@ def __init__(self, **kwargs):
self.transid = kwargs.get("transid")

if not self.token:
raise ValueError(
"[token] Required fields | MerchantNumber: the company phone number ex : 0343500004"
)
raise ValueError(" Mvola Error : [token] Required fields | Generate token")

if not self.user_account_identifier:
raise ValueError("[user_account_identifier] Required field")
raise ValueError(
" Mvola Error : [user_account_identifier] Required field"
)

if self.user_language.upper() not in ("FR", "MG"):
raise ValueError("[user_language] FR or MG")
raise ValueError(" Mvola Error : [user_language] FR or MG")

if not self.partner_name:
raise ValueError("[partner_name] Required field")
raise ValueError(" Mvola Error : [partner_name] Required field")

if self.amount:
if not str(self.amount).isdigit():
raise ValueError(
"[Amount] of transaction without decimals ,example : 1000,20,15"
" Mvola Error : [Amount] of transaction without decimals ,example : 1000,20,15"
)

if str(self.currency).capitalize() != "Ar":
raise ValueError(
"[Currency] code of the transaction - Possible Values : Ar"
" Mvola Error : [Currency] code of the transaction - Possible Values : Ar"
)

if re.match((r"^[0-9]{10}$"), self.user_account_identifier) is None:
raise ValueError(
"[UserAccountIdentifier] MerchantNumber: the company phone number ex : 0343500004"
" Mvola Error : [UserAccountIdentifier] MerchantNumber: the company phone number ex : 0343500004"
)

if self.description_text:
Expand All @@ -106,7 +105,7 @@ def __init__(self, **kwargs):
is None
):
raise ValueError(
"[description_text] on transaction. At most 50 characters long without special character except : “-”, “.”, “_”, “,”"
" Mvola Error : [description_text] on transaction. At most 50 characters long without special character except : “-”, “.”, “_”, “,”"
)

if self.requesting_organisation_transaction_reference:
Expand All @@ -118,7 +117,7 @@ def __init__(self, **kwargs):
is None
):
raise ValueError(
"Transaction ID of client side. At most 50 characters long without special Character except : “-”, “.”, “_”, “,”"
" Mvola Error : Transaction ID of client side. At most 50 characters long without special Character except : “-”, “.”, “_”, “,”"
)

if self.original_transaction_reference:
Expand All @@ -130,7 +129,7 @@ def __init__(self, **kwargs):
is None
):
raise ValueError(
"Transaction ID of client side. At most 50 characters long without special Character except : “-”, “.”, “_”, “,”"
" Mvola Error : Transaction ID of client side. At most 50 characters long without special Character except : “-”, “.”, “_”, “,”"
)

if self.request_date:
Expand All @@ -144,19 +143,19 @@ def __init__(self, **kwargs):
is None
):
raise ValueError(
"[request_date]Transaction requested date by client - yyyy-MM-ddTHH:mm:ss.SSSZ format , example = 2022-05-05T21:14:59.567Z"
" Mvola Error : [request_date]Transaction requested date by client - yyyy-MM-ddTHH:mm:ss.SSSZ format , example = 2022-05-05T21:14:59.567Z"
)

if self.debit:
if re.match((r"^[0-9]{10}$"), self.debit) is None:
raise ValueError(
"[Debit]Phone number of subscriber .In preprod it’s fixed: 034350003 or 0343500004"
" Mvola Error : [Debit]Phone number of subscriber .In preprod it’s fixed: 034350003 or 0343500004"
)

if self.credit:
if re.match((r"^[0-9]{10}$"), self.credit) is None:
raise ValueError(
"[Credit]Phone number of merchant. In preprod it’s fixed: 034350003 or 0343500004"
" Mvola Error : [Credit]Phone number of merchant. In preprod it’s fixed: 034350003 or 0343500004"
)

@property
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = mvola
version = 1.0.3
version = 1.0.4
author = rivo2302
author_email = [email protected]
description = A light open source module for Mvola API.
Expand Down

0 comments on commit 8dcf1d9

Please sign in to comment.