├── paymentsds ├── __init__.py └── mpesa │ ├── exceptions │ ├── timeout_error.py │ ├── validation_error.py │ ├── invalid_host_error.py │ ├── authentication_error.py │ ├── invalid_receiver_error.py │ ├── missing_property_error.py │ └── __init__.py │ ├── __init__.py │ ├── operation.py │ ├── environment.py │ ├── client.py │ ├── response.py │ ├── configuration.py │ ├── constants.py │ └── service.py ├── requirements.txt ├── .gitignore ├── setup.py ├── README.md └── LICENSE /paymentsds/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.0.0 2 | pycryptodome -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /*.egg-info 2 | /dist 3 | /build 4 | /test.py 5 | /**/__pycache__ -------------------------------------------------------------------------------- /paymentsds/mpesa/exceptions/timeout_error.py: -------------------------------------------------------------------------------- 1 | class TimeoutError(Exception): 2 | pass -------------------------------------------------------------------------------- /paymentsds/mpesa/exceptions/validation_error.py: -------------------------------------------------------------------------------- 1 | class ValidationError(Exception): 2 | pass -------------------------------------------------------------------------------- /paymentsds/mpesa/exceptions/invalid_host_error.py: -------------------------------------------------------------------------------- 1 | class InvalidHostError(Exception): 2 | pass -------------------------------------------------------------------------------- /paymentsds/mpesa/exceptions/authentication_error.py: -------------------------------------------------------------------------------- 1 | class AuthenticationError(Exception): 2 | pass -------------------------------------------------------------------------------- /paymentsds/mpesa/exceptions/invalid_receiver_error.py: -------------------------------------------------------------------------------- 1 | class InvalidReceiverError(Exception): 2 | pass -------------------------------------------------------------------------------- /paymentsds/mpesa/exceptions/missing_property_error.py: -------------------------------------------------------------------------------- 1 | class MissingPropertyError(Exception): 2 | pass -------------------------------------------------------------------------------- /paymentsds/mpesa/__init__.py: -------------------------------------------------------------------------------- 1 | from .client import Client 2 | from .service import Service 3 | from .operation import Operation 4 | from .environment import Environment -------------------------------------------------------------------------------- /paymentsds/mpesa/operation.py: -------------------------------------------------------------------------------- 1 | class Operation: 2 | PARAMS = [ 3 | 'name', 4 | 'method', 5 | 'port', 6 | 'path', 7 | 'expects', 8 | 'returns' 9 | ] 10 | 11 | def __init__(self, **kwargs): 12 | for key, value in kwargs.items(): 13 | if key in self.PARAMS: 14 | self.__dict__[key] = value -------------------------------------------------------------------------------- /paymentsds/mpesa/exceptions/__init__.py: -------------------------------------------------------------------------------- 1 | from .authentication_error import AuthenticationError 2 | from .invalid_host_error import InvalidHostError 3 | from .invalid_receiver_error import InvalidReceiverError 4 | from .validation_error import ValidationError 5 | from .missing_property_error import MissingPropertyError 6 | from .timeout_error import TimeoutError -------------------------------------------------------------------------------- /paymentsds/mpesa/environment.py: -------------------------------------------------------------------------------- 1 | class Environment: 2 | PARAMS = [ 3 | 'scheme', 4 | 'domain' 5 | ] 6 | 7 | SANDBOX = 'https://api.sandbox.vm.co.mz' 8 | PRODUCTION = 'https://api.mpesa.vm.co.mz' 9 | 10 | def __init__(self, **kwargs): 11 | for key, value in kwargs.items(): 12 | if key in self.PARAMS: 13 | self.__dict__[key] = value 14 | 15 | @staticmethod 16 | def from_url(url): 17 | parts = url.split('://') 18 | return Environment(scheme=parts[0], domain=parts[1]) 19 | -------------------------------------------------------------------------------- /paymentsds/mpesa/client.py: -------------------------------------------------------------------------------- 1 | from .service import Service 2 | 3 | class Client: 4 | def __init__(self,**kwargs): 5 | self.service = Service(**kwargs) 6 | 7 | def send(self, data): 8 | return self.service.handle_send(data) 9 | 10 | def receive(self, data): 11 | return self.service.handle_receive(data) 12 | 13 | 14 | def revert(self, data): 15 | return self.service.handle_revert(data) 16 | 17 | def query(self, data): 18 | return self.service.handle_query(data) 19 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup_args = dict( 4 | name='paymentsds-mpesa', 5 | version='0.1a10', 6 | description='MPesa Python SDK', 7 | license='Apache-2.0', 8 | author='Edson Michaque', 9 | author_email='edson@michaque.com', 10 | keywords=['MPesa'], 11 | url='https://github.com/paymentsds/mpesa-python-sdk', 12 | packages=[ 13 | "paymentsds", 14 | "paymentsds/mpesa", 15 | "paymentsds/mpesa/exceptions" 16 | ], 17 | install_requires=[ 18 | 'requests>=2.0.0', 19 | 'pycryptodome' 20 | ] 21 | ) 22 | 23 | if __name__ == '__main__': 24 | setup(**setup_args) 25 | -------------------------------------------------------------------------------- /paymentsds/mpesa/response.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | 3 | class Response: 4 | def __init__(self, status, data): 5 | self.success = status 6 | self.status = namedtuple('ResponseStatus', 'code description')( 7 | data['output_ResponseCode'], 8 | data['output_ResponseDesc'] 9 | ) 10 | 11 | self.data = {#namedtuple('ResponseData' , 'transaction conversation reference')( 12 | # 'transaction': data['output_TransactionID'], 13 | 'conversation': data['output_ConversationID'], 14 | 'reference': data['output_ThirdPartyReference'] 15 | }#) 16 | if hasattr(data, 'output_TransactionID'): self.data['transaction'] = data['output_TransactionID'] 17 | -------------------------------------------------------------------------------- /paymentsds/mpesa/configuration.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | from .environment import Environment 3 | from Crypto.Cipher import PKCS1_v1_5 4 | 5 | import base64 6 | 7 | class Configuration: 8 | PARAMS = [ 9 | 'user_agent', 10 | 'api_key', 11 | 'public_key', 12 | 'timeout', 13 | 'verify_ssl', 14 | 'debugging', 15 | 'access_token', 16 | 'environment', 17 | 'host', 18 | 'service_provider_code', 19 | 'initiator_identifier', 20 | 'security_credential', 21 | 'origin' 22 | ] 23 | 24 | def __init__(self, **kwargs): 25 | self.user_agent = 'Paymentsds/M-Pesa' 26 | self.timeout = 0 27 | self.verify_ssl = False 28 | self.debugging = True 29 | self.environment = Environment.from_url(Environment.SANDBOX) 30 | self.origin = '*' 31 | 32 | for key, value in kwargs.items(): 33 | if key in self.PARAMS: 34 | if key == 'host': 35 | self.environment = Environment.from_url(value) 36 | elif key == 'environment': 37 | self.environment = Environment.from_url(value) 38 | else: 39 | self.__dict__[key] = value 40 | 41 | def generate_access_token(self): 42 | has_keys = hasattr(self, 'api_key') and hasattr(self, 'public_key') 43 | has_access_token = hasattr(self, 'access_token') 44 | 45 | if has_keys: 46 | formated_rsa_public_key = self.format_public_key(self.public_key) 47 | rsa_public_key_buffer = formated_rsa_public_key.encode() 48 | 49 | rsa_public_key = RSA.importKey(rsa_public_key_buffer) 50 | cipher = PKCS1_v1_5.new(rsa_public_key) 51 | encrypted_api_key = cipher.encrypt(self.api_key.encode()) 52 | self.auth = base64.b64encode(encrypted_api_key).decode() 53 | 54 | if has_access_token: 55 | self.auth = self.access_token 56 | 57 | def format_public_key(self, public_key): 58 | header = '-----BEGIN PUBLIC KEY-----' 59 | footer = '-----END PUBLIC KEY-----' 60 | 61 | return '{}\n{}\n{}'.format(header, public_key, footer) 62 | -------------------------------------------------------------------------------- /paymentsds/mpesa/constants.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | PATTERNS = { 4 | 'PHONE_NUMBER': re.compile('^((00|\+)?258)?8[45][0-9]{7}$'), 5 | 'SERVICE_PROVIDER_CODE': re.compile('^[0-9]{5,6}$'), 6 | 'WORD': re.compile('\\w+'), 7 | 'MONEY_AMOUNT': re.compile( '^[1-9][0-9]*(\.[0-9])*$') 8 | } 9 | 10 | DEFAULT_OPERATIONS = { 11 | 'C2B_PAYMENT': { 12 | 'method': 'POST', 13 | 'port':'18352', 14 | 'path':'/ipg/v1x/c2bPayment/singleStage/', 15 | 'mapping': { 16 | 'from': 'input_CustomerMSISDN', 17 | 'to': 'input_ServiceProviderCode', 18 | 'amount': 'input_Amount', 19 | 'transaction': 'input_TransactionReference', 20 | 'reference': 'input_ThirdPartyReference' 21 | }, 22 | 'validation': { 23 | 'from': PATTERNS['PHONE_NUMBER'], 24 | 'to': PATTERNS['SERVICE_PROVIDER_CODE'], 25 | 'amount': PATTERNS['MONEY_AMOUNT'], 26 | 'transaction': PATTERNS['WORD'], 27 | 'reference': PATTERNS['WORD'] 28 | }, 29 | 'required': [ 30 | 'to', 31 | 'amount', 32 | 'transaction', 33 | 'reference' 34 | ], 35 | 'optional': [ 36 | 'to' 37 | ] 38 | }, 39 | 'B2B_PAYMENT': { 40 | 'method': 'POST', 41 | 'port':'18349', 42 | 'path':'/ipg/v1x/b2bPayment/', 43 | 'mapping': { 44 | 'from': 'input_ServiceProviderCode', 45 | 'to': 'input_ReceiverPartyCode', 46 | 'amount': 'input_Amount', 47 | 'transaction': 'input_TransactionReference', 48 | 'reference': 'input_ThirdPartyReference' 49 | }, 50 | 'validation': { 51 | 'from': PATTERNS['SERVICE_PROVIDER_CODE'], 52 | 'to': PATTERNS['SERVICE_PROVIDER_CODE'], 53 | 'amount': PATTERNS['MONEY_AMOUNT'], 54 | 'transaction': PATTERNS['WORD'], 55 | 'reference': PATTERNS['WORD'] 56 | }, 57 | 'required': [ 58 | 'to', 59 | 'amount', 60 | 'transaction', 61 | 'reference' 62 | ], 63 | 'optional': [ 64 | 'from' 65 | ] 66 | }, 67 | 'B2C_PAYMENT': { 68 | 'method': 'POST', 69 | 'port':'18345', 70 | 'path':'/ipg/v1x/b2cPayment/', 71 | 'mapping': { 72 | 'from': 'input_ServiceProviderCode', 73 | 'to': 'input_CustomerMSISDN', 74 | 'amount': 'input_Amount', 75 | 'transaction': 'input_TransactionReference', 76 | 'reference': 'input_ThirdPartyReference' 77 | }, 78 | 'validation': { 79 | 'from': PATTERNS['SERVICE_PROVIDER_CODE'], 80 | 'to': PATTERNS['PHONE_NUMBER'], 81 | 'amount': PATTERNS['MONEY_AMOUNT'], 82 | 'transaction': PATTERNS['WORD'], 83 | 'reference': PATTERNS['WORD'] 84 | }, 85 | 'required': [ 86 | 'to', 87 | 'amount', 88 | 'transaction', 89 | 'reference' 90 | ], 91 | 'optional': [ 92 | 'from' 93 | ] 94 | }, 95 | 'REVERSAL': { 96 | 'method': 'PUT', 97 | 'port':'18354', 98 | 'path':'/ipg/v1x/reversal/', 99 | 'mapping': { 100 | 'to': 'input_ServiceProviderCode', 101 | 'amount': 'input_ReversalAmount', 102 | 'transaction': 'input_TransactionID', 103 | 'reference': 'input_ThirdPartyReference', 104 | 'security_credential': 'input_SecurityCredential', 105 | 'initiator_identifier': 'input_InitiatorIdentifier' 106 | }, 107 | 'validation': { 108 | 'to': PATTERNS['SERVICE_PROVIDER_CODE'], 109 | 'amount': PATTERNS['MONEY_AMOUNT'], 110 | 'transaction': PATTERNS['WORD'], 111 | 'reference': PATTERNS['WORD'], 112 | 'security_credential': PATTERNS['WORD'], 113 | 'initiator_identifier': PATTERNS['WORD'] 114 | }, 115 | 'required': [ 116 | 'to', 117 | 'amount', 118 | 'transaction', 119 | 'reference', 120 | 'security_credential', 121 | 'initiator_identifier' 122 | ], 123 | 'optional': [ 124 | 'to', 125 | 'security_credential', 126 | 'initiator_identifier' 127 | ] 128 | }, 129 | 'QUERY_TRANSACTION_STATUS': { 130 | 'method': 'GET', 131 | 'port':'18353', 132 | 'path':'/ipg/v1x/queryTransactionStatus/', 133 | 'mapping': { 134 | 'from': 'input_ServiceProviderCode', 135 | 'subject': 'input_QueryReference', 136 | 'reference': 'input_ThirdPartyReference' 137 | }, 138 | 'validation': { 139 | 'from': PATTERNS['SERVICE_PROVIDER_CODE'], 140 | 'subject': PATTERNS['WORD'], 141 | 'reference': PATTERNS['WORD'] 142 | }, 143 | 'required': [ 144 | 'from', 145 | 'subject', 146 | 'reference' 147 | ], 148 | 'optional': [ 149 | 'from' 150 | ] 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PYTHON M-Pesa SDK 2 | 3 | 4 |

Total Downloads Latest Stable Version License

5 | 6 | This is a library willing to help you to integrate the [Vodacom M-Pesa](https://developer.mpesa.vm.co.mz) operations to your application. 7 | 8 |
9 | 10 | ### Features 11 | 12 | Using this library, you can implement the following operations: 13 | 14 | - Receive money from a mobile account to a business account (C2B) 15 | - Send money from a business account to a mobile account (B2C) 16 | - Send money from a business account to another business account (B2B) 17 | - Revert any of the transactions above mentioned 18 | 19 |

20 | 21 | ## Requirements 22 | 23 | - Valid credentials obtained from the [Mpesa Developer](https://developer.mpesa.vm.co.mz) portal 24 | - Port 18352 open on your server (usually open on local env) 25 | - [Python 3.5+](https://www.python.org) 26 | - [PIP](https://pip.pypa.io) 27 | 28 | 29 |

30 | 31 | 32 | ## Installation 33 | 34 |
35 | 36 | ### Using PIP 37 | 38 | ```bash 39 | $ pip install paymentsds-mpesa 40 | 41 | $ cd paymentsds-mpesa 42 | 43 | $ pip install -r requirements.txt 44 | ``` 45 | 46 |

47 | 48 | 49 | ## Usage 50 | 51 | Using this SDK is very simple and fast, let us see some examples: 52 | 53 |
54 | 55 | #### C2B Transaction (Receive money from mobile account) 56 | 57 | ```python 58 | from paymentsds.mpesa import Client 59 | 60 | client = Client( 61 | api_key='', # API Key 62 | public_key='', # Public Key 63 | service_provider_code='' # input_ServiceProviderCode 64 | ) 65 | 66 | try: 67 | payment_data = { 68 | 'from': '841234567', # input_CustomerMSISDN 69 | 'reference': '11114', # input_ThirdPartyReference 70 | 'transaction': 'T12344CC', # input_TransactionReference 71 | 'amount': '10' # input_Amount 72 | } 73 | 74 | result = client.receive(payment_data) 75 | except: 76 | print('Operation failed') 77 | 78 | ``` 79 | 80 |
81 | 82 | #### B2C Transaction (Sending money to mobile account) 83 | 84 | ```python 85 | from paymentsds.mpesa import Client 86 | 87 | client = Client( 88 | api_key='', # API Key 89 | public_key='', # Public Key 90 | service_provider_code='' # input_ServiceProviderCode 91 | ) 92 | 93 | try: 94 | payment_data = { 95 | 'to': '841234567', # input_CustomerMSISDN 96 | 'reference': '11114', # input_ThirdPartyReference 97 | 'transaction': 'T12344CC', # input_TransactionReference 98 | 'amount': '10' # input_Amount 99 | } 100 | 101 | result = client.send(payment_data) 102 | except: 103 | print('Operation failed') 104 | 105 | ``` 106 | 107 |
108 | 109 | #### B2B Transaction (Sending money to business account) 110 | 111 | ```python 112 | from paymentsds.mpesa import Client 113 | 114 | client = Client( 115 | api_key='', # API Key 116 | public_key='', # Public Key 117 | service_provider_code='' # input_ServiceProviderCode 118 | ) 119 | 120 | try: 121 | payment_data = { 122 | 'to': '979797', # input_ReceiverPartyCode 123 | 'reference': '11114', # input_ThirdPartyReference 124 | 'transaction': 'T12344CC', # input_TransactionReference 125 | 'amount': '10' # input_Amount 126 | } 127 | 128 | result = client.send(payment_data) 129 | except: 130 | print('Operation failed') 131 | 132 | ``` 133 | 134 |
135 | 136 | 137 | #### Transaction Reversal 138 | 139 | ```python 140 | from paymentsds.mpesa import Client 141 | 142 | client = Client( 143 | api_key='', # API Key 144 | public_key='', # Public Key 145 | service_provider_code='', # input_ServiceProviderCode 146 | initiatorIdentifier='', # input_InitiatorIdentifier, 147 | securityIdentifier='' # input_SecurityCredential 148 | ) 149 | 150 | try: 151 | reversion_data = { 152 | 'reference': '11114', # input_ThirdPartyReference 153 | 'transaction': 'T12344CC', # input_TransactionReference 154 | 'amount': '10' # input_ReversalAmount 155 | } 156 | 157 | result = client.revert(reversion_data) 158 | except: 159 | # Handle success scenario 160 | 161 | ``` 162 | 163 |
164 | 165 | ## Friends 166 | 167 | - [M-Pesa SDK for Javascript](https://github.com/paymentsds/mpesa-js-sdk) 168 | - [M-Pesa SDK for Java](https://github.com/paymentsds/mpesa-java-sdk) 169 | - [M-Pesa SDK for PHP](https://github.com/paymentsds/mpesa-php-sdk) 170 | - [M-Pesa SDK for Ruby](https://github.com/paymentsds/mpesa-ruby-sdk) 171 | 172 | 173 |

174 | 175 | ## Authors 176 | 177 | - [Edson Michaque](https://github.com/edsonmichaque) 178 | - [Nélio Macombo](https://github.com/neliomacombo) 179 | 180 | 181 |

182 | 183 | ## Contributing 184 | 185 | Thank you for considering contributing to this package. If you wish to do it, email us at [developers@paymentsds.org](mailto:developers@paymentsds.org) and we will get back to you as soon as possible. 186 | 187 | 188 |

189 | 190 | ## Security Vulnerabilities 191 | 192 | If you discover a security vulnerability, please email us at [developers@paymentsds.org](mailto:developers@paymentsds.org) and we will address the issue with the needed urgency. 193 | 194 |

195 | 196 | ## License 197 | 198 | Copyright 2022 © The PaymentsDS Team 199 | 200 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 201 | 202 | http://www.apache.org/licenses/LICENSE-2.0 203 | 204 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 205 | -------------------------------------------------------------------------------- /paymentsds/mpesa/service.py: -------------------------------------------------------------------------------- 1 | from .configuration import Configuration 2 | from .exceptions import * 3 | from .constants import * 4 | from .response import Response 5 | 6 | import requests 7 | 8 | class Service: 9 | def __init__(self, **kwargs): 10 | self.config = Configuration(**kwargs) 11 | 12 | def handle_request(self, opcode, intent): 13 | data = self.fill_optional_properties(opcode, intent) 14 | 15 | missing_properties = self.detect_missing_properties(opcode, data) 16 | if len(missing_properties): 17 | print(missing_properties) 18 | raise MissingPropertyError() 19 | 20 | errors = self.detect_errors(opcode, data) 21 | if len(errors): 22 | raise ValidationError() 23 | 24 | return self.perform_request(opcode, data) 25 | 26 | def handle_send(self, data): 27 | opcode = self.detect_operation(data) 28 | if opcode: 29 | return self.handle_request(opcode, data) 30 | raise InvalidReceiverError() 31 | 32 | def handle_receive(self, data): 33 | return self.handle_request('C2B_PAYMENT', data) 34 | 35 | def handle_query(self, data): 36 | return self.handle_request('QUERY_TRANSACTION_STATUS', data) 37 | 38 | def handle_revert(self, data): 39 | return self.handle_request('REVERSAL', data) 40 | 41 | def detect_operation(self, data): 42 | if PATTERNS['PHONE_NUMBER'].match(data['to']): 43 | return 'B2C_PAYMENT' 44 | 45 | if PATTERNS['SERVICE_PROVIDER_CODE'].match(data['to']): 46 | return 'B2B_PAYMENT' 47 | 48 | return None 49 | 50 | def detect_errors(self, opcode, data): 51 | errors = [] 52 | operation = DEFAULT_OPERATIONS[opcode] 53 | 54 | for k, v in data.items(): 55 | regex = operation['validation'][k] 56 | if not regex.match(v): 57 | errors.append(k) 58 | 59 | return errors 60 | 61 | def detect_missing_properties(self, opcode, data): 62 | operation = DEFAULT_OPERATIONS[opcode] 63 | required_properties = set(operation['required']) 64 | given_properties = set(data.keys()) 65 | missing_properties = required_properties - given_properties 66 | 67 | return list(missing_properties) 68 | 69 | def fill_optional_properties(self, opcode, data): 70 | def complete_to(to_complete): 71 | if 'to' not in to_complete.keys(): 72 | if 'service_provider_code' in self.config.__dict__.keys(): 73 | to_complete['to'] = self.config.service_provider_code 74 | 75 | return to_complete 76 | 77 | def complete_from(to_complete): 78 | if 'from' not in to_complete.keys(): 79 | if 'service_provider_code' in self.config.__dict__.keys(): 80 | to_complete['from'] = self.config.service_provider_code 81 | 82 | return to_complete 83 | 84 | def complete_reversal(to_complete): 85 | if 'to' not in to_complete.keys(): 86 | if 'service_provider_code' in self.config.__dict__.keys(): 87 | to_complete['to'] = self.config.service_provider_code 88 | 89 | if 'initiator_identifier' not in to_complete.keys(): 90 | if 'initiator_identifier' in self.config.__dict__.keys(): 91 | to_complete['initiator_identifier'] = self.config.initiator_identifier 92 | 93 | if 'security_credential' not in to_complete.keys(): 94 | if 'security_credential' in self.config.__dict__.keys(): 95 | to_complete['security_credential'] = self.config.security_credential 96 | 97 | return to_complete 98 | 99 | def complete_query_transaction_status(to_complete): 100 | if 'from' not in to_complete.keys(): 101 | if 'service_provider_code' in self.config.__dict__.keys(): 102 | to_complete['from'] = self.config.service_provider_code 103 | 104 | return to_complete 105 | 106 | if opcode == 'C2B_PAYMENT': 107 | return complete_to(data) 108 | elif opcode == 'B2B_PAYMENT': 109 | return complete_from(data) 110 | elif opcode == 'B2C_PAYMENT': 111 | return complete_from(data) 112 | elif opcode == 'REVERSAL': 113 | return complete_reversal(data) 114 | elif opcode == 'QUERY_TRANSACTION_STATUS': 115 | return complete_query_transaction_status(data) 116 | else: 117 | return data 118 | 119 | def perform_request(self, opcode, intent): 120 | self.generate_access_token() 121 | 122 | if hasattr(self.config, 'environment'): 123 | if hasattr(self.config, 'auth'): 124 | operation = DEFAULT_OPERATIONS[opcode] 125 | 126 | headers = self.build_request_headers() 127 | body = self.build_request_body(opcode, intent) 128 | 129 | url = '{}://{}:{}{}'.format(self.config.environment.scheme, self.config.environment.domain, operation['port'], operation['path']) 130 | 131 | if operation['method'] == 'GET': 132 | if self.config.timeout > 0: 133 | response = requests.get(url, headers=headers, params=body, timeout=self.config.timeout, verify=self.config.verify_ssl) 134 | else: 135 | response = requests.get(url, headers=headers, params=body, verify=self.config.verify_ssl) 136 | 137 | elif operation['method'] == 'PUT': 138 | 139 | if self.config.timeout > 0: 140 | response = requests.put(url, headers=headers, json=body, timeout=self.config.timeout, verify=self.config.verify_ssl) 141 | else: 142 | response = requests.put(url, headers=headers, json=body, verify=self.config.verify_ssl) 143 | 144 | else: 145 | 146 | if self.config.timeout > 0: 147 | response = requests.post(url, headers=headers, json=body, timeout=self.config.timeout, verify=self.config.verify_ssl) 148 | else: 149 | response = requests.post(url, headers=headers, json=body, verify=self.config.verify_ssl) 150 | 151 | if response.status_code >= 200 and response.status_code < 300: 152 | return Response(True, response.json()) 153 | else: 154 | return Response(False, response.json()) 155 | else: 156 | raise AuthenticationError() 157 | else: 158 | raise InvalidHostError() 159 | 160 | def generate_access_token(self): 161 | self.config.generate_access_token() 162 | 163 | def build_request_headers(self): 164 | return { 165 | 'User-Agent': self.config.user_agent, 166 | 'Origin': self.config.origin, 167 | 'Authorization': 'Bearer {}'.format(self.config.auth), 168 | 'Content-Type': 'application/json' 169 | } 170 | 171 | def build_request_body(self, opcode, intent): 172 | body = {} 173 | 174 | for old_key, v in intent.items(): 175 | new_key = DEFAULT_OPERATIONS[opcode]['mapping'][old_key] 176 | if (opcode == 'C2B_PAYMENT' and old_key == 'from') or (opcode == 'B2C_PAYMENT' and old_key == 'to'): 177 | body[new_key] = self.normalize_phone_number(intent[old_key]) 178 | else: 179 | body[new_key] = intent[old_key] 180 | 181 | return body 182 | 183 | def normalize_phone_number(self, str): 184 | return str -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Edson Michaque and Nélio Macombo 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------