<?php
namespace App\Service;
use App\Entity\Billing;
use App\Entity\BillingItem;
use App\Entity\Client;
use App\Entity\Company;
use App\Model\Invoice;
use App\Traits\LoggerTrait;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class PaytweakService
{
const NOTICE_PAYMENT = 'payment';
const NOTICE_MANDATE_SIGNED = 'MANDATE_SIGNED';
const PAYMENT_STATUS_INCOMPLETE = 0;
const PAYMENT_STATUS_AUTHORIZED_REFUSED = 2;
const PAYMENT_STATUS_REFUSED_FRAUD = 3;
const PAYMENT_STATUS_REFUSED = 4;
const PAYMENT_STATUS_AUTHORIZED = 5;
const PAYMENT_STATUS_WAITING = 51;
const PAYMENT_STATUS_CANCEL = 7;
const PAYMENT_STATUS_CANCEL_WAITING = 71;
const PAYMENT_STATUS_REFUNDED = 8;
const PAYMENT_STATUS_REFUND_WAITING = 81;
const PAYMENT_STATUS_PAYMENT_EXECUTED = 9;
const PAYMENT_STATUS_PAYMENT_UNCERTAINED = 91;
const PAYMENT_STATUS_PAYMENT_REFUSED = 93;
const BASE_URL = 'https://api.paytweak.cloud/v1/';
const CODE_NOT_FOUND = "404";
const CODE_OK = "OK";
private $client;
private $parameterBag;
use LoggerTrait;
public function __construct(HttpClientInterface $client, ParameterBagInterface $parameterBag)
{
$this->client = $client;
$this->parameterBag = $parameterBag;
}
/**
* @param Company $company
* @return mixed
* @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*/
public function hello(Company $company)
{
$apiKey = $this->parameterBag->get('API_KEY_PAYTWEAK_FRESSIA');
$url = $this->parameterBag->get('API_PAYTWEAK_URL');
if ($company->getName() === 'SILVER BEAUTÉ') {
$apiKey = $this->parameterBag->get('API_KEY_PAYTWEAK_SILVER');
$url = $this->parameterBag->get('API_PAYTWEAK_URL_SILVER');
}
$response = $this->client->request(
Request::METHOD_GET,
$url . 'hello/',
[
"body" => '',
"headers" => [
'Paytweak-API-KEY' => $apiKey,
]
]
);
return json_decode($response->getContent(), true);
}
/**
* @param $token
* @param Company $company
* @return mixed
* @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*/
public function verify($token, Company $company)
{
$private_key = $this->parameterBag->get('PRIVATE_PAYTWEAK_FRESSIA'); // fressia
$url = $this->parameterBag->get('API_PAYTWEAK_URL');
if ($company->getName() === 'SILVER BEAUTÉ') {
//$private_key = '389f01e98d02992c';
$private_key = $this->parameterBag->get('PRIVATE_PAYTWEAK_SILVER');
$url = $this->parameterBag->get('API_PAYTWEAK_URL_SILVER');
}
$user_token = base64_encode(trim($token) . $private_key);
$response = $this->client->request(
Request::METHOD_GET,
$url . 'verify/',
[
"body" => '',
"headers" => [
'Paytweak-USER-TOKEN' => $user_token,
]
]
);
return json_decode($response->getContent(), true);
}
/**
* Problem when no address
* @param Invoice $invoice
* @param Company $company
* @return string
* @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*/
public function createBilling(Invoice $invoice, Company $company)
{
$token = $this->hello($company);
$url = $this->parameterBag->get('API_PAYTWEAK_URL');
if ($company->getName() === 'SILVER BEAUTÉ') {
$url = $this->parameterBag->get('API_PAYTWEAK_URL_SILVER');
}
$workToken = $this->verify($token['Paytweak-Security-Token'], $company);
$response = $this->client->request(
Request::METHOD_POST,
$url . 'invoices/',
[
"body" => $invoice->toArray(),
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
$statusCode = $response->getStatusCode();
// $statusCode = 200
$content = $response->getContent();
//dump($content);die;
$content = $response->toArray();
return $content;
}
/**
* Problem when no address
* @param Invoice $invoice
* @param Company $company
* @return string
* @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*/
public function reSend(Company $company, $orderId, $email)
{
$token = $this->hello($company);
$url = $this->parameterBag->get('API_PAYTWEAK_URL');
if ($company->getName() === 'SILVER BEAUTÉ') {
$url = $this->parameterBag->get('API_PAYTWEAK_URL_SILVER');
}
$workToken = $this->verify($token['Paytweak-Security-Token'], $company);
$response = $this->client->request(
Request::METHOD_POST,
$url . 'emails/',
[
"body" => [
'order_id' => $orderId,
'email' => $email,
'transactional' => 1,
'template' => $company->getId() === 2 ? '0JS6HBV' : 'GVB1WBK'
],
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
$statusCode = $response->getStatusCode();
// $statusCode = 200
$content = $response->toArray();
return $content;
}
/**
* Problem when no address
* @param Invoice $invoice
* @param Company $company
* @return string
* @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*/
public function getLink(Company $company, $orderId)
{
$token = $this->hello($company);
$url = $this->parameterBag->get('API_PAYTWEAK_URL');
if ($company->getName() === 'SILVER BEAUTÉ') {
$url = $this->parameterBag->get('API_PAYTWEAK_URL_SILVER');
}
$workToken = $this->verify($token['Paytweak-Security-Token'], $company);
$response = $this->client->request(
Request::METHOD_GET,
$url . 'links',
[
"query" => [
'order_id' => $orderId,
],
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
$statusCode = $response->getStatusCode();
// $statusCode = 200
$content = $response->toArray();
return $content;
}
public function listBilling(Company $company)
{
$token = $this->hello($company);
$url = $this->parameterBag->get('API_PAYTWEAK_URL');
if ($company->getName() === 'SILVER BEAUTÉ') {
$url = $this->parameterBag->get('API_PAYTWEAK_URL_SILVER');
}
$workToken = $this->verify($token['Paytweak-Security-Token'], $company);
$response = $this->client->request(
Request::METHOD_GET,
$url . 'invoices/',
[
'query' => [
'year' => date('Y'),
'month' => date('m')
],
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
$statusCode = $response->getStatusCode();
// $statusCode = 200
$content = $response->getContent();
$content = $response->toArray();
return $content;
}
public function getBilling($orderId, Company $company)
{
$token = $this->hello($company);
$url = $this->parameterBag->get('API_PAYTWEAK_URL');
if ($company->getName() === 'SILVER BEAUTÉ') {
$url = $this->parameterBag->get('API_PAYTWEAK_URL_SILVER');
}
$workToken = $this->verify($token['Paytweak-Security-Token'], $company);
$response = $this->client->request(
Request::METHOD_GET,
$url . 'links/',
[
'query' => [
'order_id' => $orderId,
],
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
$statusCode = $response->getStatusCode();
// $statusCode = 200
$content = $response->getContent();
$content = $response->toArray();
return $content;
}
public function createInvoiceFromClient(Client $client, Billing $billing)
{
$invoice = new Invoice();
$cityFill = !!$client->getCity();
$invoice->setCity($client->getCity());
if (!$cityFill) {
$invoice->setCity($billing->getClient()->getSite()->getAddress()->getCity());
}
if ($client->getBillingInfos() && $client->getBillingInfos()->getEmail()) {
$invoice->setEmail($client->getBillingInfos()->getEmail());
} else {
if ($client->getEmail()) {
$invoice->setEmail($client->getEmail());
}
// else {
// $invoice->setEmail($client->getSite()->getContactBilling()->getEmail());
// }
}
$invoice->setFirstname($client->getFirstname());
$invoice->setLastname($client->getLastname());
$invoice->setZip($client->getZipcode());
if (!$cityFill) {
$invoice->setZip($billing->getClient()->getSite()->getAddress()->getZipcode());
}
$invoice->setCur('EUR');
$invoice->setFirstname($client->getFirstname());
$invoice->setLastname($client->getLastname());
$genre = 'M';
if ($client->getGender() === 'Madame') {
$genre = 'Me';
}
$invoice->setGender($genre);
$invoice->setPhone($client->getPhone());
$invoice->setAddressCustomer($client->getAddressTuteur());
if (!$cityFill) {
$invoice->setAddressCustomer($billing->getClient()->getSite()->getAddress()->getStreet());
}
$invoice->setCustomerRef($client->getIdentifier());
$invoice->setReference($billing->getCode());
$invoice->setAmount($billing->getTtc());
$invoice->setDate($billing->getDateBilling()->format('d/m/Y'));
$invoice->setFreetext($billing->getComment());
//$invoice->setDiscountName('Remise');
//$invoice->setDiscountAmount($billing->get);
$items = [];
/** @var BillingItem $item */
foreach ($billing->getBillingItems() as $item) {
$rdv = $billing->getRDV();
$date = $item->getDateRDV() ? $item->getDateRDV()->format('d/m/Y') : '';
$items[] = [
'ref' => $item->getId(),
'desc' => $date . ' - ' . $item->getLibelleProduct(),
'quantity' => $item->getQuantity(),
'vat' => '20',
'price' => $item->getPrice(),
'discount' => $item->getDiscount()
];
}
$invoice->setItems(json_encode($items));
$invoice->setEmailTemplate('B7EV3PN');
if($client->getBillingInfos() && $client->getBillingInfos()->getPayMode() === Client\BillingInfos::PAY_MODE_SEPA){
$invoice->setEmailTemplate('HURNEAN');
}
if ($_SERVER['SERVER_NAME'] === 'emmaconnect.fr') {
$invoice->setTemplate('classic_SilverBeaute_discount');
$invoice->setSend(true);
}
return $invoice;
}
/**
* method hello
* @return mixed
*/
public function helloReservation()
{
$apiKey = $this->parameterBag->get('API_KEY_PAYTWEAK');
$url = $this->parameterBag->get('API_PAYTWEAK_URL_DEV');
$response = $this->client->request(
Request::METHOD_GET,
$url . 'hello/',
[
"body" => '',
"headers" => [
'Paytweak-API-KEY' => $apiKey,
]
]
);
return json_decode($response->getContent(), true);
}
/**
* method verify
* @param mixed $token
*
* @return mixed
*/
public function verifyReservation($token)
{
$private_key = $this->parameterBag->get('PRIVATE_PAYTWEAK');
$url = $this->parameterBag->get('API_PAYTWEAK_URL_DEV');
$user_token = base64_encode(trim($token) . $private_key);
$response = $this->client->request(
Request::METHOD_GET,
$url . 'verify/',
[
"body" => '',
"headers" => [
'Paytweak-USER-TOKEN' => $user_token,
]
]
);
return json_decode($response->getContent(), true);
}
/**
* create payment link
* @return array
*/
public function createLink($orderIdPaytweak = null, $scenario = null)
{
$token = $this->helloReservation();
$url = $this->parameterBag->get('API_PAYTWEAK_URL_DEV');
$workToken = $this->verifyReservation($token['Paytweak-Security-Token']);
$requestBody = [
'operation' => 'TOK',
'amount' => '0'
];
if ($scenario) {
$requestBody['scenario'] = $scenario;
}
if ($orderIdPaytweak !== null) {
//$requestBody['order_id'] = $orderIdPaytweak;
}
try {
$response = $this->client->request(
Request::METHOD_POST,
$url . 'links',
[
"body" => $requestBody,
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
$this->logger->error(json_encode($response->getContent()));
} catch (\Exception $exception) {
$this->logger->error($exception->getMessage());
}
return json_decode($response->getContent(), true);
}
public function createLinkScenario(Company $company,
$orderIdPaytweak = null,
$scenario = null,
$amount,
$email,
$prenom,
$nom,
$gender,
$order_id,
$rum = null,
$template
)
{
$token = $this->hello($company);
$url = $this->parameterBag->get('API_PAYTWEAK_URL_DEV'); ////api.silver-beaute.paytweak.com/v1/
$workToken = $this->verify($token['Paytweak-Security-Token'], $company);
$requestBody = [
'operation' => 'TOK',
'amount' => $amount,
'email' => $email,
'firstname' => $prenom,
'lastname' => $nom,
'mandat' => $rum,
'lng' => 'fr_FR',
'cur' => 'EUR',
'template' => $template,
'gender' => $gender,
'order_id' => $order_id
];
if ($scenario) {
$requestBody['scenario'] = $scenario;
}
if ($orderIdPaytweak !== null) {
//$requestBody['order_id'] = $orderIdPaytweak;
}
try {
$response = $this->client->request(
Request::METHOD_POST,
$url . 'emails',
[
"body" => $requestBody,
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
$this->logger->error(json_encode($response->getContent()));
} catch (\Exception $exception) {
$this->logger->error($exception->getMessage());
}
return json_decode($response->getContent(), true);
}
/**
* Get payment information
* @return array
*/
public function checkPayment($linkId)
{
$token = $this->helloReservation();
$url = $this->parameterBag->get('API_PAYTWEAK_URL_DEV');
$workToken = $this->verifyReservation($token['Paytweak-Security-Token']);
$response = $this->client->request(
Request::METHOD_GET,
$url . 'links/' . $linkId,
[
"body" => [],
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
return json_decode($response->getContent(), true);
}
/**
* Trigger payment
* @return array
*/
public function triggerPayment(string $link, float $amount, $orderCode)
{
$token = $this->helloReservation();
$url = $this->parameterBag->get('API_PAYTWEAK_URL_DEV');
$amount = number_format($amount, 2, '.', '');
$workToken = $this->verifyReservation($token['Paytweak-Security-Token']);
preg_match("/[^\/]+$/", $link, $matches);
$response = $this->client->request(
Request::METHOD_POST,
$url . 'm2m/token',
[
"body" => [
'order_id' => $orderCode,
'amount' => "{$amount}",
'token' => $matches[0],
],
"headers" => [
'Paytweak-Token' => $workToken['Paytweak-Work-Token'],
]
]
);
return json_decode($response->getContent(), true);
}
/**
* Generate password
* @param int $length
*
* @return string
*/
private function passwordGenerate($length): string
{
$data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle($data), 0, $length);
}
}