· 6 years ago · Jan 20, 2020, 09:00 AM
1 <?php
2//require "openssl";
3
4/**
5 * Description of SubPalenstine
6 *
7 * @author rinkal@mobpair
8 */
9class SubpayMgage extends AApiBase {
10
11 public $uid,
12 $pwd,
13 $service_id,
14 $merchand_id,
15 $amount,
16 $description,
17 $merchand_ref,
18 $subscription_length,
19 $msisdn,
20 $sig,
21 $wapurl,
22 $imsi,
23 $csize,
24 $operator,
25 $conf,
26 $eventids,
27 $event_id,
28
29 $force_eventid,
30 $product_id,
31 $orgid,
32 $siteController;
33 private $service_type;
34
35 public $apiURI = [
36 'api' => 'http://pay.mgage.com/', //
37 'subscribe' => 'http://pay.mgage.com/nl/subscriptions/new?', // for consent at operator
38 'getToken' =>'http://dcb.universe-telecom.com/api/token'
39 ];
40 const defaultMSISDN = '1111111111';
41
42 public function __init($siteController) {
43// error_reporting(E_ALL);
44// exit;
45 $this->siteController = $siteController;
46 $this->service_type = self::TYPE_SUB;
47
48 $flagCG = isset($this->conf['lp']) ? $this->conf['lp'] : 0;
49 $flagCG = (int) $flagCG;
50
51// $this->getAuthToken();
52// if($_REQUEST['otpchk']){
53// $code = $_REQUEST['otp'];
54// $this->verifyPinSub($code);
55// }
56// if ($_REQUEST['msisdn']) {
57// if(isset(W::getSession()["msisdn_heKey"]) && W::getSession()["msisdn_heKey"]!=""){
58// $this->msisdn =$_REQUEST['msisdn'];
59// W::setMSISDN($_REQUEST['msisdn']);
60// }else{
61// $this->msisdn = "972".ltrim($_REQUEST['msisdn'],'0');
62// W::setMSISDN("972".ltrim($_REQUEST['msisdn'],'0'));
63// }
64// }
65 // Check already subscription
66 $this->checkAlready($this->msisdn, W::getLiveProduct()->id);
67
68 if (($flagCG != 1) || $_GET['key']) {
69
70 $statusMsg = $this->getredirUrl();
71 $msisdn=$this->msisdn;
72
73 $msgLog = $this->getCollection();
74 $msgLog->insert(['msisdn' => (string) $this->msisdn,
75 'params' => json_encode($this),
76 'type' => "cg_url",
77 'product_id' => $this->product_id, //W::getLiveProduct()->id,
78 'event_id' => $this->getEventId(),
79 'HE' => ($this->msisdn == self::defaultMSISDN) ? 'NO' : 'YES',
80 'url' => $url,
81 'time' => new MongoDate()
82 ]);
83 Yii::app()->controller->redirect(W::getProductHomePageUrl($this->product_id) . '?msg_var=smsg&smsg=' . urlencode($statusMsg) . '&noredirect=Y&msisdn=' . $msisdn);
84 Yii::app()->end();
85
86 }
87 $product = (new ProductEx)->findByPk($this->product_id);
88 $description = "You will be charged from your prepaid/postpaid bill";
89 $this->siteController->render('/site/consent', ['product' => $product, 'description' => $description]);
90 Yii::app()->end();
91 }
92
93 /**
94 * Redirect url
95 */
96
97 public function getredirUrl() {
98//
99 return $url = $this->subscribeReq();
100 }
101 /**
102 * User redirect for purchase and Auth
103 * @return type
104 */
105 public function subscribeReq(){
106// $endpoint = $this->apiURI['api'];
107// echo "<pre>";
108// print_r($endpoint);
109// exit;
110
111// $v=$_REQUEST['v'];
112// if(isset($_REQUEST['validity']) && $_REQUEST['validity']!=""){
113// $v=$_REQUEST['validity'];
114// }
115// $purchaseId=$this->conf['eDetails'][$v];
116// $this->event_id=$purchaseId['eid'];
117// $priceDeatils=$this->getPriceInfo();
118
119 $msg = $this->errorStatus()[500];
120
121// $headers = [
122// 'connection: close',
123// 'Content-Type: application/json',
124// 'Authorization: Bearer '.$this->conf['accessToken']
125// ];
126
127 $serviceid = $this->conf['serviceid'];
128 $MerchantID = $this->conf['MerchantID'];
129 $amount = $this->conf['amount'];//$this->conf['ProductAmount'],
130 //"OrderPrice" => $priceDeatils['price'],
131 //"MSISDN" => ltrim(W::getMSISDN(),'972'),//$this->msisdn ,
132 $description = $this->conf['description'];
133 $merchant_ref = $this->conf['merchant_ref'];
134 $subscriptionLength = $_REQUEST['validity'];
135 $key = "d114ea6c8af1fdb2568fa581b6828c08";
136 $message = "amount=100&description=CosmosRingtone&merchant_id=1&merchant_ref=c39197a1ff43160542c593d5016d4217&service_id=1";
137
138 $signature = hash_hmac("sha1", $key, $message, true);
139 $data = base64_encode($signature);
140
141//$digest = sha1('sha1');
142 //$digest = sha1('sha1');
143 //$digest = OpenSSL::Digest.new('sha1');
144// $sig = hash_hmac('sha1',$key,$message);
145 echo $data;
146 exit;
147// $data = $subscriptionLength[$v];
148// echo "<pre>";
149// print_r($data);
150// exit;
151
152 //"IsProcessed" =>0 ,// $this->conf['IsProcessed'],
153 //"isVerifiedPin" =>0 // $this->conf['isVerifiedPin'],
154 $url = $this->apiURI['subscribe'] . "description={description}&MerchantID={MerchantID}&amount={amount}&merchant_ref={merchant_ref}&serviceid={serviceid}&subscriptionLength={subscriptionLength}&sig={sig}";
155 $replace = [
156 '{description}' => $description,
157 '{MerchantID}' => $MerchantID,
158 '{amount}' => $amount,
159 '{merchant_ref}' => $merchant_ref,
160 '{serviceid}' => $serviceid,
161 '{subscriptionLength}' => $subscriptionLength,
162 '{sig}' => $sig,
163
164 ];
165
166 $url = strtr($url, $replace);
167// echo "<pre>";
168// print_r($url);
169// exit;
170 // http://pay.mgage.com/nl/subscriptions/new?description=weekly&MerchantID=41&amount=100&merchant_ref=c39197a1ff43160542c593d5016d4217&serviceid=109&subscriptionLength=7&sig=rinkal
171 // http://pay.mgage.com/nl/subscriptions/new?description=WeeklyRingtones&merchant_id=1&amount=100&merchant_ref=c39197a1ff43160542c593d5016d4217&service_id=1&subscription_length=weekly&sig=generatedsignature
172 $data = json_encode($replace);
173 $curlParams = ['method' => "GET", 'url' => $url, 'postData' => ''];
174 $result = Common::curlRequestCall($curlParams);
175 $responseData = json_decode($result['body'], true);
176 // Mongo Store
177 $toStore = [
178 'type' => 'subscribe',
179 'product_id' => $this->product_id,
180 //'msisdn' => $msisdn,
181 'curlParams' => $curlParams,
182 'result' => $result,
183 'resData' => $responseData,
184 'time' => new MongoDate()
185 ];
186 echo "<pre>";
187 print_r($toStore);
188 //exit;
189 $this->getCollection()->save($toStore);
190 if (!$result['curl_error']) {
191 if ($result['http_code'] == 200) {
192// if ($responseData['Success'] == true) {
193////
194// $response_id = $responseData['Message']['ID'];
195// $response_pincode = $responseData['Message']['PinCode'];
196// W::getSession()["response_id"] = $response_id;
197// W::getSession()["response_pin"] = $response_pincode;
198//
199// $otp = '&otp=enter';
200// $msg = 'تم ارسال رمز التفعيل بنجاح'; //Otp sent successfully
201// $url = W::getProductHomeUrl() . '?msg_var=smsg&smsg=' . urlencode($msg) . "$otp";
202// Yii::app()->controller->redirect($url);
203// Yii::app()->end();
204// } else if ($responseData['Success'] == FALSE) {
205// $url = W::getProductHomeUrl() . '?msg_var=smsg&smsg=' . urlencode($responseData['Message']) . "$otp";
206// Yii::app()->controller->redirect($url);
207// Yii::app()->end();
208//// $msg= $this->errorStatus()['F_SUB'];
209// }
210// } else {
211// $msg = $this->errorStatus()[500];
212// }
213 }
214 return $msg;
215 }
216 }
217
218 /**
219 * User verification for pin-code
220 * @return type
221 */
222 public function verifyPinSub($code){
223
224 $msg = $this->errorStatus()[500];
225
226 $endpoint = $this->apiURI['PinValidate']."id=".W::getSession()["response_id"];
227// $endpoint= strtr($endpoint, ['{id}'=>W::getSession()["response_id"]]);
228 $headers = [
229 'connection: close',
230 'Content-Type: application/json',
231 'Authorization: Bearer '.$this->conf['accessToken']
232 ];
233
234 $postData = [
235 "PinCode" => $code,
236 ];
237
238 $data=json_encode($postData);
239 $curlParams = ['method' => "PUT", 'url' => $endpoint, 'headers' => $headers, 'postData' => $data];
240 $result = Common::curlRequestCall($curlParams);
241 $responseData = json_decode($result['body'],1);
242
243 $toStore = [
244 'type' => 'pinVerify',
245 'product_id' => $this->product_id,
246 'msisdn' => $this->msisdn,
247 'curlParams' => $curlParams,
248 'result' => $result,
249 'resData' => $responseData,
250 'time' => new MongoDate()
251 ];
252 $this->getCollection()->save($toStore);
253 $otp="";
254
255 if (!$result['curl_error']) {
256 if ($result['http_code'] == 200) {
257 if ($responseData['Success'] == true) {
258
259 $msg = $this->errorStatus()['ACT'];
260 }
261 elseif($responseData['Success'] == false) {
262
263// $msg = $this->errorStatus()['F_SUB'];
264 $otp='&otp=enter';
265 $msg =$responseData['Message'];
266 }
267 }
268 }
269 $url = W::getProductHomeUrl().'?msg_var=smsg&smsg='.urlencode($msg)."$otp";
270 Yii::app()->controller->redirect($url);
271 Yii::app()->end();
272 }
273
274 public function getCustomMsisdn() {
275//
276 $msisdn = self::defaultMSISDN;
277
278 // for HE flow
279// if (isset($_COOKIE['uid'])) {
280//
281// $uid = isset($_COOKIE['uid']) ? $_COOKIE['uid'] : '';
282// $uidrel = Yii::app()->mongodb->uid_relation;
283// $tidData = $uidrel->findOne(['uid' => $uid]);
284//// echo $uid,'===>';
285//// var_dump($cbData);
286// if ($tidData) {
287// $msisdn = $tidData['msisdn'];
288// if ($msisdn != self::defaultMSISDN) {
289// W::getSession()['x-msisdn'] = $msisdn; //remove (int)
290// }
291// }
292// else{
293// $msisdn = self::defaultMSISDN;
294// $this->msisdn = $msisdn;
295// }
296// }
297 return $msisdn;
298 }
299
300 /*
301 * get product Url
302 */
303
304 private function getRequestProductUrl() {
305
306 $url = $_SERVER['REQUEST_URI'];
307 return $parseUrl = parse_url($url, PHP_URL_PATH);
308 }
309
310 private function getMsisdnRequest() {
311
312 $msisdn = self::defaultMSISDN;
313 $endpoint = W::getLiveProduct()->conf['heURL'];
314 $headers = [
315 'connection: close',
316 'Content-Type: application/json'
317 ];
318
319 $curlParams = ['method' => "GET", 'url' => $endpoint, 'headers' => $headers];
320 $result = Common::curlRequestCall($curlParams);
321 $responseData = json_decode($result['body'],1);
322
323 if (!$result['curl_error']) {
324 if ($result['http_code'] == 200) {
325 if ($responseData['data']['msisdn']) {
326 $msisdn=$responseData['data']['msisdn'];
327 W::setMSISDN($msisdn);
328 }
329 }
330 }
331 $uidRel = Yii::app()->mongodb->uid_relation;
332 $cbData=$uidRel->findOne(['msisdn' => $msisdn]);
333 if($cbData){
334 $this->setCookie($cbData['uid']);
335 }else{
336 if($msisdn!=self::defaultMSISDN){
337 $uid= $this->setCookie($this->getRefId());
338 $insertArr=['uid'=> $uid, 'msisdn'=> $msisdn];
339 $uidRel->save($insertArr);
340 }
341 }
342 $toStore = [
343 'type' => 'requestMsisdn',
344 'product_id' => W::getLiveProduct()->id,
345 'msisdn' => $msisdn,
346 'curlParams' => $curlParams,
347 'result' => $result,
348 'resData' => $responseData,
349 'time' => new MongoDate()
350 ];
351 $this->getCollection()->save($toStore);
352 return $msisdn;
353 }
354
355 public function getAuthToken(){
356
357 $msg = $this->errorStatus()[500];
358
359 $endpoint = $this->apiURI['getToken'];
360 $headers = [
361 'connection: close',
362// 'Content-Type: application/json',
363 ];
364 $postData = [
365 "grant_type"=>"password",
366 "username"=>$this->conf['uid'],
367 "password"=>$this->conf['pwd']
368 ];
369 $data= http_build_query($postData);
370 $curlParams = ['method' => "POST", 'url' => $endpoint, 'headers' => $headers, 'postData' => $data];
371
372 $result = Common::curlRequestCall($curlParams);
373 $toStore = [
374 'type' => 'GetAuthToken',
375 'product_id' => $this->product_id,
376 'msisdn' => $this->msisdn,
377 'curlParams' => $curlParams,
378 'result' => $result,
379 'time' => new MongoDate()
380 ];
381 $this->getCollection()->save($toStore);
382 }
383
384 public function getPriceInfo()
385 {
386 $product=Product::model()->findByPk($this->product_id);
387 $priceValidity=$product->validityByEventPrice($this->event_id);
388 return $priceValidity;
389 }
390
391 /**
392 * Check user Subscription
393 */
394 public function checkAlready($msisdn, $product_id) {
395 $subInfo = (new SubscriptionEx())->getSubscription($msisdn, $product_id, 365);
396// echo "<pre>";
397// print_r($subInfo);exit;
398 if ($subInfo and ( $subInfo->status == SubscriptionEx::TYPE_ACTIVE or $subInfo->status == SubscriptionEx::TYPE_GRACE)) {
399 $statusMsg = SubPalestine::errorStatus()['ALREADY_ACT'];
400 W::setMSISDN($msisdn);
401 Yii::app()->controller->redirect(W::getProductHomePageUrl($product_id) . '?msg_var=smsg&smsg=' . urlencode($statusMsg) . '&noredirect=Y&msisdn=' . $msisdn);
402 Yii::app()->end();
403 exit();
404 }
405 }
406
407 /*
408 * Set cookie
409 */
410
411 public function setCookie($value) {
412 setcookie('uid', $value, time() + 60 * 60 * 24 * 365);
413 return $value;
414 }
415
416 /**
417 * @return MongoCollection Store api call data
418 */
419 public static function getCollection() {
420 return Yii::app()->mongodb->palestine_logs;
421 }
422
423 /*
424 * Generate Reference id
425 * @return string $refId
426 */
427
428 public function getRefId($length = 9) {
429 $refId = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
430 return $refId;
431 }
432
433 /*
434 * Generate Reference id
435 * @return string $refId
436 */
437
438 public function getReqId($length = 6) {
439 $refId = substr(str_shuffle("0812345678998765432160"), 0, $length);
440 return $refId;
441 }
442
443 /*
444 * Save the token mongo
445 */
446
447 public function saveTokenByCpid($refId) {
448
449 if (!$this->siteController)
450 $this->siteController = new SiteController();
451 $tokenCamp = new MongoCampTransaction();
452 $tokenCamp->_id = $refId;
453 $tokenCamp->camp = $this->siteController->getCampId();
454 $tokenCamp->token = $this->siteController->getToken();
455 $tokenCamp->device_id = $this->siteController->getDeviceId();
456 $tokenCamp->phone = (string) W::getMSISDN();
457 $tokenCamp->datetime = new MongoDate();
458 $tokenCamp->save();
459 }
460
461 /**
462 * get eventid
463 * @return type
464 */
465 public function getEventId() {
466 $force_eventid = $this->force_eventid;
467 //checks whether eventid is corrent or not
468 if ($force_eventid) {
469 return $force_eventid;
470 }
471 $key = key($this->eventids);
472
473 return $this->eventids[$key];
474 }
475
476 /**
477 * Get productinfo by product and event_id
478 * @param type $productId
479 * @param type $eventId
480 * @return type
481 */
482 public function getProductInfo($productId, $eventId) {
483
484 $sql = "select price, validity, content,eventid, operator_id from product_price where product_id='{$productId}' " .
485 ($eventId ? "and eventid='$eventId' " : '') . " order by price desc limit 1";
486 try {
487 $row = Yii::app()->db->createCommand($sql)->queryRow();
488 return $row;
489 } catch (Exception $exc) {
490 //echo $exc->getTraceAsString();
491 }
492 }
493
494 /**
495 * get Statuses
496 */
497 public static function errorStatus() {
498 return
499 [
500 "MSG"=>"تم إرسال الرسالة الناجحة",//Successful Message Sent
501 "F_UNSUB"=>"فشل إلغاء الاشتراك",//Failed Unsubscribe
502 "F_SUB"=>"فشل الاشتراك",//Failed Subscribe
503 "F_DCT"=>"لم تشترك في هذه الخدمة.",//You have not subscribed this service.
504 "VALID_PRODUCT"=>"يرجى اختيار منتج صالح.",//Please Select Valid Product.
505 "ALREADY_ACT"=>"أنت مشترك بالفعل في هذه الخدمة.",//You are already subscribed for this service.
506 "ALREADY_DCT"=>"أنت مشترك بالفعل في هذه الخدمة.",//You are already unsubscribed for this service.
507 "ACT"=>"لقد اشتركت بنجاح في هذه الخدمة.",//You have successfully subscribed for this service.
508 "DCT"=>"لقد نجحت في إلغاء اشتراكك في هذه الخدمة. ",//You have successsfully unsubscribed from this service.
509 "INSUFBAL"=>"ليس لديك رصيد كافٍ للاشتراك في هذه الخدمة.",//You have insufficient balance to subscribe this service.
510 "U_PRO"=>"طلبك قيد العملية.",//Your request is under process.
511 "RENEW" => "تجديد الخدمة بنجاح",//Renew Service successfully
512 500 => "حدث خطأ ما ، يرجى المحاولة بعد وقت ما!",//Something went wrong, please try after sometime!
513 "REF" => "استرداد كامل",//Refund complete
514 "PERROR" => "يرجى ملء جميع المعلمة"//Please filled all parameter
515
516 ];
517 }
518
519 /**
520 * Get sms text
521 * @return type
522 */
523 public function getSmsText() {
524 return [
525 'SUBLINK' => '{service_name}: Enjoy {service_url}.To cancel subscription send {unsubkey} to {shortcode}.',
526 'UNSUB' => 'You have successfully unsubscribed {service_name} service. Visit {product_url} to subscribe again.',
527 'SUB' => 'Welcome to {service_name} subscription, you will receive {freq_count} content {freq}. To unsubscription send {unsubkey} to {shortcode}.',
528 'RENEW' => 'Your subscription to {service_name} has been renewed at Rs.{price}+taxes. Next renewal will be on {freq}.'
529 ];
530 }
531
532 /**
533 * operator list display in home page
534 * @return type
535 */
536 public function getOperator() {
537
538 return [
539 '56' => 'Wataniya',
540 '59' => 'Jawwal'
541 ];
542 }
543
544}