· 6 years ago · Jan 29, 2020, 01:38 PM
1 <?php
2
3/**
4 * Description of this class: SubSocialcom kenya (sushil)
5 *
6 * @author Vipul - Mobpair
7 */
8class SubPay extends AApiBase
9{
10 //define the class variables
11 public $uid,
12 $pwd,
13 $msisdn,
14 $wapurl,
15 $imsi,
16 $csize,
17 $conf,
18 $eventids,
19 $force_eventid,
20 $product_id,
21 $orgid,
22 $seqNo='',
23 $siteController;
24
25 private $service_type;
26 const MONTH_VAL=30;
27 const WEEKLY_VAL=7;
28 const DAILY_VAL=1;
29 const defaultMSISDN='12345678';
30
31 public $apiURI=[
32 'SubApi' =>'http://pay.mgage.com/nl/purchases/new?',
33 'sub'=>'http://pay.mgage.com/nl/subscriptions/new?',
34 'unsub' =>'http://pay.mgage.com/nl/deregistrations/new?',
35 'alias'=>'http://pay.mgage.com/v1/customers/'
36 ];
37
38 /*
39 * Call the default assigment
40 */
41 public function __init($siteController)
42 {
43
44 $this->getAlias();
45 $this->siteController=$siteController;
46 $this->service_type=self::TYPE_SUB;
47//
48 if($_REQUEST['msisdn'] and $_REQUEST['msisdn']!=self::defaultMSISDN){
49
50 $this->msisdn = $_REQUEST['msisdn'];
51 W::setMSISDN($_REQUEST['msisdn']);
52
53 }
54 $flagCG = isset($this->conf['lp']) ? $this->conf['lp'] : 0;
55 $flagCG = (int) $flagCG;
56
57 if (($flagCG != 1) || $_GET['key']) {
58
59 $url= $this->getredirUrl();
60
61// //Save in msg log
62 $msgLog = $this->getCollection();
63 $msgLog->insert(['msisdn' => (string) $this->msisdn,
64 'params' => json_encode($this),
65 'type'=>"cg_url",
66 'product_id' => W::getLiveProduct()->id,
67 'event_id' => $this->getEventId(),
68 'url'=>$url,
69 'time' => new MongoDate()
70
71 ]);
72 Yii::app()->controller->redirect($url);
73 Yii::app()->end();
74//
75 }
76
77 $product= (new ProductEx)->findByPk($this->product_id);
78 $description="You will be charged from your prepaid/postpaid bill";
79 $this->siteController->render('/site/consent',['product'=>$product,'description'=>$description]);
80 Yii::app()->end();
81 }
82
83 /*
84 * get event id
85 */
86 public function getEventId()
87 {
88 $force_eventid= $this->force_eventid;
89 //check if force id exists if yes return eventid
90 if($force_eventid)
91 {
92 return $force_eventid;
93 }
94 $key= key($this->eventids);
95
96 return $this->eventids[$key];
97 }
98 private function getRequestProductUrl() {
99
100 $url = $_SERVER['REQUEST_URI'];
101 return $parseUrl = parse_url($url, PHP_URL_PATH);
102 }
103 /*
104 * get redirect Url
105 */
106 public function getRedirUrl($consent)
107 {
108 $refid= $this->getTransactionId();
109 $query='description={description}&merchant_id={merchant_id}&amount={amount}&merchant_ref={merchant_ref}&service_id={service_id}&sig={sig}&subscription_length={subscription_length}';
110 $msisdn=$this->msisdn;
111
112 $key = $this->conf['key'];
113// $key = "d114ea6c8af1fdb2568fa581b6828c08";
114 $data = "amount={amount}&description={description}&merchant_id={merchant_id}&merchant_ref={merchant_ref}&service_id={service_id}";
115 $message= strtr($data, [
116 '{description}' => $this->conf['description'],
117 '{merchant_id}' => $this->conf['merchant_id'],
118 '{amount}' => $this->conf['amount'],
119 '{merchant_ref}' => $refid,
120 '{service_id}' => rawurlencode($this->conf['service_id']),
121 ]);
122 $sig=$this->sig($message,$key);
123
124 $oquery= strtr($query, [
125 '{description}' => $this->conf['description'],
126 '{merchant_id}' => $this->conf['merchant_id'],
127 '{amount}' => $this->conf['amount'],
128 '{merchant_ref}' => $refid,
129 '{service_id}' => rawurlencode($this->conf['service_id']),
130 '{sig}' =>$sig ,
131 '{subscription_length}'=>'weekly'
132 ]);
133
134 $data=[
135 '_id'=>$refid,
136 'type'=>'Sub',
137 'sig'=>$sig,
138 'tr_id'=>$refid,
139 'time' => new MongoDate()
140 ];
141
142 $this->getTransCollection()->save($data);
143
144 $toStore = [
145 'type' => 'Subscription',
146 'product_id' => $this->product_id,
147 'msisdn' => $msisdn,
148 'm_refid'=>$refid,
149 'endpoint' => $endpoint,
150 'params' => $oquery,
151 'time' => new MongoDate()
152 ];
153 $this->getCollection()->save($toStore);
154
155 $campData=['eventId'=>$this->getEventId(), 'camp'=> $this->siteController->getCampId(), 'token'=>$this->siteController->getToken(),'device_id'=> $this->siteController->getDeviceId()];
156 W::getSession()['campData']=$campData;
157
158 $endpoint= $this->apiURI['sub'].$oquery;
159 $url=$endpoint;
160 return $url;
161
162 }
163 public function sig($message,$key){
164
165 $sig = hash_hmac('sha1',$message,$key);
166 return $sig;
167 }
168 public function storeStatusByCb(){
169
170 $params=W::getRequestParams();
171 $toStore = [
172 'type' => 'getResponse',
173 'product_id'=>W::getLiveProduct()->id,
174 'params'=> $params,
175 'time' => new MongoDate()
176 ];
177
178 $this->getCollection()->save($toStore);
179
180 if($params['action']!=""){
181
182 if($params['merchant_ref']!=''){
183 $data= $this->getTransCollection()->findOne(['_id'=>$params['merchant_ref']]);
184 }
185 if(isset($params['status']) && ($params['status']=='successful')){
186 if($data['type']=='Sub'){
187 $msg = SubPay::errorStatus()['ACT'];
188 }else{
189 $msg = SubPay::errorStatus()['DCT'];
190 }
191 }elseif(isset($params['status']) && ($params['status']=='failed')){
192 $msg = SubPay::errorStatus()[500];
193 }elseif(isset($params['status']) && ($params['status']=='cancelled')){
194 if($data['type']=='Sub'){
195 $msg = SubPay::errorStatus()['F_SUB'];
196 }else{
197 $msg = SubPay::errorStatus()['F_UNSUB'];
198 }
199 }
200 }
201
202 return $msg;
203
204 }
205 /*
206 * bulk sms
207 */
208 public function oneoffpay(){
209
210 $this->orgid = $this->conf['orgid'];
211 $refid= $this->getTransactionId();
212 $query='description={description}&merchant_id={merchant_id}&amount={amount}&merchant_ref={merchant_ref}&service_id={service_id}&sig={sig}&subscription_length={subscription_length}';
213 $msisdn=$this->msisdn;
214
215 $key = $this->conf['key'];
216// $key = "d114ea6c8af1fdb2568fa581b6828c08";
217 $data = "amount={amount}&description={description}&merchant_id={merchant_id}&merchant_ref={merchant_ref}&service_id={service_id}";
218 $message= strtr($data, [
219 '{description}' => $this->conf['description'],
220 '{merchant_id}' => $this->conf['merchant_id'],
221 '{amount}' => $this->conf['amount'],
222 '{merchant_ref}' => $refid,
223 '{service_id}' => rawurlencode($this->conf['service_id']),
224 ]);
225 $sig=$this->sig($message,$key);
226
227 $oquery= strtr($query, [
228 '{description}' => $this->conf['description'],
229 '{merchant_id}' => $this->conf['merchant_id'],
230 '{amount}' => $this->conf['amount'],
231 '{merchant_ref}' => $refid,
232 '{service_id}' => rawurlencode($this->conf['service_id']),
233 '{sig}' =>$sig ,
234 '{subscription_length}'=>'weekly'
235 ]);
236
237 $toStore = [
238 'type' => 'Subscription',
239 'product_id' => $this->product_id,
240 'msisdn' => $msisdn,
241 'endpoint' => $endpoint,
242 'params' => $oquery,
243 'time' => new MongoDate()
244 ];
245 $this->getCollection()->save($toStore);
246
247 $campData=['eventId'=>$this->getEventId(), 'camp'=> $this->siteController->getCampId(), 'token'=>$this->siteController->getToken(),'device_id'=> $this->siteController->getDeviceId()];
248 W::getSession()['campData']=$campData;
249
250 $endpoint= $this->apiURI['SubApi'].$oquery;
251 $url=$endpoint;
252 return $url;
253
254
255 }
256 /*
257 * Set cookie
258 */
259 private function setCookie($value)
260 {
261 setcookie('uid', $value, time()+60*60*24*365);
262 return $value;
263 }
264
265 public function getTransactionId() {
266 return $this->getRefId(32);
267 //return (string)(new MongoId());
268 }
269
270 /**
271 * get Msisdn from the UID using the cookies, mongo and transaction table
272 */
273 public function getCustomMsisdn() {
274
275 if(isset($_GET['?MSISDN'])){
276 $msisdn = $_GET['?MSISDN'];
277 }elseif(isset($_GET['msisdn'])){
278 $msisdn = $_GET['msisdn'];
279 } else {
280 $msisdn = self::defaultMSISDN;//testing
281 }
282 $this->getAlias($msisdn);
283 W::setMSISDN($msisdn);
284 return $msisdn;
285 }
286
287 public function getAlias($msisdn){
288
289 $endpoint = $this->apiURI['alias'];
290 $url = $endpoint . "{msisdn}/msisdn_alias";
291 $replace = [
292 "{msisdn}" => $msisdn,
293 ];
294
295 $endpoint = strtr($url, $replace);
296 echo $endpoint;
297 $headers = [
298 'connection: close',
299 ];
300
301 $curlParams = ['method' => "GET", 'url' => $endpoint, 'headers' => $headers, 'postData' => []];
302
303 $result = Common::curlRequestCall($curlParams);
304 $responseData = json_decode($result['body'], 1);
305
306
307// print_r($responseData);
308 // Mongo Store
309 $toStore = [
310 'type' => 'AliasCreate',
311 'product_id' => $this->product_id,
312 'postData' => $postData,
313 'result' => $result,
314 'request' => $curlParams,
315 'responseData' => $responseData,
316 'time' => new MongoDate()
317 ];
318
319 $this->getCollection()->save($toStore);
320
321 // if success then redirect else return product home page
322 if (!$result['curl_error']) {
323
324 if ($result['http_code'] == 200) {
325
326 if (isset($responseData['msisdn_alias'])) {
327//
328 $toStore = [
329 '_id'=>$responseData['msisdn_alias'],
330 'type' => 'AliasNumber',
331 'product_id' => $this->product_id,
332 'msisdn_alias'=>$responseData['msisdn_alias'],
333 'msisdn'=>$responseData['msisdn'],
334 'responseData' => $responseData,
335 'time' => new MongoDate()
336 ];
337 $this->getaliasCollection()->save($toStore);
338
339
340 }
341 }
342 }
343 return;
344 }
345 /* get Price info of the user
346 */
347 public function getPriceInfo()
348 {
349 $product=Product::model()->findByPk($this->product_id);
350 $priceValidity=$product->validityByEventPrice($this->eventid);
351 return $priceValidity;
352 }
353 /**
354 * @return MongoCollection Store api call data
355 */
356 public static function getCollection()
357 {
358 return Yii::app()->mongodb->pay_log;
359 }
360 public static function getTransCollection()
361 {
362 return Yii::app()->mongodb->Trans_pay_log;
363 }
364 public static function getaliasCollection()
365 {
366 return Yii::app()->mongodb->alias_pay_log;
367 }
368 /*
369 * deactivate the user for content
370 */
371 public function deactivate($sub_id)
372 {
373 //http://http1.za.oxygen8.com:9081/subs.php?username=ClientName&password=clientpass&
374 //request=unsubscribe&msisdn=27823456789&source=wap¬ify=no&listid=8042
375
376 $subcription=(new SubscriptionEx)->findByPk($sub_id);
377 /*@var $subscription SubscriptionEx */
378 $product=$subcription->product;
379
380 $refid=(new SubPay())->getTransactionId();
381
382 $relay=$product->conf['relay'];
383 $query='description={description}&merchant_id={merchant_id}&amount={amount}&merchant_ref={merchant_ref}&service_id={service_id}&sig={sig}';
384 $msisdn=$this->msisdn;
385
386 $key = $this->conf['key'];
387// $key = "d114ea6c8af1fdb2568fa581b6828c08";
388 $data = "amount={amount}&description={description}&merchant_id={merchant_id}&merchant_ref={merchant_ref}&service_id={service_id}";
389 $message= strtr($data, [
390 '{description}' => $product->conf['description'],
391 '{merchant_id}' => $product->conf['merchant_id'],
392 '{amount}' => $product->conf['amount'],
393 '{merchant_ref}' => $refid,
394 '{service_id}' => rawurlencode($product->conf['service_id']),
395 ]);
396
397 $sig=$this->sig($message,$key);
398
399
400 $oquery= strtr($query, [
401 '{description}' => $product->conf['description'],
402 '{merchant_id}' => $product->conf['merchant_id'],
403 '{amount}' => $product->conf['amount'],
404 '{merchant_ref}' => $refid,
405 '{service_id}' => rawurlencode($product->conf['service_id']),
406 '{sig}' =>$sig ,
407 ]);
408
409 $endpoint= $this->apiURI['unsub'].$oquery;
410 $url=$endpoint;
411
412 $data=[
413 '_id'=>$refid,
414 'type'=>'UnSub',
415 'sig'=>$sig,
416 'tr_id'=>$refid,
417 'time' => new MongoDate()
418 ];
419
420 (new SubPay())->getTransCollection()->save($data);
421
422 $toStore=[
423 'time'=>new MongoDate(),
424 'api_data'=>$url,
425 'msg'=>$msg,
426 'msisdn'=>$subcription->msisdn,
427 'subid'=>$subcription->id,
428 'type'=>'unsubcall'
429 ];
430 (new SubPay())->getCollection()->save($toStore);
431
432 Yii::app()->controller->redirect($url);
433 Yii::app()->end();
434 //$curlParams = ['method' => "POST", 'url' => $endpoint, 'headers' => $headers, 'postData' => ''];
435 $curlParams=['method'=>'GET','url'=>$endpoint,'headers'=>$headers];
436 $result= Common::curlRequestCall($curlParams);
437
438// print_r($url);exit;
439 $headers=[
440 'Connection: close',
441 'Content-Type: application/x-www-form-urlencoded',
442 ];
443 $getData=[];
444
445 $curlParams=['method'=> "GET", 'url' => $url, 'headers'=> $headers, 'postData'=>$getData];
446 $result=Common::curlRequestCall($curlParams);
447
448 if(!$result['curl_error']){
449 if($result['http_code'] == 200){
450 $msg="You have been successfully unsubscribed.";
451 $subcription->status= SubscriptionEx::TYPE_INACTIVE;
452 $subcription->save();
453 }else{
454 $msg='HTTP Error '.$result['http_code'].':'.(new Common())->getHttpErrorByCode($result['http_code']).'- deactivation request fail.';
455 }
456 }else{
457 $msg=$result['curl_error'];
458 }
459 $toStore=[
460 'time'=>new MongoDate(),
461 'api_data'=>$result,
462 'msg'=>$msg,
463 'msisdn'=>$subcription->msisdn,
464 'subid'=>$subcription->id,
465 'type'=>'unsubcall'
466 ];
467 (new SubPay())->getCollection()->save($toStore);
468 return [1=>$result, 2=>'', 3 => $msg];
469 }
470 /*
471 * Generate Reference id
472 * @return string $refId
473 */
474 public function getRefId($length=13)
475 {
476 $refId=substr(str_shuffle("01234567890123456789"), 0, $length);
477 return $refId;
478 }
479 /*
480 * Save the activation log mongo
481 */
482 public function getSmsText()
483 {
484 return [
485 'SUBLINK' => '{service_name}: Enjoy {content_url}.To cancel subscription send {unsubkey} to {shortcode}.',
486 'SUB'=> 'Welcome to {service_name} subscription, You will be charged {currency}.{r_price} per {freq}. To unsubscription send {unsubkey} to {shortcode}.',
487 'SUB_RENEW'=> 'Renewal for {service_name} subscription, You will be charged {currency}.{r_price} per {freq}. To unsubscription send {unsubkey} to {shortcode}.'
488 ];
489 }
490 public static function errorStatus()
491 {
492 return [
493 "MSG"=>"Successful Message Sent",
494 "F_UNSUB"=>"Failed Unsubscribe",
495 "F_SUB"=>"Failed Subscribe.",
496 "F_DCT"=>"You have not subscribed this service.",
497 "VALID_PRODUCT"=>"Please Select Valid Product.",
498 "ALREADY_ACT"=>"You are already subscribed for this service.",
499 "ALREADY_DCT"=>"You are already unsubscribed for this service.",
500 "ACT"=>"You have successfully subscribed for this service.",
501 "DCT"=>"You have successsfully unsubscribed from this service. ",
502 "INSUFBAL"=>"You have insufficient balance to subscribe this service.",
503 "U_PRO"=>"Your request is under process.",
504 "RENEW" => "Renew Service successfully",
505 500 => "Something went wrong, please try after sometime!",
506 "REF" => "Refund complete",
507 "PERROR" => "Please filled all parameter"
508 ];
509 }
510 public static function errorCode()
511 {
512 return [
513 200 => 'Request accepted',
514 530 => 'Missing Mandatory Parameter',
515 531 => 'Some Parameter Value is Wrong',
516 532 => 'CP Validation Failure, Incorrect CPID or password',
517 533 => 'Product Validation Failure, Product not configured At CG End',
518 536 => 'Same transaction pending with same CP id and msisdn and same transaction id',
519 538 => 'System error (CP’s will re-try )',
520 600 => 'System Error',
521 400 => 'Bad Request',
522 401 => 'Unauthorized',
523 403 => 'Forbidden',
524 404 => 'Not Found',
525 405 => 'Method Not Allowed',
526 406 => 'Not Acceptable – You requested a format that isn’t JSON',
527 429 => 'Too Many Requests – You’re requesting too many kittens! Slow down!',
528 500 => 'Internal Server Error – We had a problem with our server. Try again later.',
529 503 => 'Service Unavailable – We’re temporarily offline for maintenance. Please try again later.'
530 ];
531 }
532
533
534}