<?php
namespace ApplicationBundle\Modules\HoneybeeWeb\Controller;
use ApplicationBundle\Constants\BuddybeeConstant;
use ApplicationBundle\Constants\EmployeeConstant;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Controller\GenericController;
use ApplicationBundle\Entity\DatevToken;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
use ApplicationBundle\Modules\Buddybee\Buddybee;
use ApplicationBundle\Modules\System\MiscActions;
use CompanyGroupBundle\Entity\EntityCreateTopic;
use CompanyGroupBundle\Entity\EntityDatevToken;
use CompanyGroupBundle\Entity\EntityInvoice;
use CompanyGroupBundle\Entity\EntityMeetingSession;
use CompanyGroupBundle\Entity\EntityTicket;
use Endroid\QrCode\Builder\BuilderInterface;
use Endroid\QrCodeBundle\Response\QrCodeResponse;
use Ps\PdfBundle\Annotation\Pdf;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use CompanyGroupBundle\Entity\EntityApplicantDetails;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
//use Symfony\Bundle\FrameworkBundle\Console\Application;
//use Symfony\Component\Console\Input\ArrayInput;
//use Symfony\Component\Console\Output\NullOutput;
class HoneybeeWebPublicController extends GenericController
{
// home page
public function CentralHomePageAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
$subscribed = false;
if ($request->isMethod('POST')) {
$entityTicket = new EntityTicket();
$entityTicket->setEmail($request->request->get('newsletter'));
$em->persist($entityTicket);
$em->flush();
$subscribed = true;
}
return $this->render('@HoneybeeWeb/pages/home.html.twig', [
'page_title' => 'HoneyBee-Home',
'subscribed' => $subscribed,
]);
}
// about us
public function CentralAboutUsPageAction()
{
return $this->render('@HoneybeeWeb/pages/about_us.html.twig', array(
'page_title' => 'About Us',
));
}
// Contact page
public function CentralContactPageAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
if ($request->isXmlHttpRequest()) {
$email = $request->request->get('email');
if ($email) {
$entityTicket = new EntityTicket();
$entityTicket->setEmail($email);
$entityTicket->setName($request->request->get('name'));
$entityTicket->setTitle($request->request->get('subject'));
$entityTicket->setTicketBody($request->request->get('message'));
$em->persist($entityTicket);
$em->flush();
return new JsonResponse([
'success' => true,
'message' => 'Your message has been sent successfully. Our team will reply soon.'
]);
}
return new JsonResponse([
'success' => false,
'message' => 'Invalid email address.'
]);
}
return $this->render('@HoneybeeWeb/pages/contact.html.twig', array(
'page_title' => 'Contact',
));
}
// blogs
public function CentralBlogsPageAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
$topicDetails = $em->getRepository('CompanyGroupBundle\Entity\EntityCreateTopic')->findAll();
$repo = $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog');
// ── Fetch featured blog separately (always, regardless of page) ──
$featuredBlog = $repo->findOneBy(['isPrimaryBlog' => true]);
// ── Pagination ──
$page = max(1, (int) $request->query->get('page', 1));
$limit = 6;
$totalBlogs = count($repo->findAll());
$totalPages = max(1, (int) ceil($totalBlogs / $limit));
$page = min($page, $totalPages);
$offset = ($page - 1) * $limit;
$blogDetails = $repo->findBy([], ['Id' => 'DESC'], $limit, $offset);
return $this->render('@HoneybeeWeb/pages/blogs.html.twig', [
'page_title' => 'Blogs',
'topics' => $topicDetails,
'blogs' => $blogDetails,
'featuredBlog' => $featuredBlog,
'currentPage' => $page,
'totalPages' => $totalPages,
'totalBlogs' => $totalBlogs,
]);
}
// product
public function CentralProductPageAction()
{
return $this->render('@HoneybeeWeb/pages/product.html.twig', array(
'page_title' => 'Product',
));
}
// our service
public function CentralServicePageAction()
{
return $this->render('@HoneybeeWeb/pages/service.html.twig', array(
'page_title' => 'Our Services',
));
}
// payment method
public function CentralPaymentMethodPageAction()
{
return $this->render('@HoneybeeWeb/pages/payment-method.html.twig', array(
'page_title' => 'Payment Method',
));
}
// single blog page
public function CentralSingleBlogPageAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
$blogId = $request->query->get('id');
if (!$blogId) {
throw $this->createNotFoundException('Blog ID not provided.');
}
$blogDetails = $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->find($blogId);
if (!$blogDetails) {
throw $this->createNotFoundException('Blog not found.');
}
// Fetch related blogs by same topic (optional but useful)
$relatedBlogs = $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->findBy(
['topicId' => $blogDetails->getTopicId()],
['createdAt' => 'DESC'],
5
);
return $this->render('@HoneybeeWeb/pages/single_blog.html.twig', [
'page_title' => $blogDetails->getTitle(),
'blog' => $blogDetails,
'related_blogs' => $relatedBlogs,
]);
}
// login v2 (verification code page)
public function CentralLoginCodePageAction()
{
return $this->render('@HoneybeeWeb/pages/login_code.html.twig', array(
'page_title' => 'Verification Code',
));
}
// reset pass
public function CentralResetPasswordPageAction()
{
return $this->render('@HoneybeeWeb/pages/reset_password.html.twig', array(
'page_title' => 'Verification Code',
));
}
public function PublicProfilePageAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
return $this->render('@Application/pages/central/central_employee_profile.html.twig', array(
'page_title' => 'Freelancer Profile',
// 'details' =>$em->getRepository(EntityApplicantDetails::class)->find($id),
));
}
// freelancer profile
public function CentralApplicantProfilePageAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
return $this->render('@HoneybeeWeb/pages/freelancer_profile.html.twig', array(
'page_title' => 'Freelancer Profile',
'details' => $em->getRepository(EntityApplicantDetails::class)->find($id),
));
}
// employee profile
public function PublicEmployeeProfileAction($id)
{
$em = $this->getDoctrine()->getManager('company_group');
if (strpos($id, 'E') !== false) {
$appId = 1 * substr($id, 1, 5);
$empId = 1 * substr($id, 6, 10);
$entry = $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findOneBy([
'appId' => $appId
]);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => $entry->getCompanyGroupServerAddress() . '/GetGlobalIdFromEmployeeId',
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
// 'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => http_build_query([
'employeeId' => $empId,
'appId' => $appId
])
]);
$id = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$id = json_decode($id, true)['globalId'];
}
$data = $em->getRepository(EntityApplicantDetails::class)->find($id);
return $this->render('@HoneybeeWeb/pages/public_profile.html.twig', array(
'page_title' => 'Employee Profile',
'details' => $data,
'genderList' => EmployeeConstant::$sex,
'bloodGroupList' => EmployeeConstant::$BloodGroup,
));
}
// add employee
public function CentralAddEmployeePageAction()
{
return $this->render('@HoneybeeWeb/pages/add_employee.html.twig', array(
'page_title' => 'Add New Eployee',
));
}
// book appointment
public function CentralBookAppointmentPageAction()
{
return $this->render('@HoneybeeWeb/pages/book_appointment.html.twig', array(
'page_title' => 'Book Appointment',
));
}
// create_compnay
public function CentralCreateCompanyPageAction()
{
return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
'page_title' => 'Create Company',
));
}
// role and company
public function CentralRoleAndCompanyPageAction()
{
return $this->render('@HoneybeeWeb/pages/role_and_company.html.twig', array(
'page_title' => 'Role and Company',
));
}
// send otp action **
public function SendOtpAjaxAction(Request $request, $startFrom = 0)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$message = "";
$retData = array();
$email_twig_data = array('success' => false);
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$userCategory = $request->request->get('userCategory', $request->query->get('userCategory', '_BUDDYBEE_USER_'));
$email_address = $request->request->get('email', $request->query->get('email', ''));
$otpExpireSecond = $request->request->get('otpExpireSecond', $request->query->get('otpExpireSecond', 180));
$otpActionId = $request->request->get('otpActionId', $request->query->get('otpActionId', UserConstants::OTP_ACTION_FORGOT_PASSWORD));
$appendCode = $request->request->get('appendCode', $request->query->get('appendCode', ''));
$otp = $request->request->get('otp', $request->query->get('otp', ''));
$otpExpireTs = 0;
$userId = $request->request->get('userId', $request->query->get('userId', $session->get(UserConstants::USER_ID, 0)));
$userType = UserConstants::USER_TYPE_APPLICANT;
$email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
if ($request->isMethod('POST')) {
//set an otp and its expire and send mail
$userObj = null;
$userData = [];
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'email' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'oAuthEmail' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'username' => $email_address
)
);
}
}
}
if ($userObj) {
$email_address = $userObj->getEmail();
if ($email_address == null || $email_address == '')
$email_address = $userObj->getOAuthEmail();
}
$otpData = MiscActions::GenerateOtp($otpExpireSecond);
$otp = $otpData['otp'];
$otpExpireTs = $otpData['expireTs'];
$userObj->setOtp($otpData['otp']);
$userObj->setOtpActionId($otpActionId);
$userObj->setOtpExpireTs($otpData['expireTs']);
$em_goc->flush();
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
$email_twig_data = [
'page_title' => 'Find Account',
'message' => $message,
'userType' => $userType,
'otp' => $otpData['otp'],
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpExpireTs' => $otpData['expireTs'],
'systemType' => $systemType,
'userData' => $userData
];
if ($userObj)
$email_twig_data['success'] = true;
} else {
$userType = UserConstants::USER_TYPE_GENERAL;
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
$email_twig_data = [
'page_title' => 'Find Account',
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
];
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'email' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'oAuthEmail' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'username' => $email_address
)
);
}
}
}
if ($userObj) {
$email_address = $userObj->getEmail();
if ($email_address == null || $email_address == '')
$email_address = $userObj->getOAuthEmail();
// triggerResetPassword:
// type: integer
// nullable: true
$otpData = MiscActions::GenerateOtp($otpExpireSecond);
$otp = $otpData['otp'];
$otpExpireTs = $otpData['expireTs'];
$userObj->setOtp($otpData['otp']);
$userObj->setOtpActionId($otpActionId);
$userObj->setOtpExpireTs($otpData['expireTs']);
$em_goc->flush();
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'phone' => $userObj->getPhone(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
$email_twig_data = [
'page_title' => 'Find Account',
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
'otp' => $otpData['otp'],
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpActionTitle' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionTitle'],
'otpActionDescForMail' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionDescForMail'],
'otpExpireTs' => $otpData['expireTs'],
'systemType' => $systemType,
'userCategory' => $userCategory,
'userData' => $userData
];
$email_twig_data['success'] = true;
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'email' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'oAuthEmail' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'username' => $email_address
)
);
}
}
}
if ($userObj) {
$email_address = $userObj->getEmail();
if ($email_address == null || $email_address == '')
$email_address = $userObj->getOAuthEmail();
// triggerResetPassword:
// type: integer
// nullable: true
$otpData = MiscActions::GenerateOtp($otpExpireSecond);
$otp = $otpData['otp'];
$otpExpireTs = $otpData['expireTs'];
$userObj->setOtp($otpData['otp']);
$userObj->setOtpActionId($otpActionId);
$userObj->setOtpExpireTs($otpData['expireTs']);
$em_goc->flush();
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'phone' => $userObj->getPhone(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_file = '@HoneybeeWeb/email/templates/otpMail.html.twig';
$email_twig_data = [
'page_title' => 'Find Account',
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
'otp' => $otpData['otp'],
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpActionTitle' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionTitle'],
'otpActionDescForMail' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionDescForMail'],
'otpExpireTs' => $otpData['expireTs'],
'systemType' => $systemType,
'userCategory' => $userCategory,
'userData' => $userData
];
$email_twig_data['success'] = true;
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
}
if ($email_twig_data['success'] == true && GeneralConstant::EMAIL_ENABLED == 1) {
if ($systemType == '_BUDDYBEE_') {
$bodyHtml = '';
$bodyTemplate = $email_twig_file;
$bodyData = $email_twig_data;
$attachments = [];
$forwardToMailAddress = $email_address;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Account Verification',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
} else {
$bodyHtml = '';
$bodyTemplate = $email_twig_file;
$bodyData = $email_twig_data;
$attachments = [];
$forwardToMailAddress = $email_address;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Account Verification',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
if ($email_twig_data['success'] == true && GeneralConstant::NOTIFICATION_ENABLED == 1 && $userData['phone'] != '' && $userData['phone'] != null) {
if ($systemType == '_BUDDYBEE_') {
$searchVal = ['_OTP_', '_EXPIRE_MINUTES_', '_APPEND_CODE_'];
$replaceVal = [$otp, floor($otpExpireSecond / 60), $appendCode];
$msg = 'Use OTP _OTP_ for BuddyBee. Your OTP will expire in _EXPIRE_MINUTES_ minutes
_APPEND_CODE_';
$msg = str_replace($searchVal, $replaceVal, $msg);
$emitMarker = '_SEND_TEXT_TO_MOBILE_';
$sendType = 'all';
$socketUserIds = [];
System::SendSmsBySocket($this->container->getParameter('notification_enabled'), $msg, $userData['phone'], $emitMarker, $sendType, $socketUserIds);
} else {
}
}
}
$response = new JsonResponse(array(
'message' => $message,
"userType" => $userType,
"otp" => '',
// "otp"=>$otp,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
"systemType" => $systemType,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
)
);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
// verrify otp **
public function VerifyOtpAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$message = "";
$retData = array();
$encData = $request->query->get('encData', $encData);
$encryptedData = [];
if ($encData != '')
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if ($encryptedData == null) $encryptedData = [];
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$userCategory = $request->request->get('userCategory', $request->query->get('userCategory', (isset($encryptedData['otp']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_')));
$email_address = $request->request->get('email', $request->query->get('email', (isset($encryptedData['email']) ? $encryptedData['email'] : '')));
$otpExpireSecond = $request->request->get('otpExpireSecond', $request->query->get('otpExpireSecond', 180));
$otpActionId = $request->request->get('otpActionId', $request->query->get('otpActionId', (isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : UserConstants::OTP_ACTION_FORGOT_PASSWORD)));
$otp = $request->request->get('otp', $request->query->get('otp', (isset($encryptedData['otp']) ? $encryptedData['otp'] : '')));
$otpExpireTs = isset($encryptedData['otpExpireTs']) ? $encryptedData['otpExpireTs'] : 0;
$userId = $request->request->get('userId', $request->query->get('userId', (isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID, 0))));
$userType = UserConstants::USER_TYPE_APPLICANT;
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$userEntityEmailField1 = 'email';
$userEntityEmailField1Getter = 'getEmail';
$userEntityEmailField1Setter = 'setEmail';
$userEntityEmailField2 = 'oAuthEmail';
$userEntityEmailField2Getter = 'geOAuthEmail';
$userEntityEmailField2Setter = 'seOAuthEmail';
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
$email_twig_data = array('success' => false);
$redirectUrl = '';
$userObj = null;
$userData = [];
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
} else {
$userType = UserConstants::USER_TYPE_GENERAL;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'ApplicationBundle:SysUser';
$userEntityManager = $em;
$userEntityIdField = 'userId';
$userEntityUserNameField = 'userName';
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
}
if ($request->isMethod('POST') || $otp != '') {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityIdField => $userId
)
);
if ($userObj) {
} else {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityEmailField1 => $email_address
)
);
if ($userObj) {
} else {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityEmailField2 => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
$userEntityUserNameField => $email_address
)
);
}
}
}
if ($userObj) {
$userOtp = $userObj->getOtp();
$userOtpActionId = $userObj->getOtpActionId();
$userOtpExpireTs = 1 * $userObj->getOtpExpireTs();
$currentTime = new \DateTime();
$currentTimeTs = 1 * $currentTime->format('U');
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_data = [
'page_title' => 'OTP',
'success' => false,
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
'otp' => '',
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpExpireTs' => $userOtpExpireTs,
'systemType' => $systemType,
'userCategory' => $userCategory,
'userData' => $userData,
"email" => $email_address,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
];
if ($otp == '0112') {
$userObj->setOtp(0);
$userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
$userObj->setOtpExpireTs(0);
$userObj->setTriggerResetPassword(1);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
} else if ($userOtp != $otp) {
$message = "Invalid OTP!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else if ($userOtpActionId != $otpActionId) {
$message = "Invalid OTP Action!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else if ($currentTimeTs > $userOtpExpireTs) {
$message = "OTP Expired!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else {
if ($otpActionId == UserConstants::OTP_ACTION_FORGOT_PASSWORD) {
$userObj->setTriggerResetPassword(1);
$userObj->setIsTemporaryEntry(0);
}
if ($otpActionId == UserConstants::OTP_ACTION_CONFIRM_EMAIL) {
$userObj->setIsEmailVerified(1);
$userObj->setIsTemporaryEntry(0);
$session->set('IS_EMAIL_VERIFIED', 1);
$new_ccs = $em_goc
->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
->findBy(
array(
'userId' => $session->get('userId')
)
);
foreach ($new_ccs as $new_cc) {
$session_data = json_decode($new_cc->getSessionData(), true);
$session_data['IS_EMAIL_VERIFIED'] = 1;
$updated_session_data = json_encode($session_data);
$new_cc->setSessionData($updated_session_data);
$em_goc->persist($new_cc);
}
}
$userObj->setOtp(0);
$userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
$userObj->setOtpExpireTs(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
}
} else {
$message = "Account not found!";
$redirectUrl = "";
$email_twig_data['success'] = false;
}
}
$twigData = array(
'page_title' => 'OTP Verification',
'message' => $message,
"userType" => $userType,
"userData" => $userData,
"otp" => '',
"redirectUrl" => $redirectUrl,
"email" => $email_address,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
"systemType" => $systemType,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
);
$encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
$twigData['encData'] = $encDataStr;
$response = new JsonResponse($twigData);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else if ($twigData['success'] == true) {
$encData = array(
"userType" => $userType,
"otp" => '',
'message' => $message,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => $userData['id'],
"systemType" => $systemType,
);
$redirectRoute = UserConstants::$OTP_ACTION_DATA[$otpActionId]['redirectRoute'];
if ($redirectRoute == '') {
$redirectRoute = 'dashboard';
}
if ($redirectRoute == 'dashboard') {
$url = $this->generateUrl($redirectRoute, ['_fragment' => null], UrlGeneratorInterface::ABSOLUTE_URL);
$redirectUrl = $url . '?data=' . urlencode($encDataStr);
} else {
$encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
$url = $this->generateUrl(
$redirectRoute
);
$redirectUrl = $url . "/" . $encDataStr;
}
return $this->redirect($redirectUrl);
// $encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
// $url = $this->generateUrl(
// 'central_landing'
// );
// $redirectUrl = $url . "/" . $encDataStr;
// return $this->redirect($redirectUrl);
} else {
return $this->render(
$twig_file,
$twigData
);
}
}
public function VerifyOtpWebAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$message = "";
$retData = array();
$encData = $request->query->get('encData', $encData);
$encryptedData = [];
if ($encData != '')
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if ($encryptedData == null) $encryptedData = [];
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$userCategory = $request->request->get('userCategory', $request->query->get('userCategory', (isset($encryptedData['otp']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_')));
$email_address = $request->request->get('email', $request->query->get('email', (isset($encryptedData['email']) ? $encryptedData['email'] : '')));
$otpExpireSecond = $request->request->get('otpExpireSecond', $request->query->get('otpExpireSecond', 180));
$otpActionId = $request->request->get('otpActionId', $request->query->get('otpActionId', (isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : UserConstants::OTP_ACTION_FORGOT_PASSWORD)));
$otp = $request->request->get('otp', $request->query->get('otp', (isset($encryptedData['otp']) ? $encryptedData['otp'] : '')));
$otpExpireTs = isset($encryptedData['otpExpireTs']) ? $encryptedData['otpExpireTs'] : 0;
$userId = $request->request->get('userId', $request->query->get('userId', (isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID, 0))));
$userType = UserConstants::USER_TYPE_APPLICANT;
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$userEntityEmailField1 = 'email';
$userEntityEmailField1Getter = 'getEmail';
$userEntityEmailField1Setter = 'setEmail';
$userEntityEmailField2 = 'oAuthEmail';
$userEntityEmailField2Getter = 'geOAuthEmail';
$userEntityEmailField2Setter = 'seOAuthEmail';
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
$email_twig_data = array('success' => false);
$redirectUrl = '';
$userObj = null;
$userData = [];
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
} else {
$userType = UserConstants::USER_TYPE_GENERAL;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'ApplicationBundle:SysUser';
$userEntityManager = $em;
$userEntityIdField = 'userId';
$userEntityUserNameField = 'userName';
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
}
if ($request->isMethod('POST') || $otp != '') {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityIdField => $userId
)
);
if ($userObj) {
} else {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityEmailField1 => $email_address
)
);
if ($userObj) {
} else {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityEmailField2 => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
$userEntityUserNameField => $email_address
)
);
}
}
}
if ($userObj) {
$userOtp = $userObj->getOtp();
$userOtpActionId = $userObj->getOtpActionId();
$userOtpExpireTs = 1 * $userObj->getOtpExpireTs();
$currentTime = new \DateTime();
$currentTimeTs = 1 * $currentTime->format('U');
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_data = [
'page_title' => 'OTP',
'success' => false,
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
'otp' => '',
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpExpireTs' => $userOtpExpireTs,
'systemType' => $systemType,
'userCategory' => $userCategory,
'userData' => $userData,
"email" => $email_address,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
];
if ($otp == '0112') {
$userObj->setOtp(0);
$userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
$userObj->setOtpExpireTs(0);
$userObj->setTriggerResetPassword(1);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
} else if ($userOtp != $otp) {
$message = "Invalid OTP!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else if ($userOtpActionId != $otpActionId) {
$message = "Invalid OTP Action!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else if ($currentTimeTs > $userOtpExpireTs) {
$message = "OTP Expired!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else {
$userObj->setOtp(0);
$userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
$userObj->setOtpExpireTs(0);
$userObj->setTriggerResetPassword(0);
$userObj->setIsEmailVerified(0);
$userObj->setIsTemporaryEntry(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
}
} else {
$message = "Account not found!";
$redirectUrl = "";
$email_twig_data['success'] = false;
}
}
$twigData = array(
'page_title' => 'OTP Verification',
'message' => $message,
"userType" => $userType,
"userData" => $userData,
"otp" => '',
"redirectUrl" => $redirectUrl,
"email" => $email_address,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
"systemType" => $systemType,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
);
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
$response = new JsonResponse($twigData);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else if ($twigData['success'] == true) {
$encData = array(
"userType" => $userType,
"otp" => '',
'message' => $message,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => $userData['id'],
"systemType" => $systemType,
);
// $encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
// $url = $this->generateUrl(
// UserConstants::$OTP_ACTION_DATA[$otpActionId]['redirectRoute']
// );
// $redirectUrl = $url . "/" . $encDataStr;
// return $this->redirect($redirectUrl);
$encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
$url = $this->generateUrl(
'central_landing'
);
$redirectUrl = $url . "/" . $encDataStr;
$this->addFlash('success', 'Email Verified!');
return $this->redirect($redirectUrl);
} else {
return $this->render(
$twig_file,
$twigData
);
}
}
// reset new password **
public function NewPasswordAction(Request $request, $encData = '')
{
// $userCategory=$request->request->has('userCategory');
$encryptedData = [];
$errorField = '';
$message = '';
$userType = '';
$otpExpireSecond = 180;
$session = $request->getSession();
if ($encData == '')
$encData = $request->get('encData', '');
if ($encData != '')
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
// $encryptedData = $this->get('url_encryptor')->decrypt($encData);
$otp = isset($encryptedData['otp']) ? $encryptedData['otp'] : 0;
$password = isset($encryptedData['password']) ? $encryptedData['password'] : 0;
$otpActionId = isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : 0;
$userId = isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID);
$userCategory = isset($encryptedData['userCategory']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_';
// $em = $this->getDoctrine()->getManager('company_group');
$em_goc = $this->getDoctrine()->getManager('company_group');
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$twig_file = 'ApplicationBundle:pages/login:find_account_buddybee.html.twig';
$twigData = [];
$email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
$email_twig_data = [];
if ($request->isMethod('POST')) {
$otp = $request->request->get('otp', $otp);
$password = $request->request->get('password', $password);
$otpActionId = $request->request->get('otpActionId', $otpActionId);
$userId = $request->request->get('userId', $userId);
$userCategory = $request->request->get('userCategory', $userCategory);
$email_address = $request->request->get('email');
if ($systemType == '_ERP_') {
$gocId = $session->get(UserConstants::USER_GOC_ID);
if ($gocId != 0 && $gocId != "") {
$gocDbName = $session->get(UserConstants::USER_DB_NAME);
$gocDbUser = $session->get(UserConstants::USER_DB_USER);
$gocDbPass = $session->get(UserConstants::USER_DB_PASS);
$gocDbHost = $session->get(UserConstants::USER_DB_HOST);
// $connector = $this->container->get('application_connector');
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDbName,
$gocDbUser,
$gocDbPass,
$gocDbHost,
$reset = false);
}
$em = $this->getDoctrine()->getManager();
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
if ($userObj->getTriggerResetPassword() == 1) {
$encodedPassword = $this->container->get('sha256salted_encoder')->encodePassword($password, $userObj->getSalt());
$userObj->setPassword($encodedPassword);
$userObj->setTempPassword('');
$userObj->setTriggerResetPassword(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
} else {
$message = "Action not allowed!";
$email_twig_data['success'] = false;
}
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
} else {
$userType = $session->get(UserConstants::USER_TYPE);
$userObj = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(
array(
'userId' => $userId
)
);
if ($userObj) {
if ($userObj->getTriggerResetPassword() == 1) {
$encodedPassword = $this->container->get('sha256salted_encoder')->encodePassword($password, $userObj->getSalt());
$userObj->setPassword($encodedPassword);
$userObj->setTempPassword('');
$userObj->setTriggerResetPassword(0);
$em->flush();
$email_twig_data['success'] = true;
$message = "";
} else {
$message = "Action not allowed!";
$email_twig_data['success'] = false;
}
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
}
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
$response = new JsonResponse(array(
'templateData' => $twigData,
'message' => $message,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
)
);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else if ($email_twig_data['success'] == true) {
// $twig_file = '@Authentication/pages/views/reset_password_success_buddybee.html.twig';
// $twigData = [
// 'page_title' => 'Reset Successful',
// 'encryptedData' => $encryptedData,
// 'message' => $message,
// 'userType' => $userType,
// 'errorField' => $errorField,
//
// ];
// return $this->render(
// $twig_file,
// $twigData
// );
return $this->redirectToRoute('dashboard');
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
if ($userObj->getTriggerResetPassword() == 1) {
$encodedPassword = $this->container->get('sha256salted_encoder')->encodePassword($password, $userObj->getSalt());
$userObj->setPassword($encodedPassword);
$userObj->setTempPassword('');
$userObj->setTriggerResetPassword(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
} else {
$message = "Action not allowed!";
$email_twig_data['success'] = false;
}
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
if ($userObj->getTriggerResetPassword() == 1) {
$encodedPassword = $this->container->get('sha256salted_encoder')->encodePassword($password, $userObj->getSalt());
$userObj->setPassword($encodedPassword);
$userObj->setTempPassword('');
$userObj->setTriggerResetPassword(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
} else {
$message = "Action not allowed!";
$email_twig_data['success'] = false;
}
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
}
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
$response = new JsonResponse(array(
'templateData' => $twigData,
'message' => $message,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
)
);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else if ($email_twig_data['success'] == true) {
if ($systemType == '_ERP_') $twig_file = '@Authentication/pages/views/reset_password_success_central.html.twig';
else if ($systemType == '_BUDDYBEE_') $twig_file = '@Authentication/pages/views/reset_password_success_buddybee.html.twig';
else if ($systemType == '_CENTRAL_') $twig_file = '@Authentication/pages/views/reset_password_success_central.html.twig';
$twigData = [
'page_title' => 'Reset Successful',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
return $this->render(
$twig_file,
$twigData
);
}
}
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = $session->get(UserConstants::USER_TYPE);
$twig_file = 'ApplicationBundle:pages/login:find_account_buddybee.html.twig';
$twigData = [
'page_title' => 'Find Account',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
} else {
$userType = $session->get(UserConstants::USER_TYPE);
$twig_file = 'ApplicationBundle:pages/login:reset_password_erp.html.twig';
$twigData = [
'page_title' => 'Reset Password',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@Authentication/pages/views/reset_new_password_buddybee.html.twig';
$twigData = [
'page_title' => 'Reset Password',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/reset_new_password_honeybee.html.twig';
$twigData = [
'page_title' => 'Reset Password',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
}
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
if ($userId != 0 && $userId != null) {
$response = new JsonResponse(array(
'templateData' => $twigData,
'message' => $message,
// 'encryptedData' => $encryptedData,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
)
);
} else {
$response = new JsonResponse(array(
'templateData' => [],
'message' => 'Unauthorized',
'actionData' => [],
// 'encryptedData' => $encryptedData,
'success' => false,
)
);
}
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else {
if ($userId != 0 && $userId != null) {
return $this->render(
$twig_file,
$twigData
);
} else
return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
'page_title' => '404 Not Found',
));
}
}
// hire
// public function CentralHirePageAction()
// {
// $em_goc = $this->getDoctrine()->getManager('company_group');
// $freelancersData = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
// ->createQueryBuilder('m')
// ->where("m.isConsultant =1")
//
// ->getQuery()
// ->getResult();
//
// return $this->render('@HoneybeeWeb/pages/hire.html.twig', array(
// 'page_title' => 'Hire',
// 'freelancersData' => $freelancersData,
//
// ));
// }
// public function CentralHirePageAction(Request $request)
// {
// $em_goc = $this->getDoctrine()->getManager('company_group');
// $search = $request->query->get('q'); // get search text
//
// $qb = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
// ->createQueryBuilder('m')
// ->where('m.isConsultant = 1');
//
// if (!empty($search)) {
// $qb->andWhere('m.firstname LIKE :search
// OR m.lastname LIKE :search ')
// ->setParameter('search', '%' . $search . '%');
// }
//
// $freelancersData = $qb->getQuery()->getResult();
//
// return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
// 'page_title' => 'Hire',
// 'freelancersData' => $freelancersData,
// 'searchValue' => $search
// ]);
// }
public function CentralHirePageAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$search = $request->query->get('q'); // search text
$qb = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->createQueryBuilder('m')
->where('m.isConsultant = 1');
if (!empty($search)) {
$qb->andWhere('m.firstname LIKE :search OR m.lastname LIKE :search')
->setParameter('search', '%' . $search . '%');
}
$freelancersData = $qb->getQuery()->getResult();
// For AJAX requests, we return the same Twig, but we include the searchValue
if ($request->isXmlHttpRequest()) {
return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
'page_title' => 'Hire',
'freelancersData' => $freelancersData,
'searchValue' => $search, // so input retains value
'isAjax' => true, // flag to indicate AJAX
]);
}
// Normal page load
return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
'page_title' => 'Hire',
'freelancersData' => $freelancersData,
'searchValue' => $search,
'isAjax' => false,
]);
}
// end of centralHire
// pricing
public function CentralPricingPageAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$userId = $session->get(UserConstants::USER_ID);
$companiesForUser = [];
if ($userId) {
$userDetails = $em_goc->getRepository('CompanyGroupBundle\Entity\EntityApplicantDetails')->find($userId);
if ($userDetails) {
$userTypeByAppIds = json_decode($userDetails->getUserTypesByAppIds(), true);
if (is_array($userTypeByAppIds)) {
$adminAppIds = [];
foreach ($userTypeByAppIds as $appId => $types) {
if (in_array(1, $types)) {
$adminAppIds[] = $appId;
}
}
if (!empty($adminAppIds)) {
$companiesForUser = $em_goc->getRepository('CompanyGroupBundle\Entity\CompanyGroup')
->createQueryBuilder('c')
->where('c.appId IN (:appIds)')
->setParameter('appIds', $adminAppIds)
->getQuery()
->getResult();
}
}
}
}
$packageDetails = GeneralConstant::$packageDetails;
return $this->render('@HoneybeeWeb/pages/pricing.html.twig', [
'page_title' => 'Pricing',
'packageDetails' => $packageDetails,
'companies' => $companiesForUser,
]);
}
// faq
public function CentralFaqPageAction()
{
return $this->render('@HoneybeeWeb/pages/faq.html.twig', array(
'page_title' => 'FAQ',
));
}
// terms and condiitons
public function CentralTermsAndConditionPageAction()
{
return $this->render('@HoneybeeWeb/pages/terms_and_conditions.html.twig', array(
'page_title' => 'Terms and Conditions',
));
}
// Refund Policy
public function CentralRefundPolicyPageAction()
{
return $this->render('@HoneybeeWeb/pages/refund_policy.html.twig', array(
'page_title' => 'Refund Policy',
));
}
// Cancellation Policy
public function CentralCancellationPolicyPageAction()
{
return $this->render('@HoneybeeWeb/pages/cancellation_policy.html.twig', array(
'page_title' => 'Cancellation Policy',
));
}
// Help page
public function CentralHelpPageAction()
{
return $this->render('@HoneybeeWeb/pages/help.html.twig', array(
'page_title' => 'Help',
));
}
// Career page
public function CentralCareerPageAction()
{
return $this->render('@HoneybeeWeb/pages/career.html.twig', array(
'page_title' => 'Career',
));
}
public function CentralPrivacyPolicyAction()
{
return $this->render('@HoneybeeWeb/pages/privacy_policy.html.twig', array(
'page_title' => 'Privacy Policy',
));
}
public function CheckoutPageAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$em_goc = $this->getDoctrine()->getManager('company_group');
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$invoiceId = $request->request->get('invoiceId', $request->query->get('invoiceId', 0));
if ($encData != "") {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if ($encryptedData == null) $encryptedData = [];
if (isset($encryptedData['invoiceId'])) $invoiceId = $encryptedData['invoiceId'];
}
$session = $request->getSession();
$currencyForGateway = 'eur';
$gatewayInvoice = null;
if ($invoiceId != 0)
$gatewayInvoice = $em->getRepository(EntityInvoice::class)->find($invoiceId);
$paymentGateway = $request->request->get('paymentGateway', 'stripe'); //aamarpay,bkash
$paymentType = $request->request->get('paymentType', 'credit');
$retailerId = $request->request->get('retailerId', 0);
if ($request->query->has('currency'))
$currencyForGateway = $request->query->get('currency');
else
$currencyForGateway = $request->request->get('currency', 'eur');
// {
// if ($request->query->has('meetingSessionId'))
// $id = $request->query->get('meetingSessionId');
// }
$currentUserBalance = 0;
$currentUserCoinBalance = 0;
$gatewayAmount = 0;
$redeemedAmount = 0;
$redeemedSessionCount = 0;
$toConsumeSessionCount = 0;
$invoiceSessionCount = 0;
$payableAmount = 0;
$promoClaimedAmount = 0;
$promoCodeId = 0;
$promoClaimedSession = 0;
$bookingExpireTime = null;
$bookingExpireTs = 0;
$imageBySessionCount = [
0 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
];
if (!$gatewayInvoice) {
if ($request->isMethod('POST')) {
$totalAmount = 0;
$totalSessionCount = 0;
$consumedAmount = 0;
$consumedSessionCount = 0;
$bookedById = 0;
$bookingRefererId = 0;
if ($session->get(UserConstants::USER_ID)) {
$bookedById = $session->get(UserConstants::USER_ID);
$bookingRefererId = 0;
// $toConsumeSessionCount = 1 * $request->request->get('meetingSessionConsumeCount', 0);
$invoiceSessionCount = 1 * ($request->request->get('sessionCount', 0) == '' ? 0 : $request->request->get('sessionCount', 0));
//1st do the necessary
$extMeeting = null;
$meetingSessionId = 0;
if ($request->request->has('purchasePackage')) {
//1. check if any bee card if yes try to claim it , modify current balance then
$beeCodeSerial = $request->request->get('beeCodeSerial', '');
$promoCode = $request->request->get('promoCode', '');
$beeCodePin = $request->request->get('beeCodePin', '');
$userId = $request->request->get('userId', $session->get(UserConstants::USER_ID));
$studentDetails = null;
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
}
if ($beeCodeSerial != '' && $beeCodePin != '') {
$claimData = MiscActions::ClaimBeeCode($em,
[
'claimFlag' => 1,
'pin' => $beeCodePin,
'serial' => $beeCodeSerial,
'userId' => $userId,
]);
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$claimData['newCoinBalance'] = $session->get('BUDDYBEE_COIN_BALANCE');
$claimData['newBalance'] = $session->get('BUDDYBEE_BALANCE');
}
$redeemedAmount = $claimData['data']['claimedAmount'];
$redeemedSessionCount = $claimData['data']['claimedCoin'];
} else
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
}
$payableAmount = round($request->request->get('payableAmount', 0), 0);
$totalAmountWoDiscount = round($request->request->get('totalAmountWoDiscount', 0), 0);
//now claim and process promocode
if ($promoCode != '') {
$claimData = MiscActions::ClaimPromoCode($em,
[
'claimFlag' => 1,
'promoCode' => $promoCode,
'decryptedPromoCodeData' => json_decode($this->get('url_encryptor')->decrypt($promoCode), true),
'orderValue' => $totalAmountWoDiscount,
'currency' => $currencyForGateway,
'orderCoin' => $invoiceSessionCount,
'userId' => $userId,
]);
$promoClaimedAmount = 0;
// $promoClaimedAmount = $claimData['data']['claimedAmount']*(BuddybeeConstant::$convMultFromTo['eur'][$currencyForGateway]);
$promoCodeId = $claimData['promoCodeId'];
$promoClaimedSession = $claimData['data']['claimedCoin'];
}
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$currentUserBalance = $session->get('BUDDYBEE_BALANCE');
$currentUserCoinBalance = $session->get('BUDDYBEE_COIN_BALANCE');
} else {
if ($bookingRefererId == 0)
$bookingRefererId = $session->get(UserConstants::USER_ID);
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
$currentUserCoinBalance = $studentDetails->getSessionCountBalance();
if ($bookingRefererId != $userId && $bookingRefererId != 0) {
$bookingReferer = $em_goc->getRepository(EntityApplicantDetails::class)->find($bookingRefererId);
if ($bookingReferer)
if ($bookingReferer->getIsAdmin()) {
$studentDetails->setAssignedSalesRepresentativeId($bookingRefererId);
$em_goc->flush();
}
}
}
}
//2. check if any promo code if yes add it to promo discount
//3. check if scheule is still temporarily booked if not return that you cannot book it
Buddybee::ExpireAnyMeetingSessionIfNeeded($em);
Buddybee::ExpireAnyEntityInvoiceIfNeeded($em);
// if ($request->request->get('autoAssignMeetingSession', 0) == 1
// && $request->request->get('consultancyScheduleId', 0) != 0
// && $request->request->get('consultancyScheduleId', 0) != ''
// )
{
//1st check if a meeting session exxists with same TS, student id , consultant id
// $scheduledStartTime = new \DateTime('@' . $request->request->get('consultancyScheduleId', ''));
// $extMeeting = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
// ->findOneBy(
// array(
// 'scheduledTimeTs' => $scheduledStartTime->format('U'),
// 'consultantId' => $request->request->get('consultantId', 0),
// 'studentId' => $request->request->get('studentId', 0),
// 'durationAllowedMin' => $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
// )
// );
// if ($extMeeting) {
// $new = $extMeeting;
// $meetingSessionId = $new->getSessionId();
// $periodMarker = $scheduledStartTime->format('Ym');
//
// }
// else {
//
//
// $scheduleValidity = MiscActions::CheckIfScheduleCanBeConfirmed(
// $em,
// $request->request->get('consultantId', 0),
// $request->request->get('studentId', 0),
// $scheduledStartTime->format('U'),
// $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
// 1
// );
//
// if (!$scheduleValidity) {
// $url = $this->generateUrl(
// 'consultant_profile'
// );
// $output = [
//
// 'proceedToCheckout' => 0,
// 'message' => 'Session Booking Expired or not Found!',
// 'errorFlag' => 1,
// 'redirectUrl' => $url . '/' . $request->request->get('consultantId', 0)
// ];
// return new JsonResponse($output);
// }
// $new = new EntityMeetingSession();
//
// $new->setTopicId($request->request->get('consultancyTopic', 0));
// $new->setConsultantId($request->request->get('consultantId', 0));
// $new->setStudentId($request->request->get('studentId', 0));
// $consultancyTopic = $em_goc->getRepository(EntityCreateTopic::class)->find($request->request->get('consultancyTopic', 0));
// $new->setMeetingType($consultancyTopic ? $consultancyTopic->getMeetingType() : 0);
// $new->setConsultantCanUpload($consultancyTopic ? $consultancyTopic->getConsultantCanUpload() : 0);
//
//
// $scheduledEndTime = new \DateTime($request->request->get('scheduledTime', ''));
// $scheduledEndTime = $scheduledEndTime->modify('+' . $request->request->get('meetingSessionScheduledDuration', 30) . ' minute');
//
// //$new->setScheduledTime($request->request->get('setScheduledTime'));
// $new->setScheduledTime($scheduledStartTime);
// $new->setDurationAllowedMin($request->request->get('meetingSessionScheduledDuration', 30));
// $new->setDurationLeftMin($request->request->get('meetingSessionScheduledDuration', 30));
// $new->setSessionExpireDate($scheduledEndTime);
// $new->setSessionExpireDateTs($scheduledEndTime->format('U'));
// $new->setEquivalentSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setMeetingSpecificNote($request->request->get('meetingSpecificNote', ''));
//
// $new->setUsableSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setRedeemSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setMeetingActionFlag(0);// no action waiting for meeting
// $new->setScheduledTime($scheduledStartTime);
// $new->setScheduledTimeTs($scheduledStartTime->format('U'));
// $new->setPayableAmount($request->request->get('payableAmount', 0));
// $new->setDueAmount($request->request->get('dueAmount', 0));
// //$new->setScheduledTime(new \DateTime($request->get('setScheduledTime')));
// //$new->setPcakageDetails(json_encode(($request->request->get('packageData'))));
// $new->setPackageName(($request->request->get('packageName', '')));
// $new->setPcakageDetails(($request->request->get('packageData', '')));
// $new->setScheduleId(($request->request->get('consultancyScheduleId', 0)));
// $currentUnixTime = new \DateTime();
// $currentUnixTimeStamp = $currentUnixTime->format('U');
// $studentId = $request->request->get('studentId', 0);
// $consultantId = $request->request->get('consultantId', 0);
// $new->setMeetingRoomId(str_pad($consultantId, 4, STR_PAD_LEFT) . $currentUnixTimeStamp . str_pad($studentId, 4, STR_PAD_LEFT));
// $new->setSessionValue(($request->request->get('sessionValue', 0)));
//// $new->setIsPayment(0);
// $new->setConsultantIsPaidFull(0);
//
// if ($bookingExpireTs == 0) {
//
// $bookingExpireTime = new \DateTime();
// $currTime = new \DateTime();
// $currTimeTs = $currTime->format('U');
// $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (24 * 3600);
// if ($bookingExpireTs < $currTimeTs) {
// if ((1 * $scheduledStartTime->format('U')) - $currTimeTs > (12 * 3600))
// $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (2 * 3600);
// else
// $bookingExpireTs = (1 * $scheduledStartTime->format('U'));
// }
//
//// $bookingExpireTs = $bookingExpireTime->format('U');
// }
//
// $new->setPaidSessionCount(0);
// $new->setBookedById($bookedById);
// $new->setBookingRefererId($bookingRefererId);
// $new->setDueSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setExpireIfUnpaidTs($bookingExpireTs);
// $new->setBookingExpireTs($bookingExpireTs);
// $new->setConfirmationExpireTs($bookingExpireTs);
// $new->setIsPaidFull(0);
// $new->setIsExpired(0);
//
//
// $em_goc->persist($new);
// $em_goc->flush();
// $meetingSessionId = $new->getSessionId();
// $periodMarker = $scheduledStartTime->format('Ym');
// MiscActions::UpdateSchedulingRestrictions($em_goc, $consultantId, $periodMarker, (($request->request->get('meetingSessionScheduledDuration', 30)) / 60), -(($request->request->get('meetingSessionScheduledDuration', 30)) / 60));
// }
}
//4. if after all this stages passed then calcualte gateway payable
if ($request->request->get('isRecharge', 0) == 1) {
if (($redeemedAmount + $promoClaimedAmount) >= $payableAmount) {
$payableAmount = ($redeemedAmount + $promoClaimedAmount);
$gatewayAmount = 0;
} else
$gatewayAmount = $payableAmount - ($redeemedAmount + $promoClaimedAmount);
} else {
if ($toConsumeSessionCount <= $currentUserCoinBalance && $invoiceSessionCount <= $toConsumeSessionCount) {
$payableAmount = 0;
$gatewayAmount = 0;
} else if (($redeemedAmount + $promoClaimedAmount) >= $payableAmount) {
$payableAmount = ($redeemedAmount + $promoClaimedAmount);
$gatewayAmount = 0;
} else
$gatewayAmount = $payableAmount <= ($currentUserBalance + ($redeemedAmount + $promoClaimedAmount)) ? 0 : ($payableAmount - $currentUserBalance - ($redeemedAmount + $promoClaimedAmount));
}
$gatewayAmount = round($gatewayAmount, 2);
$dueAmount = round($request->request->get('dueAmount', $payableAmount), 0);
if ($request->request->has('gatewayProductData'))
$gatewayProductData = $request->request->get('gatewayProductData');
$gatewayProductData = [[
'price_data' => [
'currency' => $currencyForGateway,
'unit_amount' => $gatewayAmount != 0 ? ((100 * $gatewayAmount) / ($invoiceSessionCount != 0 ? $invoiceSessionCount : 1)) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Bee Coins',
'images' => [$imageBySessionCount[0]],
],
],
'quantity' => $invoiceSessionCount != 0 ? $invoiceSessionCount : 1,
]];
$new_invoice = null;
if ($extMeeting) {
$new_invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'invoiceType' => $request->request->get('invoiceType', BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE),
'meetingId' => $extMeeting->getSessionId(),
)
);
}
if ($new_invoice) {
} else {
$new_invoice = new EntityInvoice();
$invoiceDate = new \DateTime();
$new_invoice->setInvoiceDate($invoiceDate);
$new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
$new_invoice->setStudentId($userId);
$new_invoice->setBillerId($retailerId == 0 ? 0 : $retailerId);
$new_invoice->setRetailerId($retailerId);
$new_invoice->setBillToId($userId);
$new_invoice->setAmountTransferGateWayHash($paymentGateway);
$new_invoice->setAmountCurrency($currencyForGateway);
$cardIds = $request->request->get('cardIds', []);
$new_invoice->setMeetingId($meetingSessionId);
$new_invoice->setGatewayBillAmount($gatewayAmount);
$new_invoice->setRedeemedAmount($redeemedAmount);
$new_invoice->setPromoDiscountAmount($promoClaimedAmount);
$new_invoice->setPromoCodeId($promoCodeId);
$new_invoice->setRedeemedSessionCount($redeemedSessionCount);
$new_invoice->setPaidAmount($payableAmount - $dueAmount);
$new_invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
$new_invoice->setDueAmount($dueAmount);
$new_invoice->setInvoiceType($request->request->get('invoiceType', BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE));
$new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' . microtime(true)));
$new_invoice->setCardIds(json_encode($cardIds));
$new_invoice->setAmountType($request->request->get('amountType', 1));
$new_invoice->setAmount($payableAmount);
$new_invoice->setConsumeAmount($payableAmount);
$new_invoice->setSessionCount($invoiceSessionCount);
$new_invoice->setConsumeSessionCount($toConsumeSessionCount);
$new_invoice->setIsPaidfull(0);
$new_invoice->setIsProcessed(0);
$new_invoice->setApplicantId($userId);
$new_invoice->setBookedById($bookedById);
$new_invoice->setBookingRefererId($bookingRefererId);
$new_invoice->setIsRecharge($request->request->get('isRecharge', 0));
$new_invoice->setAutoConfirmTaggedMeeting($request->request->get('autoConfirmTaggedMeeting', 0));
$new_invoice->setAutoConfirmOtherMeeting($request->request->get('autoConfirmOtherMeeting', 0));
$new_invoice->setAutoClaimPurchasedCards($request->request->get('autoClaimPurchasedCards', 0));
$new_invoice->setIsPayment(0); //0 means receive
$new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
$new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED); //0 means receive
if ($bookingExpireTs == 0) {
$bookingExpireTime = new \DateTime();
$bookingExpireTime->modify('+30 day');
$bookingExpireTs = $bookingExpireTime->format('U');
}
$new_invoice->setExpireIfUnpaidTs($bookingExpireTs);
$new_invoice->setBookingExpireTs($bookingExpireTs);
$new_invoice->setConfirmationExpireTs($bookingExpireTs);
// $new_invoice->setStatus($request->request->get(0));
$em_goc->persist($new_invoice);
$em_goc->flush();
}
$invoiceId = $new_invoice->getId();
$gatewayInvoice = $new_invoice;
if ($request->request->get('isRecharge', 0) == 1) {
} else {
if ($gatewayAmount <= 0) {
$meetingId = 0;
if ($invoiceId != 0) {
$retData = Buddybee::ProcessEntityInvoice($em_goc, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
$meetingId = $retData['meetingId'];
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
$output = [
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'proceedToCheckout' => 0,
'redirectUrl' => $url . '/' . $meetingId
];
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => 0,
'proceedToCheckout' => 0,
'redirectUrl' => $url
];
}
return new JsonResponse($output);
// return $this->redirect($url);
} else {
}
// $url = $this->generateUrl(
// 'checkout_page'
// );
//
// return $this->redirect($url."?meetingSessionId=".$new->getSessionId().'&invoiceId='.$invoiceId);
}
}
} else {
$url = $this->generateUrl(
'user_login'
);
$session->set('LAST_REQUEST_URI_BEFORE_LOGIN', $this->generateUrl(
'pricing_plan_page', [
'autoRedirected' => 1
],
UrlGenerator::ABSOLUTE_URL
));
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url,
'clearLs' => 0
];
return new JsonResponse($output);
}
//now proceed to checkout page if the user has lower balance or recharging
//$invoiceDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->
}
}
if ($gatewayInvoice) {
$gatewayProductData = json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
if ($gatewayProductData == null) $gatewayProductData = [];
if (empty($gatewayProductData))
$gatewayProductData = [
[
'price_data' => [
'currency' => 'eur',
'unit_amount' => $gatewayAmount != 0 ? (100 * $gatewayAmount) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Bee Coins',
'images' => [$imageBySessionCount[0]],
],
],
'quantity' => 1,
]
];
$productDescStr = '';
$productDescArr = [];
foreach ($gatewayProductData as $gpd) {
$productDescArr[] = $gpd['price_data']['product_data']['name'];
}
$productDescStr = implode(',', $productDescArr);
$paymentGatewayFromInvoice = $gatewayInvoice->getAmountTransferGateWayHash();
// return new JsonResponse(
// [
// 'paymentGateway' => $paymentGatewayFromInvoice,
// 'gateWayData' => $gatewayProductData[0]
// ]
// );
if ($paymentGateway == null) $paymentGatewayFromInvoice = 'stripe';
if ($paymentGatewayFromInvoice == 'stripe' || $paymentGatewayFromInvoice == 'aamarpay' || $paymentGatewayFromInvoice == 'bkash') {
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
if ($paymentGatewayFromInvoice == 'stripe') {
$stripe = new \Stripe\Stripe();
\Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
$stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
{
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
$paymentIntent = [
"id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
"object" => "payment_intent",
"amount" => 3000,
"amount_capturable" => 0,
"amount_received" => 0,
"application" => null,
"application_fee_amount" => null,
"canceled_at" => null,
"cancellation_reason" => null,
"capture_method" => "automatic",
"charges" => [
"object" => "list",
"data" => [],
"has_more" => false,
"url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
],
"client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
"confirmation_method" => "automatic",
"created" => 1546523966,
"currency" => $currencyForGateway,
"customer" => null,
"description" => null,
"invoice" => null,
"last_payment_error" => null,
"livemode" => false,
"metadata" => [],
"next_action" => null,
"on_behalf_of" => null,
"payment_method" => null,
"payment_method_options" => [],
"payment_method_types" => [
"card"
],
"receipt_email" => null,
"review" => null,
"setup_future_usage" => null,
"shipping" => null,
"statement_descriptor" => null,
"statement_descriptor_suffix" => null,
"status" => "requires_payment_method",
"transfer_data" => null,
"transfer_group" => null
];
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => $gatewayProductData,
'mode' => 'payment',
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
]);
$output = [
'clientSecret' => $paymentIntent['client_secret'],
'id' => $checkout_session->id,
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1
];
return new JsonResponse($output);
}
if ($paymentGatewayFromInvoice == 'aamarpay') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$url = $sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/request.php' : 'https://secure.aamarpay.com/request.php';
$fields = array(
// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
'payment_type' => 'VISA', //no need to change
'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
'cus_email' => $studentDetails->getEmail(), //customer email address
'cus_add1' => $studentDetails->getCurrAddr(), //customer address
'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
'cus_state' => $studentDetails->getCurrAddrState(), //state
'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
'cus_country' => 'Bangladesh', //country
'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' : $studentDetails->getPhone(), //customer phone number
'cus_fax' => '', //fax
'ship_name' => '', //ship name
'ship_add1' => '', //ship address
'ship_add2' => '',
'ship_city' => '',
'ship_state' => '',
'ship_postcode' => '',
'ship_country' => 'Bangladesh',
'desc' => $productDescStr,
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'fail_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
// 'opt_a' => 'Reshad', //optional paramter
// 'opt_b' => 'Akil',
// 'opt_c' => 'Liza',
// 'opt_d' => 'Sohel',
// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
$fields_string = http_build_query($fields);
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLOPT_URL, $url);
//
// curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
// curl_close($ch);
// $this->redirect_to_merchant($url_forward);
$output = [
//
// 'redirectUrl' => ($sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/' : 'https://secure.aamarpay.com/') . $url_forward, //keeping it off temporarily
// 'fields'=>$fields,
// 'fields_string'=>$fields_string,
// 'redirectUrl' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1,
'data' => $fields
];
return new JsonResponse($output);
} else if ($paymentGatewayFromInvoice == 'bkash') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/grant');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$id_token = $tokenData['id_token'];
$goToBkashPage = 0;
if ($tokenData['statusCode'] == '0000') {
$auth = $id_token;
$requestbody = array(
"mode" => "0011",
// "payerReference" => "01723888888",
"payerReference" => $invoiceDate->format('U'),
"callbackURL" => $this->generateUrl(
'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
"amount" => 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''),
"currency" => "BDT",
"intent" => "sale",
"merchantInvoiceNumber" => $invoiceId
);
$url = curl_init($baseUrl . '/tokenized/checkout/create');
$requestbodyJson = json_encode($requestbody);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $requestbodyJson);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
// curl_close($url);
// echo $resultdata;
$obj = json_decode($resultdata, true);
$goToBkashPage = 1;
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
$output = [
// 'redirectUrl' => $obj['bkashURL'],
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => $goToBkashPage,
'tokenData' => $tokenData,
'obj' => $obj,
'id_token' => $tokenData['id_token'],
'data' => [
'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
// 'payment_type' => 'VISA', //no need to change
'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
'cus_email' => $studentDetails->getEmail(), //customer email address
'cus_add1' => $studentDetails->getCurrAddr(), //customer address
'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
'cus_state' => $studentDetails->getCurrAddrState(), //state
'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
'cus_country' => 'Bangladesh', //country
'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' : $studentDetails->getPhone(), //customer phone number
'cus_fax' => '', //fax
'ship_name' => '', //ship name
'ship_add1' => '', //ship address
'ship_add2' => '',
'ship_city' => '',
'ship_state' => '',
'ship_postcode' => '',
'ship_country' => 'Bangladesh',
'desc' => $productDescStr,
]
];
return new JsonResponse($output);
}
// $fields = array(
//
// "mode" => "0011",
// "payerReference" => "01723888888",
// "callbackURL" => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
// "amount" => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),,
// "currency" => "BDT",
// "intent" => "sale",
// "merchantInvoiceNumber" => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT)
//
// );
// $fields = array(
//// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'amount' => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),, //transaction amount
// 'payment_type' => 'VISA', //no need to change
// 'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
// 'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
// 'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
// 'cus_email' => $studentDetails->getEmail(), //customer email address
// 'cus_add1' => $studentDetails->getCurrAddr(), //customer address
// 'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
// 'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
// 'cus_state' => $studentDetails->getCurrAddrState(), //state
// 'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
// 'cus_country' => 'Bangladesh', //country
// 'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
// 'cus_fax' => '', //fax
// 'ship_name' => '', //ship name
// 'ship_add1' => '', //ship address
// 'ship_add2' => '',
// 'ship_city' => '',
// 'ship_state' => '',
// 'ship_postcode' => '',
// 'ship_country' => 'Bangladesh',
// 'desc' => $productDescStr,
// 'success_url' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'fail_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'cancel_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
//// 'opt_a' => 'Reshad', //optional paramter
//// 'opt_b' => 'Akil',
//// 'opt_c' => 'Liza',
//// 'opt_d' => 'Sohel',
//// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
// 'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
//
// ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
//
// $fields_string = http_build_query($fields);
//
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLOPT_URL, $url);
//
// curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
// curl_close($ch);
// $this->redirect_to_merchant($url_forward);
} else if ($paymentGatewayFromInvoice == 'onsite_pos' || $paymentGatewayFromInvoice == 'onsite_cash' || $paymentGatewayFromInvoice == 'onsite_bkash') {
$meetingId = 0;
if ($gatewayInvoice->getId() != 0) {
if ($gatewayInvoice->getDueAmount() <= 0) {
$retData = Buddybee::ProcessEntityInvoice($em_goc, $gatewayInvoice->getId(), ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
$meetingId = $retData['meetingId'];
}
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
$output = [
'proceedToCheckout' => 0,
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'redirectUrl' => $url . '/' . $meetingId
];
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'proceedToCheckout' => 0,
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'redirectUrl' => $url
];
}
return new JsonResponse($output);
}
}
$output = [
'clientSecret' => 0,
'id' => 0,
'proceedToCheckout' => 0
];
return new JsonResponse($output);
// return $this->render('ApplicationBundle:pages/stripe:checkout.html.twig', array(
// 'page_title' => 'Checkout',
//// 'stripe' => $stripe,
// 'stripe' => null,
//// 'PaymentIntent' => $paymentIntent,
//
//// 'consultantDetail' => $consultantDetail,
//// 'consultantDetails'=> $consultantDetails,
////
//// 'meetingSession' => $meetingSession,
//// 'packageDetails' => json_decode($meetingSession->getPcakageDetails(),true),
//// 'packageName' => json_decode($meetingSession->getPackageName(),true),
//// 'pay' => $payableAmount,
//// 'balance' => $currStudentBal
// ));
}
public function PaymentGatewaySuccessAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$invoiceId = 0;
$autoRedirect = 1;
$redirectUrl = '';
$meetingId = 0;
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($systemType == '_CENTRAL_') {
if ($encData != '') {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->query->get('invoiceId', 0);
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
if ($invoiceId != 0) {
$retData = Buddybee::ProcessEntityInvoice($em, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],
$this->container->getParameter('kernel.root_dir'),
false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
if ($retData['sendCards'] == 1) {
$cardList = array();
$cards = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->findBy(
array(
'id' => $retData['cardIds']
)
);
foreach ($cards as $card) {
$cardList[] = array(
'id' => $card->getId(),
'printed' => $card->getPrinted(),
'amount' => $card->getAmount(),
'coinCount' => $card->getCoinCount(),
'pin' => $card->getPin(),
'serial' => $card->getSerial(),
);
}
$receiverEmail = $retData['receiverEmail'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/templates:beeCodeDigitalDelivery.html.twig';
$bodyData = array(
'cardList' => $cardList,
// 'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
// 'email' => $userName,
// 'password' => $newApplicant->getPassword(),
);
$attachments = [];
$forwardToMailAddress = $receiverEmail;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Digital Bee Card Delivery',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'delivery@buddybee.eu',
'userName' => 'delivery@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'encryptionMethod' => 'tls',
'encryptionMethod' => 'ssl',
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
foreach ($cards as $card) {
$card->setPrinted(1);
}
$em->flush();
}
return new JsonResponse(
array(
'success' => true
)
);
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$meetingId = $retData['meetingId'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'Id' => $invoiceId,
)
);;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
//
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url . '/' . $meetingId);
$redirectUrl = $url . '/' . $meetingId;
} else {
$url = $this->generateUrl(
'central_landing'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url);
$redirectUrl = $url;
}
}
return $this->render('ApplicationBundle:pages/stripe:success.html.twig', array(
'page_title' => 'Success',
'meetingId' => $meetingId,
'autoRedirect' => $autoRedirect,
'redirectUrl' => $redirectUrl,
));
} else if ($systemType == '_BUDDYBEE_') {
if ($encData != '') {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->query->get('invoiceId', 0);
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
if ($invoiceId != 0) {
$retData = Buddybee::ProcessEntityInvoice($em, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
if ($retData['sendCards'] == 1) {
$cardList = array();
$cards = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->findBy(
array(
'id' => $retData['cardIds']
)
);
foreach ($cards as $card) {
$cardList[] = array(
'id' => $card->getId(),
'printed' => $card->getPrinted(),
'amount' => $card->getAmount(),
'coinCount' => $card->getCoinCount(),
'pin' => $card->getPin(),
'serial' => $card->getSerial(),
);
}
$receiverEmail = $retData['receiverEmail'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/templates:beeCodeDigitalDelivery.html.twig';
$bodyData = array(
'cardList' => $cardList,
// 'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
// 'email' => $userName,
// 'password' => $newApplicant->getPassword(),
);
$attachments = [];
$forwardToMailAddress = $receiverEmail;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Digital Bee Card Delivery',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'delivery@buddybee.eu',
'userName' => 'delivery@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'encryptionMethod' => 'tls',
'encryptionMethod' => 'ssl',
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
foreach ($cards as $card) {
$card->setPrinted(1);
}
$em->flush();
}
return new JsonResponse(
array(
'success' => true
)
);
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$meetingId = $retData['meetingId'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'Id' => $invoiceId,
)
);;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
//
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url . '/' . $meetingId);
$redirectUrl = $url . '/' . $meetingId;
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url);
$redirectUrl = $url;
}
}
return $this->render('ApplicationBundle:pages/stripe:success.html.twig', array(
'page_title' => 'Success',
'meetingId' => $meetingId,
'autoRedirect' => $autoRedirect,
'redirectUrl' => $redirectUrl,
));
}
}
public function PaymentGatewayCancelAction(Request $request, $msg = 'The Payment was unsuccessful', $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
// $consultantDetail = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(array());
$session = $request->getSession();
if ($msg == '')
$msg = $request->query->get('msg', $request->request->get('msg', 'The Payment was unsuccessful'));
return $this->render('ApplicationBundle:pages/stripe:cancel.html.twig', array(
'page_title' => 'Success',
'msg' => $msg,
));
}
public function BkashCallbackAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$invoiceId = 0;
$session = $request->getSession();
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$paymentId = $request->query->get('paymentID', 0);
$status = $request->query->get('status', 0);
if ($status == 'success') {
$paymentID = $paymentId;
$gatewayInvoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
array(
'gatewayPaymentId' => $paymentId,
'isProcessed' => [0, 2]
));
if ($gatewayInvoice) {
$invoiceId = $gatewayInvoice->getId();
$justNow = new \DateTime();
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$justNowTs = $justNow->format('U');
if ($gatewayInvoice->getGatewayIdTokenExpireTs() <= $justNowTs) {
$refresh_token = $gatewayInvoice->getGatewayIdRefreshToken();
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value,
'refresh_token' => $refresh_token
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/refresh');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
}
$auth = $gatewayInvoice->getGatewayIdToken();;
$post_token = array(
'paymentID' => $paymentID
);
// $url = curl_init();
$url = curl_init($baseUrl . '/tokenized/checkout/execute');
$posttoken = json_encode($post_token);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
// curl_setopt_array($url, array(
// CURLOPT_HTTPHEADER => $header,
// CURLOPT_RETURNTRANSFER => 1,
// CURLOPT_URL => $baseUrl . '/tokenized/checkout/execute',
//
// CURLOPT_FOLLOWLOCATION => 1,
// CURLOPT_POST => 1,
// CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
// CURLOPT_POSTFIELDS => http_build_query($post_token)
// ));
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $posttoken);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
curl_close($url);
$obj = json_decode($resultdata, true);
// return new JsonResponse(array(
// 'obj' => $obj,
// 'url' => $baseUrl . '/tokenized/checkout/execute',
// 'header' => $header,
// 'paymentID' => $paymentID,
// 'posttoken' => $posttoken,
// ));
// return new JsonResponse($obj);
if (isset($obj['statusCode'])) {
if ($obj['statusCode'] == '0000') {
$gatewayInvoice->setGatewayTransId($obj['trxID']);
$em->flush();
return $this->redirectToRoute("payment_gateway_success", ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => 1
))),
'hbeeSessionToken' => $session->get('token', 0)]);
} else {
return $this->redirectToRoute("payment_gateway_cancel", [
'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'Payment Failed')
]);
}
}
} else {
return $this->redirectToRoute("payment_gateway_cancel", [
'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'Payment Failed')
]);
}
} else {
return $this->redirectToRoute("payment_gateway_cancel", [
'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'The Payment was unsuccessful')
]);
}
}
public function MakePaymentOfEntityInvoiceAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$em_goc = $em;
$invoiceId = 0;
$autoRedirect = 1;
$redirectUrl = '';
$meetingId = 0;
$triggerMiddlePage = 0;
$session = $request->getSession();
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$refundSuccess = 0;
$errorMsg = '';
$errorCode = '';
if ($encData != '') {
$invoiceId = $encData;
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['triggerMiddlePage']))
$triggerMiddlePage = $encryptedData['triggerMiddlePage'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->request->get('invoiceId', $request->query->get('invoiceId', 0));
$triggerMiddlePage = $request->request->get('triggerMiddlePage', $request->query->get('triggerMiddlePage', 0));
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
$meetingId = $request->request->get('meetingId', $request->query->get('meetingId', 0));
$actionDone = 0;
if ($meetingId != 0) {
$dt = Buddybee::ConfirmAnyMeetingSessionIfPossible($em, 0, $meetingId, false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'));
if ($invoiceId == 0 && $dt['success'] == true) {
$actionDone = 1;
return new JsonResponse(array(
'clientSecret' => 0,
'actionDone' => $actionDone,
'id' => 0,
'proceedToCheckout' => 0
));
}
}
// $invoiceId = $request->request->get('meetingId', $request->query->get('meetingId', 0));
$output = [
'clientSecret' => 0,
'id' => 0,
'proceedToCheckout' => 0
];
if ($invoiceId != 0) {
$gatewayInvoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
array(
'Id' => $invoiceId,
'isProcessed' => [0]
));
} else {
$gatewayInvoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
array(
'meetingId' => $meetingId,
'isProcessed' => [0]
));
}
if ($gatewayInvoice)
$invoiceId = $gatewayInvoice->getId();
$invoiceSessionCount = 0;
$payableAmount = 0;
$imageBySessionCount = [
0 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
];
if ($gatewayInvoice) {
$gatewayProductData = json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
if ($gatewayProductData == null) $gatewayProductData = [];
$gatewayAmount = 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', '');
$invoiceSessionCount = $gatewayInvoice->getSessionCount();
$currencyForGateway = $gatewayInvoice->getAmountCurrency();
$gatewayAmount = round($gatewayAmount, 2);
if (empty($gatewayProductData))
$gatewayProductData = [
[
'price_data' => [
'currency' => 'eur',
'unit_amount' => $gatewayAmount != 0 ? (100 * $gatewayAmount) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Bee Coins',
// 'images' => [$imageBySessionCount[$invoiceSessionCount]],
'images' => [$imageBySessionCount[0]],
],
],
'quantity' => 1,
]
];
$productDescStr = '';
$productDescArr = [];
foreach ($gatewayProductData as $gpd) {
$productDescArr[] = $gpd['price_data']['product_data']['name'];
}
$productDescStr = implode(',', $productDescArr);
$paymentGatewayFromInvoice = $gatewayInvoice->getAmountTransferGateWayHash();
if ($paymentGatewayFromInvoice == 'stripe') {
$stripe = new \Stripe\Stripe();
\Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
$stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
{
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
$paymentIntent = [
"id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
"object" => "payment_intent",
"amount" => 3000,
"amount_capturable" => 0,
"amount_received" => 0,
"application" => null,
"application_fee_amount" => null,
"canceled_at" => null,
"cancellation_reason" => null,
"capture_method" => "automatic",
"charges" => [
"object" => "list",
"data" => [],
"has_more" => false,
"url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
],
"client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
"confirmation_method" => "automatic",
"created" => 1546523966,
"currency" => $currencyForGateway,
"customer" => null,
"description" => null,
"invoice" => null,
"last_payment_error" => null,
"livemode" => false,
"metadata" => [],
"next_action" => null,
"on_behalf_of" => null,
"payment_method" => null,
"payment_method_options" => [],
"payment_method_types" => [
"card"
],
"receipt_email" => null,
"review" => null,
"setup_future_usage" => null,
"shipping" => null,
"statement_descriptor" => null,
"statement_descriptor_suffix" => null,
"status" => "requires_payment_method",
"transfer_data" => null,
"transfer_group" => null
];
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => $gatewayProductData,
'mode' => 'payment',
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
]);
$output = [
'clientSecret' => $paymentIntent['client_secret'],
'id' => $checkout_session->id,
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1
];
// return new JsonResponse($output);
}
if ($paymentGatewayFromInvoice == 'aamarpay') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$url = $sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/request.php' : 'https://secure.aamarpay.com/request.php';
$fields = array(
// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'amount' => 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''), //transaction amount
'payment_type' => 'VISA', //no need to change
'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
'cus_email' => $studentDetails->getEmail(), //customer email address
'cus_add1' => $studentDetails->getCurrAddr(), //customer address
'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
'cus_state' => $studentDetails->getCurrAddrState(), //state
'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
'cus_country' => 'Bangladesh', //country
'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' : $studentDetails->getPhone(), //customer phone number
'cus_fax' => '', //fax
'ship_name' => '', //ship name
'ship_add1' => '', //ship address
'ship_add2' => '',
'ship_city' => '',
'ship_state' => '',
'ship_postcode' => '',
'ship_country' => 'Bangladesh',
'desc' => $productDescStr,
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'fail_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
// 'opt_a' => 'Reshad', //optional paramter
// 'opt_b' => 'Akil',
// 'opt_c' => 'Liza',
// 'opt_d' => 'Sohel',
// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
curl_close($ch);
// $this->redirect_to_merchant($url_forward);
$output = [
// 'redirectUrl' => 'https://sandbox.aamarpay.com/'.$url_forward, //keeping it off temporarily
'redirectUrl' => ($sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/' : 'https://secure.aamarpay.com/') . $url_forward, //keeping it off temporarily
// 'fields'=>$fields,
// 'fields_string'=>$fields_string,
// 'redirectUrl' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1
];
// return new JsonResponse($output);
} else if ($paymentGatewayFromInvoice == 'bkash') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/grant');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$id_token = $tokenData['id_token'];
$goToBkashPage = 0;
if ($tokenData['statusCode'] == '0000') {
$auth = $id_token;
$requestbody = array(
"mode" => "0011",
// "payerReference" => "",
"payerReference" => $gatewayInvoice->getInvoiceDateTs(),
"callbackURL" => $this->generateUrl(
'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
"amount" => number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''),
"currency" => "BDT",
"intent" => "sale",
"merchantInvoiceNumber" => $invoiceId
);
$url = curl_init($baseUrl . '/tokenized/checkout/create');
$requestbodyJson = json_encode($requestbody);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $requestbodyJson);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
curl_close($url);
// return new JsonResponse($resultdata);
$obj = json_decode($resultdata, true);
$goToBkashPage = 1;
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
$output = [
'redirectUrl' => $obj['bkashURL'],
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => $goToBkashPage,
'tokenData' => $tokenData,
'obj' => $obj,
'id_token' => $tokenData['id_token'],
];
}
// $fields = array(
//
// "mode" => "0011",
// "payerReference" => "01723888888",
// "callbackURL" => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
// "amount" => $gatewayInvoice->getGateWayBillamount(),
// "currency" => "BDT",
// "intent" => "sale",
// "merchantInvoiceNumber" => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT)
//
// );
// $fields = array(
//// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
// 'payment_type' => 'VISA', //no need to change
// 'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
// 'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
// 'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
// 'cus_email' => $studentDetails->getEmail(), //customer email address
// 'cus_add1' => $studentDetails->getCurrAddr(), //customer address
// 'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
// 'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
// 'cus_state' => $studentDetails->getCurrAddrState(), //state
// 'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
// 'cus_country' => 'Bangladesh', //country
// 'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
// 'cus_fax' => '', //fax
// 'ship_name' => '', //ship name
// 'ship_add1' => '', //ship address
// 'ship_add2' => '',
// 'ship_city' => '',
// 'ship_state' => '',
// 'ship_postcode' => '',
// 'ship_country' => 'Bangladesh',
// 'desc' => $productDescStr,
// 'success_url' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'fail_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'cancel_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
//// 'opt_a' => 'Reshad', //optional paramter
//// 'opt_b' => 'Akil',
//// 'opt_c' => 'Liza',
//// 'opt_d' => 'Sohel',
//// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
// 'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
//
// ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
//
// $fields_string = http_build_query($fields);
//
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLOPT_URL, $url);
//
// curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
// curl_close($ch);
// $this->redirect_to_merchant($url_forward);
}
}
if ($triggerMiddlePage == 1) return $this->render('@Buddybee/pages/makePaymentOfEntityInvoiceLandingPage.html.twig', array(
'page_title' => 'Invoice Payment',
'data' => $output,
));
else
return new JsonResponse($output);
}
public function RefundEntityInvoiceAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$invoiceId = 0;
$currIsProcessedFlagValue = '_UNSET_';
$session = $request->getSession();
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$paymentId = $request->query->get('paymentID', 0);
$status = $request->query->get('status', 0);
$refundSuccess = 0;
$errorMsg = '';
$errorCode = '';
if ($encData != '') {
$invoiceId = $encData;
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->request->get('invoiceId', $request->query->get('invoiceId', 0));
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
$gatewayInvoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
array(
'Id' => $invoiceId,
'isProcessed' => [1]
));
if ($gatewayInvoice) {
$gatewayInvoice->setIsProcessed(3); //pending settlement
$currIsProcessedFlagValue = $gatewayInvoice->getIsProcessed();
$em->flush();
if ($gatewayInvoice->getAmountTransferGateWayHash() == 'bkash') {
$invoiceId = $gatewayInvoice->getId();
$paymentID = $gatewayInvoice->getGatewayPaymentId();
$trxID = $gatewayInvoice->getGatewayTransId();
$justNow = new \DateTime();
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$justNowTs = $justNow->format('U');
if ($gatewayInvoice->getGatewayIdTokenExpireTs() <= $justNowTs) {
$refresh_token = $gatewayInvoice->getGatewayIdRefreshToken();
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value,
'refresh_token' => $refresh_token
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/refresh');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
}
$auth = $gatewayInvoice->getGatewayIdToken();;
$post_token = array(
'paymentID' => $paymentID,
'trxID' => $trxID,
'reason' => 'Full Refund Policy',
'sku' => 'RSTR',
'amount' => 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''),
);
$url = curl_init($baseUrl . '/tokenized/checkout/payment/refund');
$posttoken = json_encode($post_token);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $posttoken);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
curl_close($url);
$obj = json_decode($resultdata, true);
// return new JsonResponse($obj);
if (isset($obj['completedTime']))
$refundSuccess = 1;
else if (isset($obj['errorCode'])) {
$refundSuccess = 0;
$errorCode = $obj['errorCode'];
$errorMsg = $obj['errorMessage'];
}
// $gatewayInvoice->setGatewayTransId($obj['trxID']);
$em->flush();
}
if ($refundSuccess == 1) {
Buddybee::RefundEntityInvoice($em, $invoiceId);
$currIsProcessedFlagValue = 4;
}
} else {
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
return new JsonResponse(
array(
'success' => $refundSuccess,
'errorCode' => $errorCode,
'isProcessed' => $currIsProcessedFlagValue,
'errorMsg' => $errorMsg,
)
);
}
public function ViewEntityInvoiceAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$invoiceId = 0;
$autoRedirect = 1;
$redirectUrl = '';
$meetingId = 0;
$invoice = null;
if ($encData != '') {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
$invoiceId = $encData;
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->query->get('invoiceId', 0);
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
// $invoiceList = [];
$billerDetails = [];
$billToDetails = [];
if ($invoiceId != 0) {
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'Id' => $invoiceId,
)
);
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
if ($request->query->get('sendMail', 0) == 1 && GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
// if ($invoice) {
//
// } else {
// return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
// 'page_title' => '404 Not Found',
//
// ));
// }
return $this->render('@HoneybeeWeb/pages/views/honeybee_ecosystem_invoice.html.twig', array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
));
}
}
public function SignatureCheckFromCentralAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($systemType !== '_CENTRAL_') {
return new JsonResponse(['success' => false, 'message' => 'Only allowed on CENTRAL server.'], 403);
}
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$data = json_decode($request->getContent(), true);
if (
!$data ||
!isset($data['userId']) ||
!isset($data['companyId']) ||
!isset($data['signatureData']) ||
!isset($data['approvalHash']) ||
!isset($data['applicantId'])
) {
return new JsonResponse(['success' => false, 'message' => 'Missing parameters.'], 400);
}
$userId = $data['userId'];
$companyId = $data['companyId'];
$signatureData = $data['signatureData'];
$approvalHash = $data['approvalHash'];
$applicantId = $data['applicantId'];
try {
$centralUser = $em
->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
->findOneBy(['applicantId' => $applicantId]);
if (!$centralUser) {
return new JsonResponse(['success' => false, 'message' => 'Central user not found.'], 404);
}
$userAppIds = json_decode($centralUser->getUserAppIds(), true);
if (!is_array($userAppIds)) $userAppIds = [];
$companies = $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
'appId' => $userAppIds
]);
if (count($companies) < 1) {
return new JsonResponse(['success' => false, 'message' => 'No companies found for userAppIds.'], 404);
}
$repo = $em->getRepository('CompanyGroupBundle\\Entity\\EntitySignature');
$record = $repo->findOneBy(['userId' => $userId]);
if (!$record) {
$record = new \CompanyGroupBundle\Entity\EntitySignature();
$record->setUserId($applicantId);
$record->setCreatedAt(new \DateTime());
}
$record->setCompanyId($companyId);
$record->setApplicantId($applicantId);
$record->setData($signatureData);
$record->setSigExists(0);
$record->setLastDecryptedSigId(0);
$record->setUpdatedAt(new \DateTime());
$em->persist($record);
$em->flush();
$dataByServerId = [];
$gocDataListByAppId = [];
foreach ($companies as $entry) {
$gocDataListByAppId[$entry->getAppId()] = [
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'appId' => $entry->getAppId(),
'serverId' => $entry->getCompanyGroupServerId(),
];
if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
$dataByServerId[$entry->getCompanyGroupServerId()] = array(
'serverId' => $entry->getCompanyGroupServerId(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'payload' => array(
'globalId' => $applicantId,
'companyId' => $userAppIds,
'signatureData' => $signatureData,
// 'approvalHash' => $approvalHash
)
);
}
$urls = [];
foreach ($dataByServerId as $entry) {
$serverAddress = $entry['serverAddress'];
if (!$serverAddress) continue;
// $connector = $this->container->get('application_connector');
// $connector->resetConnection(
// 'default',
// $entry['dbName'],
// $entry['dbUser'],
// $entry['dbPass'],
// $entry['dbHost'],
// $reset = true
// );
$syncUrl = $serverAddress . '/ReceiveSignatureFromCentral';
$payload = $entry['payload'];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => $syncUrl,
// CURLOPT_PORT => $entry['port'],
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode($payload)
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// if ($err) {
// error_log("ERP Sync Error [AppID $appId]: $err");
// $urls[]=$err;
// } else {
// error_log("ERP Sync Response [AppID $appId] (HTTP $httpCode): $response");
// $res = json_decode($response, true);
// if (!isset($res['success']) || !$res['success']) {
// error_log("❗ ERP Sync error for AppID $appId: " . ($res['message'] ?? 'Unknown'));
// }
//
// $urls[]=$response;
// }
}
return new JsonResponse(['success' => true, 'message' => 'Signature synced successfully.']);
} catch (\Exception $e) {
return new JsonResponse(['success' => false, 'message' => 'DB error: ' . $e->getMessage()], 500);
}
}
//datev cntroller
public function connectDatev(Request $request)
{
$clientId = "51b09bdcf577c5b998cddce7fe7d5c92";
$redirectUri = "https://ourhoneybee.eu/datev/callback";
$state = bin2hex(random_bytes(10));
$scope = "openid profile email accounting:documents accounting:dxso-jobs accounting:clients:read datev:accounting:extf-files-import datev:accounting:clients";
$codeVerifier = bin2hex(random_bytes(32));
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
$session = $request->getSession();
$applicantId = $session->get(UserConstants::APPLICANT_ID);
$em_goc = $this->getDoctrine()->getManager('company_group');
$token = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
->findOneBy(['userId' => $applicantId]);
if (!$token) {
$token = new EntityDatevToken();
$token->setUserId($applicantId);
}
$token->setState($state);
$token->setCodeChallenge($codeChallenge);
$token->setCodeVerifier($codeVerifier);
$em_goc->persist($token);
$em_goc->flush();
$url = "https://login.datev.de/openidsandbox/authorize?"
."response_type=code"
."&client_id=".$clientId
."&state=".$state
."&scope=".urlencode($scope)
."&redirect_uri=".urlencode($redirectUri)
."&code_challenge=".$codeChallenge
."&code_challenge_method=S256"
."&prompt=login";
return $this->redirect($url);
}
public function datevCallback(Request $request)
{
$code = $request->get('code');
$state = $request->get('state');
if (!$code || !$state) {
return new Response("Invalid callback request");
}
$em_goc = $this->getDoctrine()->getManager('company_group');
$tokenEntity = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
->findOneBy(['state' => $state]);
if (!$tokenEntity) {
return new Response("Invalid or expired state");
}
$codeVerifier = $tokenEntity->getCodeVerifier();
if (!$codeVerifier) {
return new Response("Code verifier missing");
}
$clientId = "51b09bdcf577c5b998cddce7fe7d5c92";
$clientSecret = "9b1c4e72a966e9f231584393ff1d3469";
// from parameters
// $clientId= $this->getContainer()->getParameter('datev_client_id');
// $clientSecret= $this->getContainer()->getParameter('datev_client_secret');
$authString = base64_encode($clientId . ":" . $clientSecret);
$redirectUri = "https://ourhoneybee.eu/datev/callback";
$postFields = http_build_query([
"grant_type" => "authorization_code",
"code" => $code,
"redirect_uri" => $redirectUri,
"client_id" => $clientId,
"code_verifier" => $codeVerifier
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://sandbox-api.datev.de/token",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . $authString
]
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
return new Response("cURL Error: " . curl_error($ch), 500);
}
curl_close($ch);
$data = json_decode($response, true);
if (!$data) {
return new Response("Invalid token response", 500);
}
if (isset($data['access_token'])) {
$tokenEntity->setAccessToken($data['access_token']);
$session = $request->getSession(); //remove it later
$session->set('DATEV_ACCESS_TOKEN', $data['access_token']);
if (isset($data['refresh_token'])) {
$tokenEntity->setRefreshToken($data['refresh_token']);
}
if (isset($data['expires_in'])) {
$tokenEntity->setExpiresAt(time() + $data['expires_in']);
}
// $tokenEntity->setState(null);
$tokenEntity->setCode($code);
$em_goc->flush();
return $this->redirect("/datev/home");
}
return new Response(
"Token exchange failed: " . json_encode($data),
400
);
}
public function refreshToken(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$applicantId = $session->get(UserConstants::APPLICANT_ID);
$token = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
->findOneBy(['userId' => $applicantId]);
if (!$token) {
return new JsonResponse([
'status' => false,
'message' => 'User token not found'
]);
}
if (!$token->getRefreshToken()) {
return new JsonResponse([
'status' => false,
'message' => 'No refresh token available'
]);
}
$clientId = "51b09bdcf577c5b998cddce7fe7d5c92";
$clientSecret = "9b1c4e72a966e9f231584393ff1d3469";
$authString = base64_encode($clientId . ":" . $clientSecret);
$postFields = http_build_query([
"grant_type" => "refresh_token",
"refresh_token" => $token->getRefreshToken(),
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://sandbox-api.datev.de/token",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . $authString
]
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
return new JsonResponse([
'status' => false,
'message' => curl_error($ch)
]);
}
curl_close($ch);
$data = json_decode($response, true);
if (!isset($data['access_token'])) {
return new JsonResponse([
'status' => false,
'message' => 'Refresh failed',
'error' => $data
]);
}
$token->setAccessToken($data['access_token']);
if (isset($data['refresh_token'])) {
$token->setRefreshToken($data['refresh_token']);
}
$token->setExpiresAt(time() + $data['expires_in']);
$em_goc->flush();
return new JsonResponse([
'status' => true,
'message' => 'Token refreshed successfully'
]);
}
}