progress in multi pay gateways

This commit is contained in:
Hesabix 2025-02-08 01:27:57 +00:00
parent 474ec05a53
commit af3d3a9c06
5 changed files with 412 additions and 402 deletions

View file

@ -148,13 +148,13 @@ class AdminController extends AbstractController
} }
#[Route('/api/admin/business/search', name: 'admin_business_list_search')] #[Route('/api/admin/business/search', name: 'admin_business_list_search')]
public function admin_business_list_search(Extractor $extractor,Jdate $jdate, #[CurrentUser] ?User $user, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, Request $request): Response public function admin_business_list_search(Extractor $extractor, Jdate $jdate, #[CurrentUser] ?User $user, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, Request $request): Response
{ {
$params = []; $params = [];
if ($content = $request->getContent()) { if ($content = $request->getContent()) {
$params = json_decode($content, true); $params = json_decode($content, true);
} }
$items = $entityManager->getRepository(Business::class)->findByPage($params['options']['page'],$params['options']['rowsPerPage'],$params['search']); $items = $entityManager->getRepository(Business::class)->findByPage($params['options']['page'], $params['options']['rowsPerPage'], $params['search']);
$resp = []; $resp = [];
foreach ($items as $item) { foreach ($items as $item) {
$temp = []; $temp = [];
@ -173,13 +173,13 @@ class AdminController extends AbstractController
} }
#[Route('/api/admin/users/search', name: 'admin_users_list_search')] #[Route('/api/admin/users/search', name: 'admin_users_list_search')]
public function admin_users_list_search(Extractor $extractor,Jdate $jdate, #[CurrentUser] ?User $user, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, Request $request): Response public function admin_users_list_search(Extractor $extractor, Jdate $jdate, #[CurrentUser] ?User $user, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, Request $request): Response
{ {
$params = []; $params = [];
if ($content = $request->getContent()) { if ($content = $request->getContent()) {
$params = json_decode($content, true); $params = json_decode($content, true);
} }
$items = $entityManager->getRepository(User::class)->findByPage($params['options']['page'],$params['options']['rowsPerPage'],$params['search']); $items = $entityManager->getRepository(User::class)->findByPage($params['options']['page'], $params['options']['rowsPerPage'], $params['search']);
$resp = []; $resp = [];
foreach ($items as $item) { foreach ($items as $item) {
$temp = []; $temp = [];
@ -340,23 +340,25 @@ class AdminController extends AbstractController
} }
#[Route('/api/admin/settings/system/info', name: 'admin_settings_system_info')] #[Route('/api/admin/settings/system/info', name: 'admin_settings_system_info')]
public function admin_settings_system_info(Jdate $jdate, #[CurrentUser] ?User $user, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, Request $request): Response public function admin_settings_system_info(registryMGR $registryMGR, Jdate $jdate, #[CurrentUser] ?User $user, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, Request $request): Response
{ {
$item = $entityManager->getRepository(Settings::class)->findAll()[0]; $item = $entityManager->getRepository(Settings::class)->findAll()[0];
$resp = []; $resp = [];
$resp['keywords'] = $item->getSiteKeywords(); $resp['keywords'] = $item->getSiteKeywords();
$resp['description'] = $item->getDiscription(); $resp['description'] = $item->getDiscription();
$resp['scripts'] = $item->getScripts(); $resp['scripts'] = $item->getScripts();
$resp['zarinpal'] = $item->getZarinpalMerchant(); $resp['zarinpal'] = $registryMGR->get('system', key: 'zarinpalKey');;
$resp['footerScripts'] = $item->getFooterScripts(); $resp['footerScripts'] = $item->getFooterScripts();
$resp['appSite'] = $item->getAppSite(); $resp['appSite'] = $item->getAppSite();
$resp['footer'] = $item->getFooter(); $resp['footer'] = $item->getFooter();
$resp['activeGateway'] = $registryMGR->get('system', key: 'activeGateway');
$resp['parsianGatewayAPI'] = $registryMGR->get('system', key: 'parsianGatewayAPI');
return $this->json($resp); return $this->json($resp);
} }
#[Route('/api/admin/settings/system/info/save', name: 'admin_settings_system_info_save')] #[Route('/api/admin/settings/system/info/save', name: 'admin_settings_system_info_save')]
public function admin_settings_system_info_save(EntityManagerInterface $entityManager, Request $request): Response public function admin_settings_system_info_save(registryMGR $registryMGR, EntityManagerInterface $entityManager, Request $request): Response
{ {
$params = []; $params = [];
if ($content = $request->getContent()) { if ($content = $request->getContent()) {
@ -367,10 +369,12 @@ class AdminController extends AbstractController
$item->setSiteKeywords($params['keywords']); $item->setSiteKeywords($params['keywords']);
$item->setDiscription($params['description']); $item->setDiscription($params['description']);
$item->setScripts($params['scripts']); $item->setScripts($params['scripts']);
$item->setZarinpalMerchant($params['zarinpal']); $registryMGR->update('system', 'zarinpalKey', $params['zarinpal']);
$item->setFooterScripts($params['footerScripts']); $item->setFooterScripts($params['footerScripts']);
$item->setAppSite($params['appSite']); $item->setAppSite($params['appSite']);
$item->setFooter($params['footer']); $item->setFooter($params['footer']);
$registryMGR->update('system', 'activeGateway', $params['activeGateway']);
$registryMGR->update('system', 'parsianGatewayAPI', $params['parsianGatewayAPI']);
$entityManager->persist($item); $entityManager->persist($item);
$entityManager->flush(); $entityManager->flush();
return $this->json(['result' => 1]); return $this->json(['result' => 1]);
@ -561,7 +565,7 @@ class AdminController extends AbstractController
]); ]);
} }
#[Route('/api/admin/logs/last', name: 'api_admin_logs_last')] #[Route('/api/admin/logs/last', name: 'api_admin_logs_last')]
public function api_admin_logs_last(Extractor $extractor,Jdate $jdate, EntityManagerInterface $entityManager): JsonResponse public function api_admin_logs_last(Extractor $extractor, Jdate $jdate, EntityManagerInterface $entityManager): JsonResponse
{ {
$logs = $entityManager->getRepository(\App\Entity\Log::class)->findBy([], ['id' => 'DESC'], 250); $logs = $entityManager->getRepository(\App\Entity\Log::class)->findBy([], ['id' => 'DESC'], 250);
$temps = []; $temps = [];
@ -583,16 +587,16 @@ class AdminController extends AbstractController
} }
#[Route('/api/admin/onlineusers/list', name: 'api_admin_online_users_list')] #[Route('/api/admin/onlineusers/list', name: 'api_admin_online_users_list')]
public function api_admin_online_users_list(Extractor $extractor,Jdate $jdate, EntityManagerInterface $entityManager): JsonResponse public function api_admin_online_users_list(Extractor $extractor, Jdate $jdate, EntityManagerInterface $entityManager): JsonResponse
{ {
$tokens = $entityManager->getRepository(UserToken::class)->getOnlines(120); $tokens = $entityManager->getRepository(UserToken::class)->getOnlines(120);
$res = []; $res = [];
foreach($tokens as $token){ foreach ($tokens as $token) {
$res[] = [ $res[] = [
'name' => $token->getUser()->getFullName(), 'name' => $token->getUser()->getFullName(),
'email'=>$token->getUser()->getEmail(), 'email' => $token->getUser()->getEmail(),
'mobile'=>$token->getUser()->getMobile(), 'mobile' => $token->getUser()->getMobile(),
'lastActive'=>$token->getLastActive() - time(), 'lastActive' => $token->getLastActive() - time(),
]; ];
} }
return $this->json($res); return $this->json($res);
@ -621,16 +625,16 @@ class AdminController extends AbstractController
public function script2(EntityManagerInterface $entitymanager): JsonResponse public function script2(EntityManagerInterface $entitymanager): JsonResponse
{ {
$banks = $entitymanager->getRepository(BankAccount::class)->findAll(); $banks = $entitymanager->getRepository(BankAccount::class)->findAll();
foreach( $banks as $bank ){ foreach ($banks as $bank) {
if($bank->getMoney() == null){ if ($bank->getMoney() == null) {
$bank->setMoney($bank->getBid()->getMoney()); $bank->setMoney($bank->getBid()->getMoney());
$entitymanager->persist($bank); $entitymanager->persist($bank);
} }
} }
$items = $entitymanager->getRepository(Cashdesk::class)->findAll(); $items = $entitymanager->getRepository(Cashdesk::class)->findAll();
foreach( $items as $item ){ foreach ($items as $item) {
if($item->getMoney() == null){ if ($item->getMoney() == null) {
$item->setMoney($item->getBid()->getMoney()); $item->setMoney($item->getBid()->getMoney());
$entitymanager->persist($bank); $entitymanager->persist($bank);
} }

View file

@ -9,6 +9,7 @@ use App\Service\Access;
use App\Service\Jdate; use App\Service\Jdate;
use App\Service\Log; use App\Service\Log;
use App\Service\Notification; use App\Service\Notification;
use App\Service\PayMGR;
use App\Service\Provider; use App\Service\Provider;
use App\Service\twigFunctions; use App\Service\twigFunctions;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
@ -25,41 +26,42 @@ use Symfony\Component\String\Slugger\SluggerInterface;
class ArchiveController extends AbstractController class ArchiveController extends AbstractController
{ {
private function getArchiveInfo(EntityManagerInterface $entityManager,array $acc){ private function getArchiveInfo(EntityManagerInterface $entityManager, array $acc)
{
$orders = $entityManager->getRepository(ArchiveOrders::class)->findBy([ $orders = $entityManager->getRepository(ArchiveOrders::class)->findBy([
'bid'=>$acc['bid'], 'bid' => $acc['bid'],
'status'=>100 'status' => 100
]); ]);
$totalSize = 0; $totalSize = 0;
foreach ($orders as $order){ foreach ($orders as $order) {
if($order->getExpireDate()>= time()) if ($order->getExpireDate() >= time())
$totalSize += $order->getOrderSize(); $totalSize += $order->getOrderSize();
} }
$usedSize = 0; $usedSize = 0;
$files = $entityManager->getRepository(ArchiveFile::class)->findBy(['bid'=>$acc['bid']]); $files = $entityManager->getRepository(ArchiveFile::class)->findBy(['bid' => $acc['bid']]);
foreach ($files as $file) foreach ($files as $file)
$usedSize += $file->getFileSize(); $usedSize += $file->getFileSize();
return [ return [
'size' => $totalSize * 1024, 'size' => $totalSize * 1024,
'remain'=>($totalSize * 1024) - $usedSize, 'remain' => ($totalSize * 1024) - $usedSize,
'used'=>$usedSize 'used' => $usedSize
]; ];
} }
#[Route('/api/archive/info', name: 'app_archive_info')] #[Route('/api/archive/info', name: 'app_archive_info')]
public function app_archive_info(Provider $provider,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): JsonResponse public function app_archive_info(Provider $provider, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): JsonResponse
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$resp = $this->getArchiveInfo($entityManager,$acc); $resp = $this->getArchiveInfo($entityManager, $acc);
return $this->json($resp); return $this->json($resp);
} }
#[Route('/api/archive/order/settings', name: 'app_archive_order_settings')] #[Route('/api/archive/order/settings', name: 'app_archive_order_settings')]
public function app_archive_order_settings(twigFunctions $functions,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): JsonResponse public function app_archive_order_settings(twigFunctions $functions, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): JsonResponse
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$settings = $functions->systemSettings(); $settings = $functions->systemSettings();
return $this->json([ return $this->json([
@ -68,150 +70,90 @@ class ArchiveController extends AbstractController
} }
#[Route('/api/archive/order/submit', name: 'app_archive_order_submit')] #[Route('/api/archive/order/submit', name: 'app_archive_order_submit')]
public function app_archive_order_submit(twigFunctions $functions,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): JsonResponse public function app_archive_order_submit(PayMGR $payMGR, twigFunctions $functions, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): JsonResponse
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$params = []; $params = [];
if ($content = $request->getContent()) { if ($content = $request->getContent()) {
$params = json_decode($content, true); $params = json_decode($content, true);
} }
$settings = $functions->systemSettings();
$order = new ArchiveOrders(); $order = new ArchiveOrders();
$order->setBid($acc['bid']); $order->setBid($acc['bid']);
$order->setSubmitter($this->getUser()); $order->setSubmitter($this->getUser());
$order->setDateSubmit(time()); $order->setDateSubmit(time());
$order->setGatePay('zarinpal'); $order->setPrice($params['space'] * $params['month'] * $settings->getStoragePrice());
$order->setDes('خرید سرویس فضای ابری به مقدار ' . $params['space'] . ' گیگابایت به مدت ' . $params['month'] . ' ماه '); $order->setDes('خرید سرویس فضای ابری به مقدار ' . $params['space'] . ' گیگابایت به مدت ' . $params['month'] . ' ماه ');
$order->setOrderSize($params['space']);
$settings = $functions->systemSettings(); $order->setMonth($params['month']);
if(array_key_exists('space',$params) && array_key_exists('month',$params)){ $entityManager->persist($order);
$order->setPrice($params['space'] * $params['month'] * $settings->getStoragePrice()); $entityManager->flush();
$order->setOrderSize($params['space']); $result = $payMGR->createRequest($order->getPrice(), $this->generateUrl('api_archive_buy_verify', ["id"=>$order->getId()], UrlGeneratorInterface::ABSOLUTE_URL), 'خرید فضای ابری');
$order->setMonth($params['month']); if ($result['Success']) {
$order->setGatePay($result['gate']);
$entityManager->persist($order);
$entityManager->flush();
$log->insert('سرویس فضای ابری', 'صدور فاکتور سرویس فضای ابری به مقدار ' . $params['space'] . ' گیگابایت به مدت ' . $params['month'] . ' ماه ', $this->getUser(), $acc['bid']);
} }
else return $this->json($result);
throw $this->createAccessDeniedException();
$data = array("merchant_id" => $settings->getZarinpalMerchant(),
"amount" => $order->getPrice(),
"callback_url" => $this->generateUrl('api_archive_buy_verify',[],UrlGeneratorInterface::ABSOLUTE_URL),
"description" => 'خرید سرویس فضای ابری',
);
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/request.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
$result = curl_exec($ch);
$err = curl_error($ch);
$result = json_decode($result, true, JSON_PRETTY_PRINT);
curl_close($ch);
if ($err) {
throw $this->createAccessDeniedException($err);
} else {
if (empty($result['errors'])) {
if ($result['data']['code'] == 100) {
$order->setStatus(0);
$order->setVerifyCode($result['data']['authority']);
$entityManager->persist($order);
$entityManager->flush();
$log->insert('سرویس فضای ابری','صدور فاکتور سرویس فضای ابری به مقدار ' . $params['space'] . ' گیگابایت به مدت ' . $params['month']. ' ماه ' ,$this->getUser(),$acc['bid']);
return $this->json([
'authority' => $result['data']["authority"]
]);
}
}
}
throw $this->createAccessDeniedException();
} }
#[Route('/api/archive/buy/verify', name: 'api_archive_buy_verify')] #[Route('/api/archive/buy/verify/{id}', name: 'api_archive_buy_verify')]
public function api_archive_buy_verify(twigFunctions $functions,Notification $notification,Request $request,EntityManagerInterface $entityManager,Log $log): Response public function api_archive_buy_verify(string $id, PayMGR $payMGR, twigFunctions $functions, Notification $notification, Request $request, EntityManagerInterface $entityManager, Log $log): Response
{ {
$Authority = $request->get('Authority'); $req = $entityManager->getRepository(ArchiveOrders::class)->find($id);
$req = $entityManager->getRepository(ArchiveOrders::class)->findOneBy(['verifyCode'=>$Authority]); if (!$req)
//get system settings throw $this->createNotFoundException('');
$settings = $functions->systemSettings();
$data = array("merchant_id" => $settings->getZarinpalMerchant(), "authority" => $Authority, "amount" => $req->getPrice());
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/verify.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v4');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
$result = curl_exec($ch); $res = $payMGR->verify($req->getPrice(), $id, $request);
$err = curl_error($ch); if ($res['Success'] == false) {
curl_close($ch); $log->insert('سرویس فضای ابری', 'پرداخت ناموفق سرویس فضای ابری', $this->getUser(), $req->getBid());
$result = json_decode($result, true); return $this->render('buy/fail.html.twig', ['results' => $res]);
//-----------------------------------
//-----------------------------------
if ($err) {
$log->insert('سرویس فضای ابری','پرداخت ناموفق سرویس فضای ابری' ,$this->getUser(),$req->getBid());
return $this->render('buy/fail.html.twig', ['results'=>$result]);
} else { } else {
if(array_key_exists('code',$result['data'])){ $req->setStatus(100);
if ($result['data']['code'] == 100) { $req->setRefID($res['refID']);
$req->setStatus(100); $req->setCardPan($res['card_pan']);
$req->setRefID($result['data']['ref_id']); $req->setExpireDate(time() + ($req->getMonth() * 30 * 24 * 60 * 60));
$req->setCardPan($result['data']['card_pan']); $entityManager->persist($req);
$req->setExpireDate(time() + ($req->getMonth() * 30 * 24 * 60 * 60)); $entityManager->flush();
$entityManager->persist($req); $log->insert(
$entityManager->flush(); 'سرویس فضای ابری',
$log->insert( 'پرداخت موفق فاکتور سرویس فضای ابری',
'سرویس فضای ابری', $req->getSubmitter(),
'پرداخت موفق فاکتور سرویس فضای ابری', $req->getBid()
$req->getSubmitter(), );
$req->getBid() $notification->insert(' فاکتور فضای ابری پرداخت شد.', '/acc/sms/panel', $req->getBid(), $req->getSubmitter());
); return $this->render('buy/success.html.twig', ['req' => $req]);
$notification->insert(' فاکتور فضای ابری پرداخت شد.','/acc/sms/panel',$req->getBid(),$req->getSubmitter());
return $this->render('buy/success.html.twig',['req'=>$req]);
}
}
$notification->insert('پرداخت فاکتور فضای ابری ناموفق بود','/',$req->getBid(),$req->getSubmitter());
$log->insert('سرویس پیامک','پرداخت ناموفق فاکتور فضای ابری' ,$this->getUser(),$req->getBid());
return $this->render('buy/fail.html.twig', ['results'=>$result]);
} }
} }
#[Route('/api/archive/list/{cat}', name: 'app_archive_list')] #[Route('/api/archive/list/{cat}', name: 'app_archive_list')]
public function app_archive_list(string $cat,Jdate $jdate,Provider $provider,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): JsonResponse public function app_archive_list(string $cat, Jdate $jdate, Provider $provider, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): JsonResponse
{ {
$acc = $access->hasRole('archiveUpload'); $acc = $access->hasRole('archiveUpload');
if(!$acc) if (!$acc)
$acc = $access->hasRole('archiveMod'); $acc = $access->hasRole('archiveMod');
if(!$acc) if (!$acc)
$acc = $access->hasRole('archiveDelete'); $acc = $access->hasRole('archiveDelete');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
if($cat == 'all') if ($cat == 'all')
$files = $entityManager->getRepository(ArchiveFile::class)->findBy(['bid'=>$acc['bid']]); $files = $entityManager->getRepository(ArchiveFile::class)->findBy(['bid' => $acc['bid']]);
else else
$files = $entityManager->getRepository(ArchiveFile::class)->findBy(['bid'=>$acc['bid'],'cat'=>$cat]); $files = $entityManager->getRepository(ArchiveFile::class)->findBy(['bid' => $acc['bid'], 'cat' => $cat]);
$resp = []; $resp = [];
foreach ($files as $file){ foreach ($files as $file) {
$temp = []; $temp = [];
$temp['id']=$file->getId(); $temp['id'] = $file->getId();
$temp['filename']=$file->getFilename(); $temp['filename'] = $file->getFilename();
$temp['fileType']=$file->getFileType(); $temp['fileType'] = $file->getFileType();
$temp['submitter']=$file->getSubmitter()->getFullName(); $temp['submitter'] = $file->getSubmitter()->getFullName();
$temp['dateSubmit']=$jdate->jdate('Y/n/d H:i',$file->getDateSubmit()); $temp['dateSubmit'] = $jdate->jdate('Y/n/d H:i', $file->getDateSubmit());
$temp['filePublicls']=$file->isPublic(); $temp['filePublicls'] = $file->isPublic();
$temp['cat']=$file->getCat(); $temp['cat'] = $file->getCat();
$temp['filesize']=$file->getFileSize(); $temp['filesize'] = $file->getFileSize();
$resp[] = $temp; $resp[] = $temp;
} }
@ -219,41 +161,42 @@ class ArchiveController extends AbstractController
} }
#[Route('/api/archive/orders/list', name: 'app_archive_orders_list')] #[Route('/api/archive/orders/list', name: 'app_archive_orders_list')]
public function app_archive_orders_list(Jdate $jdate, Provider $provider,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): JsonResponse public function app_archive_orders_list(Jdate $jdate, Provider $provider, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): JsonResponse
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if (!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$orders = $entityManager->getRepository(ArchiveOrders::class)->findBy([ $orders = $entityManager->getRepository(ArchiveOrders::class)->findBy([
'bid'=>$acc['bid'] 'bid' => $acc['bid']
],['id'=>'DESC']); ], ['id' => 'DESC']);
$resp = $provider->ArrayEntity2Array($orders,0); $resp = $provider->ArrayEntity2Array($orders, 0);
foreach ($resp as &$item){ foreach ($resp as &$item) {
$item['dateSubmit'] = $jdate->jdate('Y/n/d H:i',$item['dateSubmit']); $item['dateSubmit'] = $jdate->jdate('Y/n/d H:i', $item['dateSubmit']);
} }
return $this->json($resp); return $this->json($resp);
} }
#[Route('/api/archive/file/upload', name: 'app_archive_file_upload')] #[Route('/api/archive/file/upload', name: 'app_archive_file_upload')]
public function app_archive_file_upload(Jdate $jdate, Provider $provider,SluggerInterface $slugger,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): JsonResponse public function app_archive_file_upload(Jdate $jdate, Provider $provider, SluggerInterface $slugger, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): JsonResponse
{ {
$acc = $access->hasRole('archiveUpload'); $acc = $access->hasRole('archiveUpload');
if (!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$info = $this->getArchiveInfo($entityManager,$acc); $info = $this->getArchiveInfo($entityManager, $acc);
$uploadedFile = $request->files->get('image'); $uploadedFile = $request->files->get('image');
if ($uploadedFile) { if ($uploadedFile) {
$originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME); $originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL // this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename); $safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$uploadedFile->guessExtension(); $newFilename = $safeFilename . '-' . uniqid() . '.' . $uploadedFile->guessExtension();
// Move the file to the directory where brochures are stored // Move the file to the directory where brochures are stored
try { try {
$uploadedFile->move( $uploadedFile->move(
$this->getParameter('archiveTempMediaDir'), $this->getParameter('archiveTempMediaDir'),
$newFilename $newFilename
);} catch (FileException $e) { );
} catch (FileException $e) {
// ... handle exception if something happens during file upload // ... handle exception if something happens during file upload
return $this->json("error"); return $this->json("error");
} }
@ -261,21 +204,21 @@ class ArchiveController extends AbstractController
// updates the 'brochureFilename' property to store the PDF file name // updates the 'brochureFilename' property to store the PDF file name
// instead of its contents // instead of its contents
//$product->setBrochureFilename($newFilename); //$product->setBrochureFilename($newFilename);
return $this->json(['name'=>$newFilename]); return $this->json(['name' => $newFilename]);
} }
} }
#[Route('/api/archive/file/save', name: 'app_archive_file_save')] #[Route('/api/archive/file/save', name: 'app_archive_file_save')]
public function app_archive_file_save(Jdate $jdate, Provider $provider,SluggerInterface $slugger,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): JsonResponse public function app_archive_file_save(Jdate $jdate, Provider $provider, SluggerInterface $slugger, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): JsonResponse
{ {
$acc = $access->hasRole('archiveUpload'); $acc = $access->hasRole('archiveUpload');
if (!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
foreach ($request->get('added_media') as $item){ foreach ($request->get('added_media') as $item) {
if (file_exists(__DIR__ . '/../../../hesabixArchive/temp/'.$item) ){ if (file_exists(__DIR__ . '/../../../hesabixArchive/temp/' . $item)) {
$size = ceil(filesize(__DIR__ . '/../../../hesabixArchive/temp/'.$item)/(1024*1024)); $size = ceil(filesize(__DIR__ . '/../../../hesabixArchive/temp/' . $item) / (1024 * 1024));
$info = $this->getArchiveInfo($entityManager,$acc); $info = $this->getArchiveInfo($entityManager, $acc);
if($info['size'] < ($info['used'] + $size)) if ($info['size'] < ($info['used'] + $size))
return $this->json(['result'=>'nem']); return $this->json(['result' => 'nem']);
$file = new ArchiveFile(); $file = new ArchiveFile();
$file->setBid($acc['bid']); $file->setBid($acc['bid']);
$file->setDateSubmit(time()); $file->setDateSubmit(time());
@ -285,89 +228,89 @@ class ArchiveController extends AbstractController
$file->setDes($request->get('des')); $file->setDes($request->get('des'));
$file->setCat($request->get('cat')); $file->setCat($request->get('cat'));
//set file type //set file type
$mimFile = mime_content_type(__DIR__ . '/../../../hesabixArchive/temp/'.$item); $mimFile = mime_content_type(__DIR__ . '/../../../hesabixArchive/temp/' . $item);
$file->setFileType($mimFile); $file->setFileType($mimFile);
$file->setFileSize(ceil(filesize(__DIR__ . '/../../../hesabixArchive/temp/'.$item)/(1024*1024))); $file->setFileSize(ceil(filesize(__DIR__ . '/../../../hesabixArchive/temp/' . $item) / (1024 * 1024)));
rename(__DIR__ . '/../../../hesabixArchive/temp/'.$item,__DIR__ . '/../../../hesabixArchive/'.$item); rename(__DIR__ . '/../../../hesabixArchive/temp/' . $item, __DIR__ . '/../../../hesabixArchive/' . $item);
$file->setRelatedDocType($request->get('doctype')); $file->setRelatedDocType($request->get('doctype'));
$file->setRelatedDocCode($request->get('docid')); $file->setRelatedDocCode($request->get('docid'));
$entityManager->persist($file); $entityManager->persist($file);
$entityManager->flush(); $entityManager->flush();
$log->insert('آرشیو','فایل با نام ' . $file->getFilename() . ' افزوده شد.',$this->getUser(),$acc['bid']); $log->insert('آرشیو', 'فایل با نام ' . $file->getFilename() . ' افزوده شد.', $this->getUser(), $acc['bid']);
} }
} }
return $this->json([ return $this->json([
'ok'=>'ok' 'ok' => 'ok'
]); ]);
} }
#[Route('/api/archive/files/list', name: 'app_archive_file_list')] #[Route('/api/archive/files/list', name: 'app_archive_file_list')]
public function app_archive_file_list(Jdate $jdate,Provider $provider,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): JsonResponse public function app_archive_file_list(Jdate $jdate, Provider $provider, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): JsonResponse
{ {
$acc = $access->hasRole('archiveView'); $acc = $access->hasRole('archiveView');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$params = []; $params = [];
if ($content = $request->getContent()) { if ($content = $request->getContent()) {
$params = json_decode($content, true); $params = json_decode($content, true);
} }
$files = $entityManager->getRepository(ArchiveFile::class)->findBy([ $files = $entityManager->getRepository(ArchiveFile::class)->findBy([
'bid'=>$acc['bid'], 'bid' => $acc['bid'],
'relatedDocType'=>$params['type'], 'relatedDocType' => $params['type'],
'relatedDocCode'=>$params['id'] 'relatedDocCode' => $params['id']
]); ]);
echo $request->get('type'); echo $request->get('type');
$resp = []; $resp = [];
foreach ($files as $file){ foreach ($files as $file) {
$temp = []; $temp = [];
$temp['id']=$file->getId(); $temp['id'] = $file->getId();
$temp['filename']=$file->getFilename(); $temp['filename'] = $file->getFilename();
$temp['fileType']=$file->getFileType(); $temp['fileType'] = $file->getFileType();
$temp['submitter']=$file->getSubmitter()->getFullName(); $temp['submitter'] = $file->getSubmitter()->getFullName();
$temp['dateSubmit']=$jdate->jdate('Y/n/d H:i',$file->getDateSubmit()); $temp['dateSubmit'] = $jdate->jdate('Y/n/d H:i', $file->getDateSubmit());
$temp['filePublicls']=$file->isPublic(); $temp['filePublicls'] = $file->isPublic();
$temp['cat']=$file->getCat(); $temp['cat'] = $file->getCat();
$temp['filesize']=$file->getFileSize(); $temp['filesize'] = $file->getFileSize();
$resp[] = $temp; $resp[] = $temp;
} }
return $this->json($resp); return $this->json($resp);
} }
#[Route('/api/archive/file/get/{id}', name: 'app_archive_file_get')] #[Route('/api/archive/file/get/{id}', name: 'app_archive_file_get')]
public function app_archive_file_get(string $id,Jdate $jdate,Provider $provider,Request $request,Access $access,Log $log,EntityManagerInterface $entityManager,$code = 0): BinaryFileResponse public function app_archive_file_get(string $id, Jdate $jdate, Provider $provider, Request $request, Access $access, Log $log, EntityManagerInterface $entityManager, $code = 0): BinaryFileResponse
{ {
$acc = $access->hasRole('archiveView'); $acc = $access->hasRole('archiveView');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$file = $entityManager->getRepository(ArchiveFile::class)->find($id); $file = $entityManager->getRepository(ArchiveFile::class)->find($id);
if(! $file) if (!$file)
throw $this->createNotFoundException(); throw $this->createNotFoundException();
if($acc['bid']->getId() != $file->getBid()->getId()) if ($acc['bid']->getId() != $file->getBid()->getId())
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$fileAdr = __DIR__ . '/../../../hesabixArchive/'. $file->getFilename(); $fileAdr = __DIR__ . '/../../../hesabixArchive/' . $file->getFilename();
$response = new BinaryFileResponse($fileAdr); $response = new BinaryFileResponse($fileAdr);
return $response; return $response;
} }
#[Route('/api/archive/file/remove/{id}', name: 'app_archive_file_remove')] #[Route('/api/archive/file/remove/{id}', name: 'app_archive_file_remove')]
public function app_archive_file_remove(string $id,Access $access,Log $log,EntityManagerInterface $entityManager): JsonResponse public function app_archive_file_remove(string $id, Access $access, Log $log, EntityManagerInterface $entityManager): JsonResponse
{ {
$acc = $access->hasRole('archiveDelete'); $acc = $access->hasRole('archiveDelete');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$file = $entityManager->getRepository(ArchiveFile::class)->find($id); $file = $entityManager->getRepository(ArchiveFile::class)->find($id);
if(! $file) if (!$file)
throw $this->createNotFoundException(); throw $this->createNotFoundException();
if($acc['bid']->getId() != $file->getBid()->getId()) if ($acc['bid']->getId() != $file->getBid()->getId())
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$fileAdr = __DIR__ . '/../../../hesabixArchive/'. $file->getFilename(); $fileAdr = __DIR__ . '/../../../hesabixArchive/' . $file->getFilename();
unlink($fileAdr); unlink($fileAdr);
$entityManager->remove($file); $entityManager->remove($file);
$entityManager->flush(); $entityManager->flush();
$log->insert('آرشیو','فایل با نام ' . $file->getFilename() . ' حذف شد.',$this->getUser(),$acc['bid']); $log->insert('آرشیو', 'فایل با نام ' . $file->getFilename() . ' حذف شد.', $this->getUser(), $acc['bid']);
return $this->json(['result'=>1]); return $this->json(['result' => 1]);
} }
} }

View file

@ -9,9 +9,12 @@ use App\Entity\Settings;
use App\Service\Access; use App\Service\Access;
use App\Service\Jdate; use App\Service\Jdate;
use App\Service\Log; use App\Service\Log;
use App\Service\PayMGR;
use App\Service\twigFunctions;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
@ -19,164 +22,119 @@ use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class PluginController extends AbstractController class PluginController extends AbstractController
{ {
#[Route('/api/plugin/get/info/{id}', name: 'api_plugin_get_info')] #[Route('/api/plugin/get/info/{id}', name: 'api_plugin_get_info')]
public function api_plugin_get_info(String $id,Access $access, Jdate $jdate, EntityManagerInterface $entityManager,Log $log): JsonResponse public function api_plugin_get_info(string $id, Access $access, Jdate $jdate, EntityManagerInterface $entityManager, Log $log): JsonResponse
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$item = $entityManager->getRepository(PluginProdect::class)->findOneBy([ $item = $entityManager->getRepository(PluginProdect::class)->findOneBy([
'code'=>$id 'code' => $id
]); ]);
return $this->json($item); return $this->json($item);
} }
#[Route('/api/plugin/insert/{id}', name: 'api_plugin_insert')] #[Route('/api/plugin/insert/{id}', name: 'api_plugin_insert')]
public function api_plugin_insert(String $id,Access $access,EntityManagerInterface $entityManager): Response public function api_plugin_insert(string $id, Log $log, twigFunctions $twigFunctions, PayMGR $payMGR, Access $access, EntityManagerInterface $entityManager): Response
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$pp = $entityManager->getRepository(PluginProdect::class)->find($id); $pp = $entityManager->getRepository(PluginProdect::class)->find($id);
if(!$pp) if (!$pp)
throw $this->createNotFoundException('plugin not found'); throw $this->createNotFoundException('plugin not found');
//get system settings //get system settings
$settings = $entityManager->getRepository(Settings::class)->findAll()[0]; $settings = $twigFunctions->systemSettings();
$data = array("merchant_id" => $settings->getZarinpalMerchant(), $plugin = new Plugin();
"amount" => ($pp->getPrice() * 109)/10, $plugin->setBid($acc['bid']);
"callback_url" => $this->generateUrl('api_plugin_buy_verify',[],UrlGeneratorInterface::ABSOLUTE_URL), $plugin->setSubmitter($this->getUser());
"description" => $pp->getName(), $plugin->setDateSubmit(time());
); $plugin->setStatus(0);
$jsonData = json_encode($data); $plugin->setDes($pp->getName());
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/request.json'); $plugin->setName($pp->getCode());
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1'); $plugin->setPrice(($pp->getPrice() * 109) / 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); $plugin->setDateExpire(time() + $pp->getTimestamp());
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); $entityManager->persist($plugin);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $entityManager->flush();
curl_setopt($ch, CURLOPT_HTTPHEADER, array( $result = $payMGR->createRequest(($pp->getPrice() * 109) / 10, $this->generateUrl('api_plugin_buy_verify', ['id' => $plugin->getId()], UrlGeneratorInterface::ABSOLUTE_URL), 'خرید فضای ابری');
'Content-Type: application/json', if ($result['Success']) {
'Content-Length: ' . strlen($jsonData) $plugin->setGatePay($result['gate']);
)); $plugin->setVerifyCode($result['authkey']);
$entityManager->persist($plugin);
$result = curl_exec($ch); $entityManager->flush();
$err = curl_error($ch); $entityManager->persist($plugin);
$result = json_decode($result, true, JSON_PRETTY_PRINT); $entityManager->flush();
curl_close($ch); $log->insert('بازار افزونه‌ها', 'صدور فاکتور افزونه ' . $pp->getName(), $this->getUser(), $acc['bid']);
if ($err) {
throw $this->createAccessDeniedException($err);
} else {
if (empty($result['errors'])) {
if ($result['data']['code'] == 100) {
$plugin = new Plugin();
$plugin->setBid($acc['bid']);
$plugin->setSubmitter($this->getUser());
$plugin->setDateSubmit(time());
$plugin->setGatePay('zarinpal');
$plugin->setVerifyCode($result['data']['authority']);
$plugin->setStatus(0);
$plugin->setDes($pp->getName());
$plugin->setName($pp->getCode());
$plugin->setPrice(($pp->getPrice() * 109)/10);
$plugin->setDateExpire(time() + $pp->getTimestamp());
$entityManager->persist($plugin);
$entityManager->flush();
return $this->json([
'authority'=> $result['data']["authority"]
]);
}
} else {
throw $this->createAccessDeniedException();
}
} }
return $this->json($result);
} }
#[Route('/api/plugin/buy/verify', name: 'api_plugin_buy_verify')]
public function api_plugin_buy_verify(\Symfony\Component\HttpFoundation\Request $request,EntityManagerInterface $entityManager,Log $log): Response #[Route('/api/plugin/buy/verify/{id}', name: 'api_plugin_buy_verify')]
public function api_plugin_buy_verify(string $id, twigFunctions $twigFunctions, PayMGR $payMGR, Request $request, EntityManagerInterface $entityManager, Log $log): Response
{ {
$Authority = $request->get('Authority'); $req = $entityManager->getRepository(Plugin::class)->find($id);
$status = $request->get('Status'); $res = $payMGR->verify($req->getPrice(), $id, $request);
$req = $entityManager->getRepository(Plugin::class)->findOneBy(['verifyCode'=>$Authority]); if ($res['Success'] == false) {
//get system settings $log->insert(
$settings = $entityManager->getRepository(Settings::class)->findAll()[0]; 'بازار افزونه‌ها' . $req->getName(),
$data = array("merchant_id" => $settings->getZarinpalMerchant(), "authority" => $Authority, "amount" => $req->getPrice()); 'پرداخت ناموفق صورت‌حساب خرید افزونه',
$jsonData = json_encode($data); $req->getSubmitter(),
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/verify.json'); $req->getBid()
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v4'); );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); return $this->render('buy/fail.html.twig', ['results' => $res]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
$result = json_decode($result, true);
//-----------------------------------
//-----------------------------------
if ($err) {
return $this->render('buy/fail.html.twig', ['results'=>$result]);
} else { } else {
if(array_key_exists('code',$result['data'])){ $req->setStatus(100);
if ($result['data']['code'] == 100) { $req->setRefID($res['refID']);
$req->setStatus(100); $req->setCardPan($res['card_pan']);
$req->setRefID($result['data']['ref_id']); $entityManager->persist($req);
$req->setCardPan($result['data']['card_pan']); $entityManager->flush();
$entityManager->persist($req); $log->insert(
$entityManager->flush(); 'افزونه ' . $req->getName(),
$log->insert( 'افزونه جدید خریداری و فعال شد.',
'افزونه ' . $req->getName(), $req->getSubmitter(),
'افزونه جدید خریداری و فعال شد.', $req->getBid()
$req->getSubmitter(), );
$req->getBid() return $this->render('buy/success.html.twig', ['req' => $req]);
);
return $this->render('buy/success.html.twig',['req'=>$req]);
}
}
return $this->render('buy/fail.html.twig', ['results'=>$result]);
} }
} }
#[Route('/api/plugin/get/actives', name: 'api_plugin_get_actives')] #[Route('/api/plugin/get/actives', name: 'api_plugin_get_actives')]
public function api_plugin_get_actives(Access $access, Jdate $jdate, EntityManagerInterface $entityManager,Log $log): JsonResponse public function api_plugin_get_actives(Access $access, Jdate $jdate, EntityManagerInterface $entityManager, Log $log): JsonResponse
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$plugins = $entityManager->getRepository(Plugin::class)->findActivePlugins($acc['bid']); $plugins = $entityManager->getRepository(Plugin::class)->findActivePlugins($acc['bid']);
$temp = []; $temp = [];
foreach ($plugins as $plugin){ foreach ($plugins as $plugin) {
$plugin->setDateExpire($jdate->jdate('Y/n/d',$plugin->getDateExpire())); $plugin->setDateExpire($jdate->jdate('Y/n/d', $plugin->getDateExpire()));
$temp[$plugin->getName()] = $plugin; $temp[$plugin->getName()] = $plugin;
} }
return $this->json($temp); return $this->json($temp);
} }
#[Route('/api/plugin/get/paids', name: 'api_plugin_get_paids')] #[Route('/api/plugin/get/paids', name: 'api_plugin_get_paids')]
public function api_plugin_get_paids(Access $access, Jdate $jdate, EntityManagerInterface $entityManager,Log $log): JsonResponse public function api_plugin_get_paids(Access $access, Jdate $jdate, EntityManagerInterface $entityManager, Log $log): JsonResponse
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$plugins = $entityManager->getRepository(Plugin::class)->findBy([ $plugins = $entityManager->getRepository(Plugin::class)->findBy([
'bid'=>$acc['bid'], 'bid' => $acc['bid'],
]); ]);
$temp = []; $temp = [];
foreach ($plugins as $plugin){ foreach ($plugins as $plugin) {
$plugin->setDateExpire($jdate->jdate('Y/n/d',$plugin->getDateExpire())); $plugin->setDateExpire($jdate->jdate('Y/n/d', $plugin->getDateExpire()));
$plugin->setDateSubmit($jdate->jdate('Y/n/d',$plugin->getDateSubmit())); $plugin->setDateSubmit($jdate->jdate('Y/n/d', $plugin->getDateSubmit()));
$plugin->setPrice(number_format($plugin->getPrice())); $plugin->setPrice(number_format($plugin->getPrice()));
} }
return $this->json($plugins); return $this->json($plugins);
} }
#[Route('/api/plugin/get/all', name: 'api_plugin_get_all')] #[Route('/api/plugin/get/all', name: 'api_plugin_get_all')]
public function api_plugin_get_all(Access $access, Jdate $jdate, EntityManagerInterface $entityManager,Log $log): JsonResponse public function api_plugin_get_all(Access $access, Jdate $jdate, EntityManagerInterface $entityManager, Log $log): JsonResponse
{ {
$acc = $access->hasRole('join'); $acc = $access->hasRole('join');
if(!$acc) if (!$acc)
throw $this->createAccessDeniedException(); throw $this->createAccessDeniedException();
$plugins = $entityManager->getRepository(PluginProdect::class)->findAll(); $plugins = $entityManager->getRepository(PluginProdect::class)->findAll();
return $this->json($plugins); return $this->json($plugins);

View file

@ -11,10 +11,12 @@ use App\Service\Access;
use App\Service\Jdate; use App\Service\Jdate;
use App\Service\Log; use App\Service\Log;
use App\Service\Notification; use App\Service\Notification;
use App\Service\PayMGR;
use App\Service\PluginService; use App\Service\PluginService;
use App\Service\Provider; use App\Service\Provider;
use App\Service\registryMGR; use App\Service\registryMGR;
use App\Service\SMS; use App\Service\SMS;
use App\Service\twigFunctions;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
@ -104,7 +106,7 @@ class SMSController extends AbstractController
} }
#[Route('/api/sms/charge', name: 'api_sms_charge')] #[Route('/api/sms/charge', name: 'api_sms_charge')]
public function api_sms_charge(Log $log, Notification $notification, Request $request, Access $access, EntityManagerInterface $entityManager): JsonResponse public function api_sms_charge(PayMGR $payMGR, Log $log, registryMGR $registryMGR, Request $request, Access $access, EntityManagerInterface $entityManager): JsonResponse
{ {
$acc = $access->hasRole('owner'); $acc = $access->hasRole('owner');
if (!$acc) if (!$acc)
@ -116,108 +118,50 @@ class SMSController extends AbstractController
if (!array_key_exists('price', $params)) if (!array_key_exists('price', $params))
throw $this->createAccessDeniedException('price not set'); throw $this->createAccessDeniedException('price not set');
//get system settings $smsPay = new SMSPays();
$settings = $entityManager->getRepository(Settings::class)->findAll()[0]; $smsPay->setBid($acc['bid']);
$data = array( $smsPay->setDateSubmit(time());
"merchant_id" => $settings->getZarinpalMerchant(), $smsPay->setSubmitter($this->getUser());
"amount" => $params['price'], $smsPay->setDes('افزایش اعتبار سرویس پیامک');
"callback_url" => $this->generateUrl('api_sms_buy_verify', [], UrlGeneratorInterface::ABSOLUTE_URL), $smsPay->setPrice($params['price']);
"description" => 'افزایش اعتبار سرویس پیامک', $smsPay->setStatus(0);
); $entityManager->persist($smsPay);
$jsonData = json_encode($data); $entityManager->flush();
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/request.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
$result = curl_exec($ch); $result = $payMGR->createRequest($params['price'], $this->generateUrl('api_sms_buy_verify', ['id' => $smsPay->getId()], UrlGeneratorInterface::ABSOLUTE_URL), 'افزایش اعتبار سرویس پیامک');
$err = curl_error($ch); if ($result['Success']) {
$result = json_decode($result, true, JSON_PRETTY_PRINT); $smsPay->setVerifyCode($result['authkey']);
curl_close($ch); $smsPay->setGatePay($result['gate']);
if ($err) { $entityManager->persist($smsPay);
throw $this->createAccessDeniedException($err); $entityManager->flush();
} else { $log->insert('سرویس پیامک', 'صدور فاکتور شارژ سرویس پیامک', $this->getUser(), $acc['bid']);
if (empty($result['errors'])) {
if ($result['data']['code'] == 100) {
$smsPay = new SMSPays();
$smsPay->setBid($acc['bid']);
$smsPay->setDateSubmit(time());
$smsPay->setSubmitter($this->getUser());
$smsPay->setDes('افزایش اعتبار سرویس پیامک');
$smsPay->setPrice($params['price']);
$smsPay->setStatus(0);
$smsPay->setVerifyCode($result['data']['authority']);
$smsPay->setGatePay('zarinpal');
$entityManager->persist($smsPay);
$entityManager->flush();
$log->insert('سرویس پیامک', 'صدور فاکتور شارژ سرویس پیامک', $this->getUser(), $acc['bid']);
return $this->json([
'authority' => $result['data']["authority"]
]);
}
}
} }
throw $this->createAccessDeniedException(); return $this->json($result);
} }
#[Route('/api/sms/buy/verify', name: 'api_sms_buy_verify')] #[Route('/api/sms/buy/verify/{id}', name: 'api_sms_buy_verify')]
public function api_sms_buy_verify(Notification $notification, Request $request, EntityManagerInterface $entityManager, Log $log): Response public function api_sms_buy_verify(string $id, PayMGR $payMGR, twigFunctions $twigFunctions, Notification $notification, Request $request, EntityManagerInterface $entityManager, Log $log): Response
{ {
$Authority = $request->get('Authority'); $req = $entityManager->getRepository(SMSPays::class)->find($id);
$status = $request->get('Status'); $res = $payMGR->verify($req->getPrice(), $id, $request);
$req = $entityManager->getRepository(SMSPays::class)->findOneBy(['verifyCode' => $Authority]); if ($res['Success'] == false) {
//get system settings
$settings = $entityManager->getRepository(Settings::class)->findAll()[0];
$data = array("merchant_id" => $settings->getZarinpalMerchant(), "authority" => $Authority, "amount" => $req->getPrice());
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/verify.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v4');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
$result = json_decode($result, true);
//-----------------------------------
//-----------------------------------
if ($err) {
$log->insert('سرویس پیامک', 'پرداخت ناموفق شارژ سرویس پیامک', $this->getUser(), $req->getBid()); $log->insert('سرویس پیامک', 'پرداخت ناموفق شارژ سرویس پیامک', $this->getUser(), $req->getBid());
return $this->render('buy/fail.html.twig', ['results' => $result]); return $this->render('buy/fail.html.twig', ['results' => $res]);
} else { } else {
if (array_key_exists('code', $result['data'])) { $req->setStatus(100);
if ($result['data']['code'] == 100) { $req->setRefID($res['refID']);
$req->setStatus(100); $req->setCardPan($res['card_pan']);
$req->setRefID($result['data']['ref_id']); $req->getBid()->setSmsCharge($req->getBid()->getSmsCharge() + ($req->getPrice() / 1.09));
$req->setCardPan($result['data']['card_pan']); $entityManager->persist($req);
$req->getBid()->setSmsCharge($req->getBid()->getSmsCharge() + ($req->getPrice() / 1.09)); $entityManager->flush();
$entityManager->persist($req); $log->insert(
$entityManager->flush(); 'سرویس پیامک',
$log->insert( 'افزایش اعتبار سرویس پیامک به مبلغ: ' . $req->getPrice() . ' ریال ',
'سرویس پیامک', $req->getSubmitter(),
'افزایش اعتبار سرویس پیامک به مبلغ: ' . $req->getPrice() . ' ریال ', $req->getBid()
$req->getSubmitter(), );
$req->getBid() $notification->insert(' سرویس پیامک شارژ شد.', '/acc/sms/panel', $req->getBid(), $req->getSubmitter());
); return $this->render('buy/success.html.twig', ['req' => $req]);
$notification->insert(' سرویس پیامک شارژ شد.', '/acc/sms/panel', $req->getBid(), $req->getSubmitter());
return $this->render('buy/success.html.twig', ['req' => $req]);
}
}
$notification->insert('پرداخت فاکتور شارژ سرویس پیامک ناموفق بود', '/', $req->getBid(), $req->getSubmitter());
$log->insert('سرویس پیامک', 'پرداخت ناموفق شارژ سرویس پیامک', $this->getUser(), $req->getBid());
return $this->render('buy/fail.html.twig', ['results' => $result]);
} }
} }
@ -238,7 +182,7 @@ class SMSController extends AbstractController
'id' => $id, 'id' => $id,
'bid' => $bid, 'bid' => $bid,
'type' => 'sell', 'type' => 'sell',
'money'=> $acc['money'] 'money' => $acc['money']
]); ]);
if (!$doc) if (!$doc)
return $this->json(['result' => 3]); return $this->json(['result' => 3]);

