@@ -29,7 +29,7 @@ class Mpesa(object):
29
29
def __init__ (
30
30
self ,
31
31
auth_path : Optional [str ] = "keys.json" ,
32
- environment : Optional [str ] = "testing " ,
32
+ environment : Optional [str ] = "sandbox " ,
33
33
):
34
34
"""
35
35
Mpesa API client for Python
@@ -44,14 +44,24 @@ def __init__(
44
44
45
45
@property
46
46
def authenticate (self ) -> bool :
47
- """"""
47
+ """
48
+ Property to check If the user is has has included auth keys
49
+ either manually or through auth json file(keys.json)
50
+
51
+ >> import pypesa
52
+ >> mpesa = pypesa()
53
+ >> mpesa.authenticate
54
+
55
+ Return True if the environment has auth keys
56
+ False if auth are not included
57
+ """
48
58
49
59
if self .auth_keys .get ("public_key" ) and self .auth_keys .get ("api_key" ):
50
60
self ._encrypted_api_key = self .__generate_encrypted_key ()
51
61
return True
52
62
53
63
elif os .path .isfile (self .auth_path ):
54
- print ("loading from file" )
64
+ # print("loading from file")
55
65
self .auth_keys = self .load_keys (self .auth_path )
56
66
if self .auth_keys :
57
67
self ._encrypted_api_key = self .__generate_encrypted_key ()
@@ -72,7 +82,17 @@ def authorized_method(self, *args, **kwargs):
72
82
73
83
@staticmethod
74
84
def load_keys (keys_filename : Union [str , Path ]) -> dict :
75
- """"""
85
+ """
86
+ Pypesa internal method to load the auth file
87
+
88
+ >> import pypesa
89
+ >> mpesa = pypesa()
90
+ >> pypesa.load_keys()
91
+
92
+ Return keys Dict if auth file is present
93
+
94
+ Raise FileNotFoundError if auth file is absent
95
+ """
76
96
try :
77
97
78
98
with open (keys_filename , "r" ) as auth :
@@ -88,7 +108,11 @@ def load_keys(keys_filename: Union[str, Path]) -> dict:
88
108
raise LoadingKeyError
89
109
90
110
def __generate_encrypted_key (self , session : Optional [bool ] = False ) -> str :
91
- """"""
111
+ """
112
+
113
+ Method use to Encrypt the api key and public key
114
+ so as to get a secure RSA Encrypted key
115
+ """
92
116
try :
93
117
pub_key = self .auth_keys .get ("public_key" )
94
118
raw_key = self .auth_keys .get ("api_key" )
@@ -100,7 +124,6 @@ def __generate_encrypted_key(self, session: Optional[bool] = False) -> str:
100
124
rsa_public_key = RSA .importKey (public_key_string )
101
125
raw_cipher = rsa_cipher .new (rsa_public_key )
102
126
encrypted_key = raw_cipher .encrypt (raw_key .encode ())
103
-
104
127
return base64 .b64encode (encrypted_key ).decode ("utf-8" )
105
128
106
129
except Exception as bug :
@@ -111,10 +134,16 @@ def __generate_encrypted_key(self, session: Optional[bool] = False) -> str:
111
134
112
135
@property
113
136
def path_to_auth (self ) -> str :
137
+ """
138
+ Return Path to Authentication file
139
+ """
114
140
return self .auth_path
115
141
116
142
@path_to_auth .setter
117
143
def path_to_auth (self , auth_path : Union [str , Path ]) -> str :
144
+ """
145
+ Setting new path to the authentication file
146
+ """
118
147
if isinstance (auth_path , str ):
119
148
self .auth_path = auth_path
120
149
return self .auth_path
@@ -124,20 +153,37 @@ def path_to_auth(self, auth_path: Union[str, Path]) -> str:
124
153
125
154
@property
126
155
def environment (self ) -> Union [sandbox , production ]:
156
+ """
157
+ Return the Environment the Pypesa is running
158
+
159
+ whether its Sandbox | Production
160
+ """
127
161
return self .urls
128
162
129
163
@environment .setter
130
164
def environment (self , enviro : str ) -> Union [sandbox , production ]:
165
+ """
166
+ Set new pypesa environment
167
+
168
+ Eg. changing env to production;
169
+
170
+ >> import pypesa
171
+ >> mpesa = pypesa()
172
+ >> mpesa.environment = "production"
173
+ <Using Production Urls>
174
+ """
131
175
if isinstance (enviro , str ):
132
- if enviro in ["testing " , "production" ]:
133
- if enviro == "testing " :
176
+ if enviro in ["sandbox " , "production" ]:
177
+ if enviro == "sandbox " :
134
178
self .urls = sandbox ()
135
179
else :
136
180
self .urls = production ()
137
181
print (self .urls )
138
182
return self .urls
139
- return ValueError ("Environment must be either testing or production" )
140
- return TypeError (f"environment must be of type string not { type (enviro )} " )
183
+ raise ValueError (
184
+ "Environment must be either sandbox or production" )
185
+ raise TypeError (
186
+ f"environment must be of type string not { type (enviro )} " )
141
187
142
188
@property
143
189
def api_key (self ) -> str :
@@ -164,21 +210,33 @@ def api_key(self, Api_key: str) -> str:
164
210
165
211
@property
166
212
def public_key (self ) -> str :
213
+ """
214
+ Return the current Public key
215
+ """
167
216
return self .auth_keys .get ("public_key" )
168
217
169
218
@public_key .setter
170
219
def public_key (self , pb_key : str ) -> str :
220
+ """
221
+ Set a new public key
222
+ """
171
223
if isinstance (pb_key , str ):
172
224
self .auth_keys ["public_key" ] = pb_key
173
225
return self .auth_keys ["public_key" ]
174
226
raise TypeError (f"Public key must be a string not a { type (pb_key )} " )
175
227
176
228
@property
177
229
def origin_address (self ) -> str :
230
+ """
231
+ Return the current origin address
232
+ """
178
233
return self ._origin_ip
179
234
180
235
@origin_address .setter
181
236
def origin_address (self , ip_address : str ) -> str :
237
+ """
238
+ Set a new origin address
239
+ """
182
240
if isinstance (ip_address , str ):
183
241
self ._origin_ip = ip_address
184
242
return self ._origin_ip
@@ -187,6 +245,10 @@ def origin_address(self, ip_address: str) -> str:
187
245
188
246
@authenticated
189
247
def default_headers (self , auth_key : Optional [str ] = "" ) -> dict :
248
+ """
249
+ Generate Default header to be used during a Request
250
+
251
+ """
190
252
if not auth_key :
191
253
auth_key = self .__generate_encrypted_key (session = True )
192
254
return {
@@ -205,9 +267,9 @@ def get_session_id(self) -> str:
205
267
session_id = response ["output_SessionID" ]
206
268
response_code = response ["output_ResponseCode" ]
207
269
description = response ["output_ResponseDesc" ]
208
- print (description , " " , response_code )
270
+ # print(description, " ", response_code)
209
271
if response_code == "INS-989" :
210
- print ("Session creation failed!!" )
272
+ # print("Session creation failed!!")
211
273
raise AuthenticationError
212
274
return session_id
213
275
except Exception as bug :
0 commit comments