Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: pix payment system (polopag) #124

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions check_pix_status.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
define('INCLUDED', true);
require 'polopag_config.php';

error_reporting(0);
ini_set('display_errors', 0);

function connect_to_database($config)
{
try {
$dsn = "mysql:host={$config['host']};dbname={$config['database']};port={$config['port']};charset=utf8mb4";
$pdo = new PDO($dsn, $config['user'], $config['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
die("Erro ao conectar ao banco de dados.");
}
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$reference = filter_input(INPUT_POST, 'reference', FILTER_SANITIZE_STRING);

if (!$reference) {
echo json_encode(['status' => 'ERROR', 'message' => 'Referência inválida.']);
exit;
}

$config = read_config($config_path);
$pdo = connect_to_database($config);

try {
$query = "SELECT status FROM polopag_transacoes WHERE reference = :reference LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute([':reference' => $reference]);
$pix = $stmt->fetch(PDO::FETCH_ASSOC);

if ($pix) {
echo json_encode(['status' => $pix['status']]);
} else {
echo json_encode(['status' => 'NOT_FOUND']);
}
} catch (PDOException $e) {
echo json_encode(['status' => 'ERROR', 'message' => "Erro ao verificar status do PIX"]);
}
}
2 changes: 1 addition & 1 deletion common.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

define('MYAAC', true);
define('MYAAC_VERSION', '0.8.16');
define('DATABASE_VERSION', 35);
define('DATABASE_VERSION', 36);
define('TABLE_PREFIX', 'myaac_');
define('START_TIME', microtime(true));
define('MYAAC_OS', stripos(PHP_OS, 'WIN') === 0 ? 'WINDOWS' : (strtoupper(PHP_OS) === 'DARWIN' ? 'MAC' : 'LINUX'));
Expand Down
2 changes: 1 addition & 1 deletion install/includes/schema.sql
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
SET @myaac_database_version = 34;
SET @myaac_database_version = 36;

CREATE TABLE `myaac_account_actions`
(
Expand Down
Binary file added payments/images/aprovado.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added payments/images/expirado.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added payments/images/pix.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 50 additions & 0 deletions polopag_config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php
if (!defined('INCLUDED')) {
http_response_code(403);
die('Acesso direto não permitido.');
}

error_reporting(0);
ini_set('display_errors', 0);

// Path para o config.lua
$config_path = ''; // Adicionar o caminho do servidor!!!
function read_config($config_path)
{
$config = [];
if (!file_exists($config_path)) {
die("Arquivo de configuração não encontrado.");
}

$file_content = file_get_contents($config_path);

preg_match('/mysqlHost\s*=\s*"(.*)"/', $file_content, $host_match);
preg_match('/mysqlUser\s*=\s*"(.*)"/', $file_content, $user_match);
preg_match('/mysqlPass\s*=\s*"(.*)"/', $file_content, $password_match);
preg_match('/mysqlDatabase\s*=\s*"(.*)"/', $file_content, $database_match);
preg_match('/mysqlPort\s*=\s*(\d+)/', $file_content, $port_match);

$config['host'] = $host_match[1];
$config['user'] = $user_match[1];
$config['password'] = $password_match[1];
$config['database'] = $database_match[1];
$config['port'] = $port_match[1];
$config['api_url'] = "https://api.polopag.com/v1/cobpix";
$config['api_key'] = ""; // Adicionar sua key aqui!!! Works with PIX from: https://polopag.com
$config['coins_column'] = "coins_transferable";
$config['webhook_url'] = "https://" . $_SERVER['HTTP_HOST'] . "/polopag_webhook.php";

return $config;
}

function calculatePromotionPoints($price) { // Implemente ou modifique sua própria fórmula de cálculo de pontos
if ($price > 0) {
$points = floor($price);
if ($price > 50) {
$points *= 2;
}
return $points;
} else {
return 0;
}
}
203 changes: 203 additions & 0 deletions polopag_generate_pix.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
<?php
define('INCLUDED', true);
require 'polopag_config.php';

error_reporting(0);
ini_set('display_errors', 0);
session_start();
function connect_to_database($config)
{
try {
$dsn = "mysql:host={$config['host']};dbname={$config['database']};port={$config['port']};charset=utf8mb4";
$pdo = new PDO($dsn, $config['user'], $config['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
die("Erro ao conectar ao banco de dados: ");
}
}

function generate_pix_from_polopag($reference, $price, $config)
{
$data = [
"valor" => number_format($price, 2, '.', ''),
"calendario" => ["expiracao" => 3600],
"referencia" => $reference,
"solicitacaoPagador" => "Pagamento via PIX",
"infoAdicionais" => [],
"webhookUrl" => $config['webhook_url']
];

$headers = [
"Api-Key: {$config['api_key']}",
"Content-Type: application/json"
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $config['api_url']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code == 200) {
$response_data = json_decode($response, true);
return $response_data;
} else {
die("Erro ao gerar o PIX. Por favor, tente novamente mais tarde.");
}
}

function check_existing_pix($account_id, $price, $pdo)
{
$query_check = "SELECT * FROM polopag_transacoes
WHERE account_id = :account_id
AND price = :price
AND status = 'ATIVA'
AND expires_at > NOW()
LIMIT 1";
$stmt_check = $pdo->prepare($query_check);
$stmt_check->execute([
':account_id' => $account_id,
':price' => $price
]);

$existing_pix = $stmt_check->fetch(PDO::FETCH_ASSOC);

if ($existing_pix) {
return [
'reference' => $existing_pix['reference'],
'txid' => $existing_pix['txid'],
'internalId' => $existing_pix['internalId'],
'base64' => $existing_pix['base64'],
'copia_e_cola' => $existing_pix['copia_e_cola'],
'price' => $existing_pix['price'],
'points' => $existing_pix['points'],
'status' => $existing_pix['status']
];
}

return false;
}

function get_account_id($account_name, $pdo)
{
try {
$account_id_query = $pdo->prepare("SELECT id FROM accounts WHERE name = :account_name LIMIT 1");
$account_id_query->execute([':account_name' => $account_name]);
$account = $account_id_query->fetch(PDO::FETCH_ASSOC);

if (!$account) {
return false;
}

return $account['id'];
} catch (PDOException $e) {
die("Erro ao buscar o ID da conta.");
}
}
function store_pix_data($reference, $txid, $internalId, $base64, $copia_e_cola, $price, $points, $status, $type, $account_id, $pdo)
{
$current_time = time();
$last_generated_time = $_SESSION['last_pix_generated_time'] ?? 0;

if (($current_time - $last_generated_time) < 10) {
die("Aguarde 10 segundos entre uma geração de PIX e outra.");
}

$_SESSION['last_pix_generated_time'] = $current_time;

try {
$query = "INSERT INTO polopag_transacoes (account_id, reference, txid, internalId, base64, copia_e_cola, price, points, status, type, origin, created_at, expires_at)
VALUES (:account_id, :reference, :txid, :internalId, :base64, :copia_e_cola, :price, :points, :status, :type, 'site', NOW(), NOW() + INTERVAL 1 HOUR)";
$stmt = $pdo->prepare($query);

$stmt->execute([
':account_id' => $account_id,
':reference' => $reference,
':txid' => $txid,
':internalId' => $internalId,
':base64' => $base64,
':copia_e_cola' => $copia_e_cola,
':price' => $price,
':points' => $points,
':status' => $status,
':type' => $type
]);

return [
'reference' => $reference,
'txid' => $txid,
'internalId' => $internalId,
'base64' => $base64,
'copia_e_cola' => $copia_e_cola,
'price' => $price,
'points' => $points,
'status' => $status
];

} catch (PDOException $e) {
die("Erro ao armazenar dados do PIX.");
}
}
function return_json_response($reference, $price, $points, $base64, $copia_e_cola)
{
if (ob_get_length()) {
ob_clean();
}

header('Content-Type: application/json');
echo json_encode([
'reference' => $reference,
'price' => $price,
'points' => $points,
'base64' => $base64,
'copia_e_cola' => $copia_e_cola // Adicione isso aqui
]);

exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$config = read_config($config_path);
$account_name = filter_input(INPUT_POST, 'account_name', FILTER_SANITIZE_STRING);
$price = filter_input(INPUT_POST, 'price', FILTER_SANITIZE_STRING);

if ($price <= 1) {
die("O preço deve ser maior que 1.");
}

if (!$account_name) {
die("Nome da conta inválido.");
}

$pdo = connect_to_database($config);
$account_id = get_account_id($account_name, $pdo);

if (!$account_id) {
die("Conta não encontrada para o nome de usuário: $account_name");
}

$reference = 'REF' . strtoupper(uniqid()) . strtoupper(uniqid());
$existing_pix = check_existing_pix($account_id, $price, $pdo);

if ($existing_pix) {
return_json_response($existing_pix['reference'], $existing_pix['price'], $existing_pix['points'], $existing_pix['base64']);
} else {
$pix_data = generate_pix_from_polopag($reference, $price, $config);
$txid = $pix_data['txid'];
$internalId = $pix_data['internalId'];
$base64 = $pix_data['qrcodeBase64'];
$copia_e_cola = $pix_data['pixCopiaECola'];
$status = $pix_data['status'];
$type = $config['coins_column'];
$points = calculatePromotionPoints($price);

store_pix_data($reference, $txid, $internalId, $base64, $copia_e_cola, $price, $points, $status, $type, $account_id, $pdo);
return_json_response($reference, $price, $points, $base64, $copia_e_cola); // Adicione copia_e_cola aqui
}
}
24 changes: 24 additions & 0 deletions system/migrations/36.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

if(!$db->hasTable('z_polls')) {
$db->query('
CREATE TABLE `polopag_transacoes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`account_id` int(11) NOT NULL,
`reference` varchar(255) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
`txid` varchar(255) NOT NULL,
`internalId` varchar(255) NOT NULL,
`base64` mediumtext DEFAULT NULL,
`copia_e_cola` mediumtext DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
`points` int(11) DEFAULT NULL,
`coins_table` varchar(255) DEFAULT NULL,
`status` varchar(50) DEFAULT NULL,
`expires_at` datetime DEFAULT NULL,
`origin` enum("game", "site") NOT NULL DEFAULT "site",
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
');
}
24 changes: 24 additions & 0 deletions system/pages/donate_pix.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
global $config, $twig, $logged;

/**
* @name myaac-polopag-pix
* @author Marcinho1994, Rokam and luanluciano93
* @version 1.0
*/

defined('MYAAC') or die('Direct access not allowed!');
$title = 'Donate Pix';

$twig->addGlobal('config', $config);

if (!$logged) {
$was_before = $config['friendly_urls'];
$config['friendly_urls'] = true;
echo 'To buy coins you need to be logged. ' . generateLink(getLink('?subtopic=accountmanagement') . '&redirect=' . urlencode(BASE_URL . '?donate_pix'), 'Login') . ' first to make a donate.';
$config['friendly_urls'] = $was_before;
} else {
echo $twig->display('donate.pix_generator.html.twig', array(
"accName" => $account_logged->getName(),
));
}
Loading
Loading