Chat global
QRCode Pix / WorldPK Shop

Salve rapaziada, na source do WorldPK que tem um pessoal que não está conseguindo gerar aquele qrcode do pix e tal, vim aqui deixar um leve tutorial mostrando como que fiz pra poder funcionar. Só precisa ter uma conta lá no Mercado Pago como vendedor, cadastrar uma chave pix aleatória e pegar o access Token.
Primeiro passo na NewShop.cpp na source do game faça a adição logo no inicio da cpp abaixo de "char amount[32] = { 0 };":
std::string pixCodeResponse;
Próximo passo é na showDonationOptions, que irão usar essa:
void showDonationOptions() { ImVec2 center = ImGui::GetMainViewport()->GetCenter(); ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); ImGui::SetNextWindowSize(ImVec2(400, 500)); if (ImGui::BeginPopupModal(u8"Efetuar uma doação", NULL, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize)) { switch (aux2) { case 0: { int posInicial = 70; ImGui::Text(u8"Selecione uma opção de doação e aguarde"); ImGui::Text(u8"a geração do seu QR Code de pagamento."); for (int x = 0; x < 6; x++) { ImGui::PushID(x); char msg[64] = { 0 }; sprintf_s(msg, sizeof(msg), u8"Valor da doação: R$ %d,00", DonationValues[x]); ImGui::SetCursorPosX(250); ImGui::Image(DonateImages[x], ImVec2(40, 40)); ImGui::SetCursorPosY(posInicial); posInicial += 20; if (ImGui::Selectable(msg, selectedDonation == DonationValues[x], 0, ImVec2(240, 36))) { { if (backgroundThread.joinable()) { backgroundThread.join(); } valorSelecionado = DonationValues[x]; NewShop::GetInstance()->Donation(valorSelecionado); } } if (x == 3) sprintf_s(msg, sizeof(msg), u8"Valor em Coins: %d + 50 Bônus", DonationResults[x]); else if (x == 4) sprintf_s(msg, sizeof(msg), u8"Valor em Coins: %d + 75 Bônus", DonationResults[x]); else if (x == 5) sprintf_s(msg, sizeof(msg), u8"Valor em Coins: %d + 100 Bônus", DonationResults[x]); else sprintf_s(msg, sizeof(msg), "Valor em Coins: %d", DonationResults[x]); ImGui::SetCursorPosY(posInicial); ImGui::Text(msg); ImGui::Separator(); ImGui::Text(""); ImGui::PopID(); posInicial += 40; } ImGui::SetCursorPosX(80); if (ImGui::Button("Fechar", ImVec2(140, 0))) { aux = 0; ImGui::CloseCurrentPopup(); } break; } case 1: { Pagpix(pixCodeResponse.c_str()); break; } case 2: { ImGui::SetCursorPosX(120); ImGui::SetCursorPosY(200); ImGui::Text("Gerando seu QR Code..."); ImGui::SetCursorPosY(220); ImGui::Text("Por favor, aguarde."); break; } } ImGui::EndPopup(); } }
void NewShop::Donation(int amount) { aux2 = 2; backgroundThread = std::thread([=]() { CURL* curl = curl_easy_init(); std::string urlDonate; if (curl) { CURLcode res; char szstring[256] = { 0 }; sprintf_s(szstring, sizeof(szstring), "https://MINHAAPIPARAGERARCOPIAECOLA.COM/test.php?user_id=%s&amount=%d", UserAccount, amount); curl_easy_setopt(curl, CURLOPT_URL, szstring); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &urlDonate); res = curl_easy_perform(curl); if (res == CURLE_OK && !urlDonate.empty()) { pixCodeResponse = urlDonate; aux2 = 1; cMessageBox.ShowMessage("QRCode Pix gerado com sucesso!!"); } else { cMessageBox.ShowMessage("Sistema indisponivel no momento!!"); aux2 = 0; } curl_easy_cleanup(curl); } }); }
PhP:
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF--8"); error_reporting(E_ALL); ini_set('display_errors', 1); // Configurações do banco de dados $host = 'localhost'; $user = 'xdd'; $password = 'xdd'; $database = 'xdd'; // Conecta ao MySQL $conn = new mysqli($host, $user, $password, $database); if ($conn->connect_error) { $response = [ 'status' => 'error', 'message' => 'Falha na conexão com o banco de dados: ' . $conn->connect_error ]; echo json_encode($response); exit; } $numeroPedido = isset($_GET['user_id']) ? $_GET['user_id'] : null; $emailCliente = isset($_GET['user_id']) ? $_GET['user_id'] . "@emaildojogo.com" : "default@email.com"; $valor = isset($_GET['amount']) ? (float)$_GET['amount'] : 0.00; // Log dos dados recebidos (para depuração) error_log("Dados recebidos no PHP: " . print_r($_GET, true)); if (!$numeroPedido || $valor <= 0) { $response = [ 'status' => 'error', 'message' => 'Dados insuficientes para gerar o pagamento.', 'data' => [ 'numero_pedido' => $numeroPedido, 'email_cliente' => $emailCliente, 'valor' => $valor ] ]; echo json_encode($response); exit; } $idempotencyKey = uniqid(); $accessToken = 'APP_USR-DOSEUMERCADOPAGO'; $data = [ "transaction_amount" => $valor, "description" => "Creditos para o Jogo - Usuario: " . $numeroPedido, "payment_method_id" => "pix", "notification_url" => "https://APIRETORNODENOTIFICATION.com/notification.php", "payer" => [ "email" => $emailCliente ] ]; $jsonData = json_encode($data); $url = "https://api.mercadopago.com/v1/payments"; // Configura a requisição HTTP com cURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "Authorization: Bearer " . $accessToken, "X-Idempotency-Key: " . $idempotencyKey ]); $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode !== 201) { $response = [ 'status' => 'error', 'message' => 'Erro ao criar pagamento no Mercado Pago.', 'http_code' => $httpCode, 'response' => $result ]; echo json_encode($response); exit; } // Verifica a resposta $response = json_decode($result, true); if (json_last_error() !== JSON_ERROR_NONE) { $response = [ 'status' => 'error', 'message' => 'Erro ao decodificar resposta do Mercado Pago.', 'json_error' => json_last_error_msg(), 'raw_response' => $result ]; echo json_encode($response); exit; } // Extrai o código Pix "copia e cola" e payment_id $pixCopiaCola = isset($response['point_of_interaction']['transaction_data']['qr_code']) ? $response['point_of_interaction']['transaction_data']['qr_code'] : null; $paymentId = isset($response['id']) ? $response['id'] : null; $stmt = $conn->prepare("INSERT INTO pagamentos (numero_pedido, valor, email_cliente, status, pix_copia_cola, response_json, payment_id) VALUES (?, ?, ?, ?, ?, ?, ?)"); $status = 'pending'; $response_json = $result; n $stmt->bind_param("sdsssss", $numeroPedido, $valor, $emailCliente, $status, $pixCopiaCola, $response_json, $paymentId); if ($stmt->execute()) { header('Content-Type: text/plain'); echo $pixCopiaCola; } else { $response = [ 'status' => 'error', 'message' => 'Erro ao inserir no banco de dados.', 'error' => $stmt->error ]; http_response_code(500); echo json_encode($response); } $stmt->close(); $conn->close(); ?>
Agora vocês só precisam criar o notification.php que tem na documentação do MercadoPago e ajustar pra receber esses dados e inserir no sql direto na ID do player caso o pagamento for concluido e também uma curl simples pra verificar pagamentos pendentes. Espero que ajude.
Vídeo do funcionamento:

god

show! 💫
Apenas criando um legado 😊





monstro!
William Varvenczak
- 20 Fóruns
- 222 Tópicos
- 1,245 Posts
- 4 Online
- 213 Membros