Ir para conteúdo
  • ×   Você colou conteúdo com formatação.   Remover formatação

      Only 75 emoji are allowed.

    ×   Your link has been automatically embedded.   Display as a link instead

    ×   Your previous content has been restored.   Clear editor

    ×   You cannot paste images directly. Upload or insert images from URL.

  • Conteúdo Similar

    • Por user32
      Boa noite a todos, 
      comprei um formulário de pagamento via pix através do mercadopago no qual a pessoa q me vendeu não me da suporte algum e to quase uma semana quebrando cabeça com isso.
      ao clicar em gerar pix não há efeito algum.
       
      <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); /** * Automatic Mercadopago payment system gateway. * * @name pix-myaac-mercadopago * @author Rafhael Oliveira <rafhaelxd@gmail.com> * @website github.com/thetibiaking/ttk-myaac-plugins * @website github.com/underewarrr/ * @version 1.0.0 */ require_once('/var/www/html/classes/functions.php'); require_once('/var/www/html/system/load.init.php'); require_once('/var/www/html/mercadopago/pix/config.php'); if (isset($config['mercadopago']) && $config['mercadopago'] = true) { } else { echo "MercadoPago is disabled. If you're an admin please configure this script in config.local.php."; return; } if (empty($logged)) { header("Location: " . $noSessionUrl); exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Verifica se os dados foram enviados via POST // Caminho relativo para o arquivo config.php $quantidadeSelecionada = (int)$_POST['quantidade']; $cpf = $_POST['cpf']; // Validate CPF if (!validateCPF($cpf)) { echo '<p>CPF inválido. Por favor, verifique e tente novamente.</p>'; exit; } $totalValue = $quantidadeSelecionada * $priceByPoints; $pontosGanhos = $quantidadeSelecionada * $pointsByDonate; $curl = curl_init(); $dados["transaction_amount"] = $totalValue; $dados["description"] = $_POST['description'] ?: 'Value and Coins'; $dados["external_reference"] = "2"; $dados["payment_method_id"] = "pix"; $dados["notification_url"] = $notificationUrl; $dados["payer"]["email"] = $_POST['email_cob']; $dados["payer"]["first_name"] = "Nilza"; $dados["payer"]["last_name"] = "Guimaraes"; $dados["payer"]["identification"]["type"] = "CPF"; $dados["payer"]["identification"]["number"] = $cpf; $dados["payer"]["address"]["zip_code"] = "76240000"; $dados["payer"]["address"]["street_name"] = "Av. Carlos Gomes"; $dados["payer"]["address"]["street_number"] = "411"; $dados["payer"]["address"]["neighborhood"] = "Bela Vista"; $dados["payer"]["address"]["city"] = "Aragarcas"; $dados["payer"]["address"]["federal_unit"] = "GO"; curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.mercadopago.com/v1/payments', CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => json_encode($dados), CURLOPT_HTTPHEADER => array( 'accept: application/json', 'content-type: application/json', 'Authorization: Bearer ' . $authorizationToken, ), )); $response = curl_exec($curl); $resultado = json_decode($response); $collector_id = isset($resultado->id) ? $resultado->id : null; curl_close($curl); // Display full response for debugging if debug is enabled if ($debug) { echo '<pre>'; var_dump($resultado); echo '</pre>'; } // Check if collector_id is present if (!$collector_id) { echo '<p>Error: Collector ID not found in the response.</p>'; exit; } echo 'Collector ID: ' . $collector_id; // Verifica se a resposta foi bem-sucedida antes de exibir o QR Code if ($resultado->status === 'pending') { // Exibe o QR Code e o código apenas se o debug estiver desativado if (!$debug) { echo '<img style="display:block; width:300px;height:300px;" id="base64image" src="data:image/jpeg;base64, ' . $resultado->point_of_interaction->transaction_data->qr_code_base64 . '" />'; echo '<b>Copie:</b> ' . $resultado->point_of_interaction->transaction_data->qr_code; } // Exibe os pontos ganhos echo '<p>Você gerou um pix no valor de ' .$totalValue. 'R$ e ' . $pontosGanhos . ' pontos!</p>'; echo '<p>Ao Pagar você recebera seus pontos automaticamente</p>'; echo '<p>Status: ' . $resultado->status . '</p>'; echo '<button onclick="location.href=\'https://meusite.com/?subtopic=mpnotification&id=' . $collector_id . '&debug=' . ($debug ? 'true' : 'false') . '\'" type="button">Conferir Status do Pedido</button> <br>'; // Ação no banco de dados (se necessário) $logged = getSession('account'); $sql = "INSERT INTO status(status, codigo, account, points) VALUES(?, ?, ?, ?)"; $stmt = mysqli_prepare($conexao, $sql); // Check if the statement was prepared successfully if ($stmt) { // Assuming $logged and $pontosGanhos are defined elsewhere in your code // Bind parameters with data types mysqli_stmt_bind_param($stmt, "sssi", $resultado->status, $collector_id, $logged, $pontosGanhos); // Execute the statement mysqli_stmt_execute($stmt); // Check for successful execution if (mysqli_stmt_affected_rows($stmt) > 0) { echo "Record inserted successfully"; } else { echo "Error inserting record"; } // Close the statement mysqli_stmt_close($stmt); } else { echo "Error preparing statement: " . mysqli_error($conexao); } } else { echo '<p>Erro ao processar o pagamento. Tente novamente.</p>'; // Display error message, if available if (isset($resultado->message)) { echo '<p>Error Message: ' . $resultado->message . '</p>'; } // Display status for further analysis echo '<p>Status: ' . $resultado->status . '</p>'; } } else { // Formulário para preenchimento dos dados echo ' <form method="POST"> <label for="quantidade">Quantidade de Doações:</label> <select name="quantidade" id="quantidade" required> <option value="1">1 - R$25,00 (60 pontos)</option> <option value="2">2 - R$50,00 (120 pontos)</option> <option value="3">3 - R$75,00 (180 pontos)</option> <!-- Adicione mais opções conforme necessário --> </select> <br> <label for="description">Descrição:</label> <input type="text" name="description" id="description" placeholder="Write any description" required> <br> <label for="email_cob">Email do Pagador:</label> <input type="email" name="email_cob" id="email_cob" required> <br> <label for="cpf">CPF do Pagador:</label> <input type="text" name="cpf" id="cpf" required> <br> <button type="submit">Gerar Pix</button> </form> '; } // Simple CPF validation function function validateCPF($cpf) { // Remove any non-numeric characters $cpf = preg_replace('/[^0-9]/', '', $cpf); // Check if CPF has 11 digits if (strlen($cpf) != 11) { return false; } // Validate CPF using basic algorithm $sum = 0; for ($i = 0; $i < 9; $i++) { $sum += (int)$cpf[$i] * (10 - $i); } $remainder = $sum % 11; $digit = ($remainder < 2) ? 0 : 11 - $remainder; if ((int)$cpf[9] != $digit) { return false; } $sum = 0; for ($i = 0; $i < 10; $i++) { $sum += (int)$cpf[$i] * (11 - $i); } $remainder = $sum % 11; $digit = ($remainder < 2) ? 0 : 11 - $remainder; if ((int)$cpf[10] != $digit) { return false; } return true; } ?> <?php /** * Automatic Mercadopago payment system gateway. * * @name pix-myaac-mercadopago * @author Rafhael Oliveira <rafhaelxd@gmail.com> * @website github.com/thetibiaking/ttk-myaac-plugins * @website github.com/underewarrr/ * @version 1.0.0 */ require_once('/var/www/html/classes/functions.php'); require_once('/var/www/html/system/load.init.php'); require_once('/var/www/html/mercadopago/pix/config.php'); // Set debug mode based on the query parameter // use debug true in url to get more infos $debug = isset($_REQUEST['debug']) && $_REQUEST['debug'] === 'true'; // Verify if the collector_id is present in the request if (isset($_REQUEST['id'])) { $collector_id = $_REQUEST['id']; // Initialize cURL $curl = curl_init(); // Set cURL options curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.mercadopago.com/v1/payments/' . $collector_id, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_HTTPHEADER => array( 'accept: application/json', 'content-type: application/json', 'Authorization: Bearer ' . $authorizationToken, ), )); // Execute cURL request $response = curl_exec($curl); // Check if cURL request was successful if ($response === false) { // Handle cURL error echo 'Error fetching payment details from Mercado Pago API.'; if ($debug) { echo '<br>Debug Mode: ON'; echo '<br>Status from Mercado Pago API: ' . $resultado->status; echo 'Total Paid Amount or Transaction Amount: ' . $resultado->transaction_amount * $conversionRate; echo '<br>Status from Mercado Pago API: <pre>' . print_r($resultado, true) . '</pre>'; echo '<br>CURL Error: ' . curl_error($curl); } } else { // Decode the JSON response $resultado = json_decode($response); // Check if the payment status is 'approved' or 'paid' // Check if the payment status is approved or paid // Check if the payment status is approved or paid if ($resultado->status === 'approved' || $resultado->status === 'paid') { // Check if the payment has already been processed $check_processed = "SELECT processed FROM status WHERE codigo = ?"; $stmt_check = mysqli_prepare($conexao, $check_processed); mysqli_stmt_bind_param($stmt_check, "i", $collector_id); mysqli_stmt_execute($stmt_check); mysqli_stmt_bind_result($stmt_check, $processed); mysqli_stmt_fetch($stmt_check); mysqli_stmt_close($stmt_check); if ($processed === 0 || $processed === null) { // Payment not processed yet // Mark the payment as processed $update_processed = "UPDATE status SET processed = 1 WHERE codigo = ?"; $stmt_processed = mysqli_prepare($conexao, $update_processed); mysqli_stmt_bind_param($stmt_processed, "i", $collector_id); mysqli_stmt_execute($stmt_processed); mysqli_stmt_close($stmt_processed); $new_status_value = 'delivered'; // Here's the additional update query for the status column in the status table $update_status = "UPDATE status SET status = ? WHERE codigo = ?"; $stmt_status = mysqli_prepare($conexao, $update_status); mysqli_stmt_bind_param($stmt_status, "si", $new_status_value, $collector_id); // Replace $new_status_value with the appropriate value mysqli_stmt_execute($stmt_status); mysqli_stmt_close($stmt_status); // Calculate premium points based on total_paid_amount and conversion rate $conversionValue = $resultado->transaction_amount * $conversionRate; // Get the current session account $logged = getSession('account'); // Update the accounts table with premium points using prepared statement $update_accounts = "UPDATE accounts SET $donationType = $donationType + ? WHERE id = ?"; $stmt_accounts = mysqli_prepare($conexao, $update_accounts); // Check if the statement for accounts table was prepared successfully if ($stmt_accounts) { // Bind parameters with data types for accounts table mysqli_stmt_bind_param($stmt_accounts, "di", $conversionValue, $logged); // Execute the statement for accounts table mysqli_stmt_execute($stmt_accounts); // Check for successful execution for accounts table if (mysqli_stmt_affected_rows($stmt_accounts) > 0) { echo "Premium points updated successfully in accounts table"; } else { echo "Error updating premium points in accounts table"; } // Close the statement for accounts table mysqli_stmt_close($stmt_accounts); } else { echo "Error preparing statement for accounts table: " . mysqli_error($conexao); } } else { echo 'Payment already processed.'; } } else { echo 'Payment status is not "approved" or "paid". No database update performed.'; } if ($debug) { echo '<br>Debug Mode: ON'; echo '<br>Status from Mercado Pago API: ' . $resultado->status; echo 'Total Paid Amount or Transaction Amount: ' . $resultado->transaction_amount * $conversionRate; echo '<br>Status from Mercado Pago API: <pre>' . print_r($resultado, true) . '</pre>'; echo '<br>CURL Error: ' . curl_error($curl); } } // Close cURL curl_close($curl); } else { echo 'Invalid or missing collector_id in the request.'; if ($debug) { echo '<br>Debug Mode: ON'; // Add more debug information as needed } } ?> <?php $pointsByDonate = 60; // coins $priceByPoints = 25.00; // value $conversionRate = $pointsByDonate / $priceByPoints; $debug = true; $notificationUrl = 'https://meusite.com/?subtopic=mpnotification'; $noSessionUrl = 'https://meusite.com/?subtopic=accountmanagement'; $donationType = 'premium_points'; // coins or premium_points $doublePoints = false; // not added yet $authorizationToken = 'APP_USR-4182410924225948-0415***************557-1249281564'; $servername = "localhost"; $username = "usuario"; $password = "senha"; $db_name = "bancodedados"; $conexao = mysqli_connect($servername, $username, $password, $db_name); if (!$conexao) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?>  
    • Por Carlos Antoliv
      Senhores, tudo bem?
       
      Tô numa dúvida aqui... tá matando.
      Estou tentando contar a quantidade de itens do carrinho de compras.
       
      Este aqui é o input que aparece a quantidade de itens:
      <td><input type="text" name="prod[<?php echo $result['id']?>]" value="<?php echo $qtdProd = $result['quantity']?>" size="1"  />                          </td>  
      Aparece normalmente a quantidade de itens. Ex: arroz   2  <<< este 2 fica dentro do input, onde posso alterá-lo.
      Minha ideia é mostrar na tela a quantidade total de itens que estão no carrinho.
       
      To usando esse código aqui pra aparecer o número total.... e até funciona:
       
                         <?php                                     if(isset($_SESSION['carrinho'])){                                     $amount = 0;                                     $count = 0;                                     $size = count($_SESSION['carrinho']);                                                                         foreach($_SESSION['carrinho'] as $data){                                     $count++;                                     $amount += $data['quantity'];                                     if($size == $count){                                     echo "TOTAL = $amount";                                     }                                 }                             }                                 ?>  
      O problema é que está exibindo o seguinte erro:
      Warning: Illegal string offset 'quantity' in C:\...\www\sistema\carrinho-de-compra\carrinho.php on line 90
       
      Erro na linha 90, no caso, neste linha aqui: 
          $amount += $data['quantity'];
       
      Daí travei um pouco.
       
      Alguém que poderia dar força ? Tá osso aqui.
      tmj
       
       
    • Por tony_lu
      Ola pessoal, preciso de uma ajuda!
      Tenho uma loja virtual na brasil na web onde esta integrado uma conta do pagseguro. Acontece que a mesma empresa quer uma outra loja, porém na plataforma Tray e com pagamento via Pagseguro! Então estou na duvida, posso integrar a mesma conta pagseguro com o mesmo token para as duas lojas? Não pode dar conflito?
      A plataforma Brasil na Web eu coloco para configurar o token e o email de cadastro do Pagseguro, na loja Tray tem que colocar além do token, cadastrar uma url la dentro do pagseguro, acho que é uma url de retorno. Então meu receio é dar conflito! Qual seria a melhor solução? Aguardo obrigado
    • Por Hamanom007
      Loja Virtual criada em 2008, nosso querido PHP atualizou e fico descontinuada, a loja não funcionava, mas com muito esforço consegui, e agora volto a ter sua função de comprar e de alertar o responsável que fizeram um novo pedido.

      Sendo assim sua funcionalidade básica volto ao normal.

      Porem á erro que não estou conseguindo resolver.
      Os meus estudos sobre a falha aponta para: 
      Atualize o ISC e magic_quotes_runtime_on 
      Mas como disse, são só conteúdos que tenho lido, porem não sei se estou no caminho correto.

      O erro aparecendo é esse:
       
      Strict Standards: Declaration of ISC_FORMFIELD_CHECKBOXSELECT::getFieldRequestValue() should be compatible with ISC_FORMFIELD_BASE::getFieldRequestValue($fieldName = '') in /home2/jajajavai/public_html/loja/lib/formfields/formfield.checkboxselect.php on line 295 Configuração do PHP INI:


       Quem poder me apontar uma direção fico muito agradecido Obrigado a todos.


      Aqui está o arquivo do alerta:

       
      <?php error_reporting(0); class ISC_FORMFIELD_CHECKBOXSELECT extends ISC_FORMFIELD_BASE { /** * Constructor * * Base constructor * * @access public * @param mixed $fieldId The optional form field Id/array * @param bool $copyField If TRUE then this field will copy the field $fieldId EXCEPT for the field ID. Default is FALSE * @return void */ public function __construct($formId, $fieldId='', $copyField=false) { $defaultExtraInfo = array( 'class' => '', 'style' => '', 'options' => array() ); parent::__construct($formId, $defaultExtraInfo, $fieldId, $copyField); } /** * Get the form field description * * Static method will return an array with the form field name and description as the elements * * @access public * @return array The description array */ public static function getDetails() { return array( 'name' => GetLang('FormFieldSingleCheckBoxName'), 'desc' => GetLang('FormFieldSingleCheckBoxDesc'), 'img' => 'checkbox.png', ); } /** * Get the requested (POST or GET) value of a field * * Method will search through all the POST and GET array values are return the field * value if found. Method will the POST and GET arrays in order based on the PHP INI * value 'variables_order' (the GPC order) * * @access public * @return mixed The value of the form field, if found. Empty string if not found */ public function getFieldRequestValue() { $options = parent::getFieldRequestValue(); if (!is_array($options)) { $options = array($options); } $options = array_filter($options); $options = array_values($options); return $options; } /** * Run validation on the server side * * Method will run the validation on the server side (will not run the JS function type) and return * the result * * @access public * @param string &$errmsg The error message if the validation fails * @return bool TRUE if the validation was successful, FALSE if it failed */ public function runValidation(&$errmsg) { if (!parent::runValidation($errmsg)) { return false; } $values = $this->getValue(); if ($values == '') { return true; } /** * Just need to check that all our selected values actually existing within our options array */ if (empty($this->extraInfo['options'])) { return true; } foreach ($values as $value) { if (!in_array($value, $this->extraInfo['options'])) { $errmsg = sprintf(GetLang('CustomFieldsValidationInvalidSelectOption'), $this->label); return false; } } return true; } /** * Set the field value * * Method will set the field value, overriding the existing one * * @access public * @param mixed $value The default value to set * @param bool $setFromDB TRUE to specify that this value is from the DB, FALSE from the request. * Default is FALSE * @param bool $assignRealValue TRUE to filter out any values that is not in the options array, * FALSE to set as is. Default is TRUE */ public function setValue($value, $setFromDB=false, $assignRealValue=true) { if (!is_array($value)) { $value = array($value); $value = array_filter($value); } if ($assignRealValue && !empty($this->extraInfo['options'])) { $filtered = array(); foreach ($value as $key => $val) { $index = array_isearch($val, $this->extraInfo['options']); if ($index !== false) { $filtered[$key] = $this->extraInfo['options'][$index]; } } $value = $filtered; } parent::setValue($value, $setFromDB); } /** * Set the field value by the indexes in the options array * * Method will set the value based upon the indexes in the options array. Every values in the * array $indexes will correspond to the index in the options array * * @access public * @param array $indexes The array of indexes * @return NULL */ public function setValueByIndex($indexes) { if (!is_array($indexes)) { $indexes = array($indexes); } $indexes = array_filter($indexes, 'is_numeric'); if (empty($indexes) || empty($this->extraInfo['options'])) { return; } $newValue = array(); foreach ($indexes as $index) { if (array_key_exists($index, $this->extraInfo['options'])) { $newValue[] = $this->extraInfo['options'][$index]; } } $this->setValue($newValue); } /** * Set the select options * * Method will set the select option for the frontend select box, overriding any perviously set options * * @access public * @param array $options The options array with the key as the options value and the value as the options text * @return bool TRUE if the options were set, FALSE if options were not an array */ public function setOptions($options) { if (!is_array($options)) { return false; } else { $options = array_values($options); } $this->extraInfo['options'] = $options; } /** * Build the frontend HTML for the form field * * Method will build and return the frontend HTML of the loaded form field. The form field must be * loaded before hand * * @access public * @return string The frontend form field HTML if the form field was loaded beforehand, FALSE if not */ public function loadForFrontend() { if (!$this->isLoaded()) { return false; } /** * Make sure that our value is an array */ $this->setValue($this->value); /** * Do we have options (hope so)? */ $GLOBALS['FormFieldCheckBoxes'] = ''; if (!empty($this->extraInfo['options'])) { $id = $this->getFieldId(); $name = $this->getFieldName(); $args = ''; if ($this->extraInfo['class'] !== '') { $args .= 'class="' . isc_html_escape($this->extraInfo['class']) . ' FormFieldOption" '; } else { $args .= 'class="FormFieldOption" '; } if ($this->extraInfo['style'] !== '') { $args .= 'style="' . isc_html_escape($this->extraInfo['style']) . '" '; } $checkboxes = array(); $options = array_values($this->extraInfo['options']); foreach ($this->extraInfo['options'] as $key => $val) { $newId = $id . '_' . $key; $newName = $name . '[' . $key . ']'; $html = '<label for="' . $newId . '">'; $html .= '<input type="checkbox" id="' . $newId . '" name="' . $newName . '" value="' . isc_html_escape($val) . '" ' . $args; /** * Is this one of our values? */ if (in_array($val, $this->value)) { $html .= ' checked="checked"'; } $html .= ' /> ' . isc_html_escape($val) . '</label>'; $checkboxes[] = $html; $key++; } $GLOBALS['FormFieldCheckBoxes'] = implode('<br />', $checkboxes); } $GLOBALS['FormFieldDefaultArgs'] = 'id="' . isc_html_escape($this->getFieldId()) . '" class="FormField"'; return $this->buildForFrontend(); } /** * Build the backend HTML for the form field * * Method will build and return the backend HTML of the form field * * @access public * @return string The backend form field HTML */ public function loadForBackend() { $GLOBALS['FormFieldClass'] = isc_html_escape($this->extraInfo['class']); $GLOBALS['FormFieldStyle'] = isc_html_escape($this->extraInfo['style']); $GLOBALS['FormFieldOptions'] = implode("\n", $this->extraInfo['options']); return parent::buildForBackend(); } /** * Save the field record * * Method will save the field record into the database * * @access protected * @param array $data The field data record set * @param string &$error The referenced variable to store the error in * @return bool TRUE if the field was saved successfully, FALSE if not */ public function saveForBackend($data, &$error) { return parent::saveForBackend($data, $error); } }  
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.