View file

@ -0,0 +1,161 @@
<?php
namespace App\Service;
use App\Entity\APIToken;
use App\Entity\Business;
use App\Entity\Money;
use App\Entity\Permission;
use App\Entity\UserToken;
use App\Entity\Year;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class PayMGR
{
protected Business|string $bid;
function __construct(
private EntityManagerInterface $entityManager,
private registryMGR $registry
) {
}
public function createRequest($price, $callback_url, $des = '', $orderID = 0): array
{
$res = [
'Success' => false,
];
$activeGateway = $this->registry->get('system', 'activeGateway');
if ($activeGateway == 'zarinpal') {
$data = array(
"merchant_id" => $this->registry->get('system', 'zarinpalKey'),
"amount" => $price,
"callback_url" => $callback_url,
"description" => $des,
);
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/request.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
$result = curl_exec($ch);
$err = curl_error($ch);
$result = json_decode($result, true, JSON_PRETTY_PRINT);
curl_close($ch);
if ($err) {
} else {
if (empty($result['errors'])) {
if ($result['data']['code'] == 100) {
$res['code'] = 100;
$res['Success'] = true;
$res['gate'] = 'zarinpal';
$res['message'] = $result['data']['message'];
$res['authkey'] = $result['data']['authority'];
$res['targetURL'] = 'https://www.zarinpal.com/pg/StartPay/' . $result['data']['authority'];
}
}
}
} elseif ($activeGateway == 'pec') {
ini_set("soap.wsdl_cache_enabled", "0");
$url = "https://pec.shaparak.ir/NewIPGServices/Sale/SaleService.asmx?WSDL";
$params = array(
"LoginAccount" => $this->registry->get('system', 'parsianGatewayAPI'),
"Amount" => $price,
"OrderId" => $orderID,
"CallBackUrl" => $callback_url,
"AdditionalData" => '',
"Originator" => ''
);
$client = new \SoapClient($url);
try {
$result = $client->SalePaymentRequest(array(
"requestData" => $params
));
if ($result->SalePaymentRequestResult->Token && $result->SalePaymentRequestResult->Status === 0) {
$res['code'] = 100;
$res['Success'] = true;
$res['gate'] = 'zarinpal';
$res['message'] = 'OK';
$res['authkey'] = $result->SalePaymentRequestResult->Token;
$res['targetURL'] = 'https://pec.shaparak.ir/NewIPG/?Token=' . $result->SalePaymentRequestResult->Token;
}
} catch (\Exception $ex) {
}
}
return $res;
}
public function verify($price,$token, Request $request): array
{
$res = [
'Success' => false
];
$activeGateway = $this->registry->get('system', 'activeGateway');
if ($activeGateway == 'zarinpal') {
$Authority = $request->get('Authority');
$data = array("merchant_id" => $this->registry->get('system', 'zarinpalKey'), "authority" => $Authority, "amount" => $price);
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/verify.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v4');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
$result = json_decode($result, true);
if ($err) {
return $res;
} else {
if (array_key_exists('code', $result['data'])) {
if ($result['data']['code'] == 100) {
$res['Success'] = true;
$res['status'] = 100;
$res['refID'] = $result['data']['ref_id'];
$res['card_pan'] = $result['data']['card_pan'];
return $res;
}
}
}
} elseif ($activeGateway == 'pec') {
$confirmUrl = 'https://pec.shaparak.ir/NewIPGServices/Confirm/ConfirmService.asmx?WSDL';
$params = array(
"LoginAccount" => $this->registry->get('system', 'parsianGatewayAPI'),
"Token" => $token
);
$client = new \SoapClient($confirmUrl);
$result = $client->ConfirmPayment(array(
"requestData" => $params
));
if ($result->ConfirmPaymentResult->Status == '0') {
$res['Success'] = true;
$res['status'] = 100;
$res['refID'] = $_POST ["RRN"];
$res['card_pan'] = $result->CardNumberMasked;
}
}
return $res;
}
}