<?php
/**
* Created by PhpStorm.
* User: MAX
* Date: 08/04/14
* Time: 00:10
* FIXME: [NEVER USED]
* TODO: erase and restart on a clean slate
*/
namespace App\BackOffice\ConfigurationBundle\Services\ApiPayment;
use App\BackOffice\ConfigurationBundle\Payment\Gateways\Sogecommerce\Message\Response;
use App\BackOffice\ConfigurationBundle\Services\Crypt;
use App\BackOffice\ConfigurationBundle\Services\Invoice\Invoices;
use App\BackOffice\ConfigurationBundle\Services\Mailing\SendMail;
use App\BackOffice\ConfigurationBundle\Services\Serializer;
use DateTime;
use JMS\Serializer\SerializerInterface;
use Services\CampaignBundle\Manager\CampaignsManager;
use Services\CampaignBundle\Manager\CampaignTypesManager;
use Services\ConfigurationBundle\Entity\Roles;
use Services\ConfigurationBundle\Manager\RolesManager;
use Services\LocationBundle\Entity\UserAddress;
use Services\LocationBundle\Manager\CountryManager;
use Services\LocationBundle\Manager\UserAddressManager;
use Services\PaymentBundle\Entity\Payment;
use Services\PaymentBundle\Entity\Retry;
use Services\PaymentBundle\Entity\UserTokens;
use Services\PaymentBundle\Manager\PaymentManager;
use Services\PaymentBundle\Manager\PaymentStatusManager;
use Services\PaymentBundle\Manager\PaymentTestCardsManager;
use Services\PaymentBundle\Manager\PaymentTestManager;
use Services\PaymentBundle\Manager\PaymentTypesManager;
use Services\PaymentBundle\Manager\UserTokensManager;
use Services\UsersBundle\Entity\Unsubscribe;
use Services\UsersBundle\Entity\UserInfos;
use Services\UsersBundle\Entity\Users;
use Services\UsersBundle\Manager\UnsubscribeManager;
use Services\UsersBundle\Manager\UserInfosManager;
use Services\UsersBundle\Manager\UsersManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
class Sogecommerce
{
protected $container;
protected $usersManager;
protected $rolesManager;
protected $userInfosManager;
protected $paymentManager;
protected $paymentStatusManager;
protected $campaignTypesManager;
protected $paymentTypesManager;
protected $sogecommerce;
protected $sendMail;
protected $crypt;
protected $campaignsManager;
protected $ip;
protected $site;
protected $serializerService;
protected $unsubscribeManager;
protected $token;
protected $_psp;
protected $userTokensManager;
protected $billingService;
protected $_brand;
private $serializer;
public function __construct(ContainerInterface $container, UsersManager $usersManager, RolesManager $rolesManager, UserInfosManager $userInfosManager,
PaymentManager $paymentManager, PaymentStatusManager $paymentStatusManager, CampaignTypesManager $campaignTypesManager, PaymentTypesManager $paymentTypesManager,
\App\BackOffice\ConfigurationBundle\Services\Sogecommerce\Sogecommerce $sogecommerce, SendMail $sendMail, Crypt $crypt, CampaignsManager $campaignsManager,
Serializer $serializerService, UnsubscribeManager $unsubscribeManager, UserAddressManager $userAddressManager, CountryManager $countryManager,
UserTokensManager $userTokensManager, BillingService $billingService, SerializerInterface $serializer)
{
$this->container = $container;
$this->usersManager = $usersManager;
$this->rolesManager = $rolesManager;
$this->userInfosManager = $userInfosManager;
$this->paymentManager = $paymentManager;
$this->paymentStatusManager = $paymentStatusManager;
$this->campaignTypesManager = $campaignTypesManager;
$this->paymentTypesManager = $paymentTypesManager;
$this->sogecommerce = $sogecommerce;
$this->sendMail = $sendMail;
$this->crypt = $crypt;
$this->campaignsManager = $campaignsManager;
$this->serializerService = $serializerService;
$this->unsubscribeManager = $unsubscribeManager;
$this->countryManager = $countryManager;
$this->userAddressManager = $userAddressManager;
$this->userTokensManager = $userTokensManager;
$this->billingService = $billingService;
$this->serializer = $serializer;
}
public function serializeEntity($entity)
{
return $this->serializer->serialize($entity, 'json');
}
public function generateAuthorization($site, $cardPan, $cardMonth, $cardYear, $cardCryptogram, $cardHolder, $user, $psp, $campaign, $ip, $token = null, $testEnv, $brand = null)
{
$response['code'] = 0;
$response['retry'] = 1;
$response['psp'] = $this->serializeEntity($psp);
$mdp = substr(md5(time()), 0, 8);
$this->_psp = $psp;
$this->ip = $ip;
$this->site = $site;
$userCreate = '';
$this->_brand = $brand;
$orderId = $site->getNameConfig().$user->id.'-T-'.time();
$createToken = $this->sogecommerce->generateToken($cardPan, $cardYear, $cardMonth, $cardCryptogram, $orderId, $user, $psp, $site);
if ($createToken['success']) {
$this->token = $createToken['token'];
} else {
$price = number_format($campaign->getCampaignType()->getFirstPrice() + $campaign->getCampaignInfo()->getPricePresentClient() + $campaign->getCampaignInfo()->getShippingCost(), 2, '.', '');
$response['paymentAttempt'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, false, $createToken['error'], $price, $site, $brand, $user->source, $orderId);
return $response;
}
$description = 'Inscription';
if ($campaign->getCampaignPaymentTypes()->getId() == 1) {
$attempt1 = false;
$attempt2 = false;
$price = number_format($campaign->getCampaignInfo()->getPricePresentClient() + $campaign->getCampaignInfo()->getShippingCost(), 2, '.', '');
$priceBilling1 = str_replace('.', '', $price);
$orderId = $site->getNameConfig().$user->id.'-'.time();
$result = $this->sogecommerce->generateAuthorization($this->token, $user, $priceBilling1, $orderId, $psp, $site);
if ($result['success']) {
$attempt1 = true;
$response['paymentAttempt'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, true, 0000, $price, $site, $brand, $user->source, $orderId);
} else {
$response['paymentAttempt'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, false, $result['error'], $price, $site, $brand, $user->source, $orderId);
}
$price = number_format($campaign->getCampaignType()->getFirstPrice(), 2, '.', '');
$priceBilling2 = str_replace('.', '', $price);
$orderId2 = $site->getNameConfig().$user->id.'-2-'.time();
$result2 = $this->sogecommerce->generateAuthorization($this->token, $user, $priceBilling2, $orderId2, $psp, $site);
if ($result2['success']) {
$attempt2 = true;
$response['paymentAttempt2'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, true, 0000, $price, $site, $brand, $user->source, $orderId2);
} else {
$response['paymentAttempt2'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, false, $result2['error'], $price, $site, $brand, $user->source, $orderId2);
}
if ($result['success'] and $result2['success']) {
$result['ORDERID'] = $orderId;
$result2['ORDERID'] = $orderId2;
$returnCode = $result['code'];
$idTransaction = $result['idTransaction'];
$returnCode2 = $result2['code'];
$idTransaction2 = $result2['idTransaction'];
//if paiement immediat
// FIXME: Arguments for this function call have changed so this call will fail
$userCreate = $this->billingService->createUser($user, $campaign, $mdp, $cardPan, $cardMonth, $cardYear, $cardCryptogram, $this->_brand, $ip, $this->token, $psp, $site);
if ($campaign->getCampaignPayment()->getId() == 1) {
$result = $this->sogecommerce->captureAuthorization($result['idTransaction'], $psp, $site);
$result['ORDERID'] = $orderId;
$returnCode = $result['code'];
$idTransaction = $result['idTransaction'];
}
$payments = $this->billingService->create2payment($returnCode, $returnCode2, $idTransaction, $idTransaction2, $orderId, $orderId2, $this->token, $userCreate, $campaign, $psp, $site);
$response['payments'] = $payments;
$response['user'] = $this->serializeEntity($userCreate);
$response['code'] = 1;
} else {
$response['retry'] = $this->codeValid($response['code']);
}
}
if ($campaign->getCampaignPaymentTypes()->getId() == 2) {
$price = number_format($campaign->getCampaignType()->getFirstPrice() + $campaign->getCampaignInfo()->getPricePresentClient() + $campaign->getCampaignInfo()->getShippingCost(), 2, '.', '');
$priceBilling1 = str_replace('.', '', $price);
$orderId = $site->getNameConfig().$user->id.'-'.time();
$result = $this->sogecommerce->generateAuthorization($this->token, $user, $priceBilling1, $orderId, $psp, $site);
if ($result['success']) {
$response['paymentAttempt'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, true, 0000, $price, $site, $brand, $user->source, $orderId);
$result['ORDERID'] = $orderId;
$returnCode = $result['code'];
$idTransaction = $result['idTransaction'];
// FIXME: Arguments for this function call have changed so this call will fail
$userCreate = $this->billingService->createUser($user, $campaign, $mdp, $cardPan, $cardMonth, $cardYear, $cardCryptogram, $this->_brand, $ip, $this->token, $psp, $site);
if ($campaign->getCampaignPayment()->getId() == 1) {
$result = $this->sogecommerce->captureAuthorization($result['idTransaction'], $psp, $site);
$returnCode = $result['code'];
$idTransaction = $result['idTransaction'];
}
$payments = $this->billingService->createPayment($returnCode, $idTransaction, $orderId, $this->token, $userCreate, $campaign, $psp, $site);
$response['payments'] = $payments;
$response['user'] = $this->serializeEntity($userCreate);
$response['code'] = 1;
} else {
$response['paymentAttempt'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, false, $result['code'], $price, $site, $brand, $user->source, $orderId, $idTransaction);
$response['retry'] = $this->codeValid($response['code']);
}
}
if ($campaign->getCampaignPaymentTypes()->getId() == 3) {
$priceBilling1 = number_format($campaign->getCampaignInfo()->getPricePresentClient() + $campaign->getCampaignInfo()->getShippingCost(), 2, '.', '');
$priceBilling1 = str_replace('.', '', $priceBilling1);
$orderId = $site->getNameConfig().$user->id.'-'.time();
$result = $this->sogecommerce->generateAuthorization($this->token, $user, $priceBilling1, $orderId, $psp, $site);
if ($result['success']) {
$response['paymentAttempt'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, true, 0000, $price, $site, $brand, $user->source, $orderId);
$result['ORDERID'] = $orderId;
$returnCode = $result['code'];
$idTransaction = $result['idTransaction'];
// FIXME: Arguments for this function call have changed so this call will fail
$userCreate = $this->billingService->createUser($user, $campaign, $mdp, $cardPan, $cardMonth, $cardYear, $cardCryptogram, $this->_brand, $ip, $this->token, $psp, $site);
if ($campaign->getCampaignPayment()->getId() == 1) {
$result = $this->sogecommerce->captureAuthorization($result['idTransaction'], $psp, $site);
$result['ORDERID'] = $orderId;
$returnCode = $result['code'];
$idTransaction = $result['idTransaction'];
$paymentStatus = $this->paymentStatusManager->getPaymentStatusById(1);
} else {
$paymentStatus = $this->paymentStatusManager->getPaymentStatusById(3);
}
$payments = $this->billingService->createPaymentSpecial($returnCode, $idTransaction, $orderId, $this->token, $paymentStatus, $userCreate, $campaign, $psp, $site);
$response['user'] = $this->serializeEntity($userCreate);
$response['payments'] = $payments;
$response['code'] = 1;
} else {
$response['paymentAttempt'] = $this->container->get('BillingService')->addPaymentAttemptOld($psp, $campaign, $user->mail, false, $result['code'], $price, $site, $brand, $user->source, $orderId);
$response['retry'] = $this->codeValid($response['code']);
}
}
$response['mdp'] = $mdp;
$response['user'] = $this->serializeEntity($userCreate);
$response['orderId'] = $orderId;
return $response;
}
public function paymentNewCard($site, $cardPan, $cardMonth, $cardYear, $cardCryptogram, $user, $psp, $campaign, $ip, $token = null, $testEnv)
{
$mdp = substr(md5(time()), 0, 8);
$this->_psp = $psp;
$this->ip = $ip;
$this->site = $site;
$userCreate = '';
$this->token = $token;
$payments = '';
$priceBilling1 = floatval($campaign->getCampaignType()->getPrice());
$result = $this->hipayService->generateAuthorizationNewCard($token, $site->getNameConfig().'reabo_'.time().'_'.$user->getId(), $priceBilling1, 'auto', $ip, $user, $psp, $testEnv);
if ($result->state == 'completed') {
$result = $this->hipayService->captureAuthorization($result->transactionReference, $priceBilling1, $psp);
$paymentStatus = $this->paymentStatusManager->getPaymentStatusById(1);
$returnCode = '';
$idTransaction = '';
$payments = $this->billingService->createPaymentNewCard($returnCode, $idTransaction, $token, $paymentStatus, $user, $campaign, $psp, $site);
}
return $payments;
}
/**
* refund
*/
public function refund($payment, $amount)
{
$response['valide'] = 0;
$priceBilling1 = number_format($amount, 2, '.', '');
$priceBilling1 = str_replace('.', '', $priceBilling1);
$refRefund = $this->sogecommerce->refund($payment->getTransactionId(), $priceBilling1, $payment->getPaymentTypes());
if ($refRefund['success'] == true) {
if ($refRefund['type'] != 'CAPTURED') {
$amount = $payment->getTransactionPrice();
}
$payment = $this->billingService->proceedRefund($payment, $amount);
$response['payment'] = $payment;
$response['valid'] = 1;
}
return $response;
}
public function codeValid($code)
{
// TODO: extend ApiPaymentBase and use parent validation for common errors
// if (parent::codeValid($code)) {
// return true;
// }
if ($code > '400' && $code < '600') {
// accept all HTTP errors as temporary ones
return true;
}
$respone = false;
$array = [
'4000001',
'4000002',
'4000003',
'4000004',
'4000006',
'4000007',
'4010101',
'4010103',
'4010307',
];
if (in_array($code, $array)) {
$respone = true;
}
return $respone;
}
/**
* execute payment recurrence
* @param Payment $payment
*/
public function executePayment($payment)
{
$user = $payment->getUser();
$site = $user->getSite();
if ($payment->getIsError()) {
return $this->executePaymentError($payment);
}
$transactionId = '';
//verif cron task no too much speed and payment its always good for billing
$payment = $this->paymentManager->getEntityById($payment->getId());
if ($payment->getPaymentStatus()->getId() != 2 and $payment->getPaymentStatus()->getId() != 3) {
return false;
}
$transactionId = '';
$this->site = $site;
$data['site'] = $this->serializeEntity($site);
$data['valid'] = false;
$data['retry'] = false;
$data['delete'] = false;
$errorCode = '';
//get payments were date < date now
//get User infos
$user = $payment->getUser();
foreach ($user->getUserTokens() as $val) {
if ($val->getPaymentTypes() == $payment->getPaymentTypes() and $val->getIsActive() == true) {
$wallet = $val->getToken();
$this->_brand = $val->getBrand();
break;
}
}
$price = number_format($payment->getTransactionPrice(), 2, '.', '');
$priceBilling = str_replace('.', '', $price);
$error = 0;
$verifP = 0;
//Capture if is an autorisaton
if ($payment->getPaymentStatus()->getId() == 2) {
$orderId = $payment->getOrderId();
$response = $this->sogecommerce->captureAuthorization($payment->getTransactionId(), $payment->getPaymentTypes(), $this->site);
//crée tous les paramètres de la requete doAutho
if (!$response['success']) {
$error = 1;
$errorCode = $response['code'];
} else {
$transactionId = $response['idTransaction'];
}
}
//oneClickPayment if is not an autorisation
if ($payment->getPaymentStatus()->getId() == 3) {
$orderId = $site->getNameConfig().$user->getId().'-'.time();
$response = $this->sogecommerce->generatePayment(
$wallet,
$user,
$priceBilling,
$orderId,
$payment->getPaymentTypes(),
$site
);
if (!$response['success']) {
$error = 1;
$errorCode = $response['code'];
} else {
$transactionId = $response['idTransaction'];
$payment->setOrderId($orderId);
}
}
if ($error == 0) {
//set role premium
$payment->getUser()->setRoles($this->rolesManager->getEntityById(6));
$payment->setNextPaymentDate(new \DateTime('now'));
$payment->setReturnCode(118);
//update payment
if ($verifP == 0) {
$transactionId = $response['idTransaction'];
$payment->setTransactionId($response['idTransaction']);
$payment->setOrderId($orderId);
}
$payment->setPaymentStatus($this->paymentStatusManager->getPaymentStatusById(1));
$this->paymentManager->flush();
$data['payment'] = $this->serializeEntity($payment);
$data['valid'] = true;
//create newpayment
$newPayment = $this->billingService->saveNewPayment($payment);
$data['newPayment'] = $this->serializeEntity($newPayment);
} else {
if ($this->codeValid($errorCode)) {
$dataRules2 = $this->billingService->retryRules3($payment, $price, $errorCode, $this->site);
$payment->setTransactionId($transactionId);
$payment->setReturnCode($errorCode);
$payment->setNextPaymentDate(new \DateTime('now'));
$this->paymentManager->flush();
$data = array_merge($data, $dataRules2);
} else {
$payment->setTransactionId($transactionId);
$payment->setReturnCode($errorCode);
$payment->setNextPaymentDate(new \DateTime('now'));
$payment->getUser()->setRoles($this->rolesManager->getEntityById(Roles::ROLE_DELETE));
$payment->setPaymentStatus($this->paymentStatusManager->getPaymentStatusById(8));
$this->paymentManager->flush();
$comment = 'unsubscribe billing error';
$this->unsubscribeManager->createIfNotExistsUnsubcribe($user, new DateTime('NOW'), $comment);
$data['payment'] = $this->serializeEntity($payment);
$data['valid'] = true;
$data['delete'] = true;
}
}
$data['user'] = $this->serializeEntity($payment->getUser());
return $data;
}
/**
* execute payment error
* @param Payment $payment
*/
protected function executePaymentError($payment)
{
$user = $payment->getUser();
$site = $user->getSite();
$this->site = $site;
$data['site'] = $this->serializeEntity($site);
$data['valid'] = false;
$data['retry'] = false;
$data['delete'] = false;
$errorCode = '';
//get payments were date < date now
foreach ($user->getUserTokens() as $val) {
if ($val->getPaymentTypes() == $payment->getPaymentTypes() and $val->getIsActive() == true) {
$wallet = $val->getToken();
break;
}
}
$error = 0;
$verifP = 0;
$priceBilling = str_replace('.', '', $payment->getTransactionPrice());
$orderId = $site->getNameConfig().$user->getId().'-'.time();
$response = $this->sogecommerce->generatePayment($wallet, $user, $priceBilling, $orderId, $payment->getPaymentTypes(), $site);
$transactionId = $response['idTransaction'];
if (!$response['success']) {
$error = 1;
$errorCode = $response['code'];
}
if ($error == 0) {
$payment->getUser()->setRoles($this->rolesManager->getEntityById(8));
if ($verifP == 0) {
$payment->setTransactionId($transactionId);
$payment->setOrderId($orderId);
}
$payment->setReturnCode(118);
$payment->setPaymentStatus($this->paymentStatusManager->getPaymentStatusById(1));
$payment->setTransactionPrice($priceBilling);
$payment->setNextPaymentDate(new \DateTime('NOW'));
$payment->setIsError(false);
$this->paymentManager->flush();
//create next payment
$newPayment = $this->billingService->saveNewPayment($payment);
$payment->setNextPaymentDate(new \DateTime('NOW'));
$this->paymentManager->flush();
$data['payment'] = $this->serializeEntity($payment);
$data['newPayment'] = $this->serializeEntity($newPayment);
$data['valid'] = true;
} else {
if ($this->codeValid($errorCode)) {
//update payment in error
$payment->setTransactionId($transactionId);
$payment->setReturnCode($errorCode);
$payment->setNextPaymentDate(new \DateTime('now'));
$payment->setPaymentStatus($this->paymentStatusManager->getPaymentStatusById(16));
$payment->setOrderId('');
$this->paymentManager->flush();
//create new payment with isError = true
$date = new \DateTime('NOW');
$dataDate = 'P3D';
$date->add(new \DateInterval($dataDate));
$newPayment = clone $payment;
$newPayment->setNextPaymentDate($date);
$newPayment->setIsError(true);
$newPayment->setTransactionId('');
$newPayment->setOrderId('');
$newPayment->setReturnCode($errorCode);
$newPayment->setPaymentStatus($this->paymentStatusManager->getPaymentStatusById(11));
$newPayment->setRef($this->site->getNameConfig().time().'-'.$payment->getUser()->getId().'-er');
$this->paymentManager->persistAndFlush($newPayment);
$data['payment'] = $this->serializeEntity($payment);
$data['newPayment'] = $this->serializeEntity($newPayment);
} else {
//set role freemium
$payment->setReturnCode($errorCode);
$payment->setNextPaymentDate(new \DateTime('now'));
$payment->getUser()->setRoles($this->rolesManager->getEntityById(Roles::ROLE_DELETE));
//desabo
$payment->setPaymentStatus($this->paymentStatusManager->getPaymentStatusById(8));
$this->paymentManager->flush();
$comment = 'unsubscribe billing error';
$this->unsubscribeManager->createIfNotExistsUnsubcribe($user, new \DateTime('NOW'), $comment);
$data['payment'] = $this->serializeEntity($payment);
$data['valid'] = true;
$data['delete'] = true;
}
}
$data['user'] = $this->serializeEntity($payment->getUser());
return $data;
}
/**
* Get the Fatal Code List
* @return array
*/
public function getFatalCodeList(): array
{
return Response::getFatalCodeList();
}
}