QUAL O ERRO PELO AMOR DE DEUS??? <?php
$dia = date("Y-m-d");
$host = 'localhost';
$usuario = 'user_teste';
$banco = 'clientes_teste';
$senha = '12345';
$conexao = mysql_connect($host, $usuario, $senha) or die (mysql_error());
mysql_select_db($banco);
$query = "SELECT * FROM cliente where nome = 'loja01'";
mysql_query($query);
$resultado = mysql_query($query,$conexao);
$linha = mysql_fetch_array($resultado);
$id = $linha['id'];
$nome = $linha['nome'];
$data_inicio = $linha['data_fim'];
$data_fim = $linha['data_fim'];
$valor = $linha['valor'];
$status = $linha['status'];
$novadata_inicio = substr($data_inicio,8,2) . "/" .substr($data_inicio,5,2) . "/" . substr($data_inicio,0,4);
$novadata_fim = substr($data_fim,8,2) . "/" .substr($data_fim,5,2) . "/" . substr($data_fim,0,4);
echo ("<b>Pagamento da última fatura:</b> $novadata_inicio <br>");
echo ("<b>Vencimento:</b> $novadata_fim <br>");
echo ("<b>Status:</b> $status <br>");
echo ("<table border='0'><tr><td><b>Valor:</b></td>");
echo ("<td>R$ $valor</td><tr><td>");
echo ("<b>Pagar: </b></td><td>");
?>
<?
// Incluindo o arquivo da biblioteca
include('pgs.php');
// Criando um novo carrinho
$pgs=new pgs(array('email_cobranca'=>'mzaidan@gmail.com'));
// Adicionando um produto
$pgs->adicionar(array(
array(
"descricao"=>"Pagamento de fatura anual",
"valor"=>2.00,
"peso"=>0,
"quantidade"=>1,
"id"=>"$id"
),
));
// Mostrando o botão de pagamento
$pgs->mostra(array("img_button"=>'pagseguro.gif'));
echo ("</td></tr></table>");
?>
pgs.php:
<?php class pgs {
var $_itens = array();
var $_config = array ();
var $_cliente = array ();
/**
* pgs
*
* Função de inicialização
* você pode passar os parâmetros padrão alterando as informações padrão como o tipo de moeda ou
* o tipo de carrinho (próprio ou do pagseguro)
*
* Ex:
* <code>
* array (
* 'email_cobranca' => 'raposa@vermelha.com.br',
* 'tipo' => 'CBR',
* 'ref_transacao' => 'A36',
* 'tipo_frete' => 'PAC',
* )
* </code>
*
* @access public
* @param array $args Array associativo contendo as configurações que você deseja alterar
* @return void
*/
function pgs($args = array()) {
if ('array'!=gettype($args)) $args=array();
$default = array(
'email_cobranca' => '',
'tipo' => 'CP',
'moeda' => 'BRL',
);
$this->_config = $args+$default;
}
/**
* error
*
* Retorna a mensagem de erro
*
* @access public
* @return string
*/
function error($msg){
trigger_error($msg);
return $this;
}
/**
* adicionar
*
* Adiciona um item ao carrinho
*
* O elemento adicionado deve ser um array associativo com as seguintes chaves
* id => string com até 100 caracteres
* descricao => string com até 100 caracteres
* quantidade => integer
* valor => integer ou float
* peso => integer (opcional) coloque o peso (em gramas) do produto, caso seja um peso único para todos os
* produtos é preferivel inplantá-lo no new pgs(array('item_peso_1' => 1300))
* frete => integer ou float (opcional) coloque o valor do frete, caso seja um frete único
* para todos os produtos é preferivel inplantá-lo no new pgs(array('item_frete_1' => 30))
*
* @access public
* @param array $item O elemento que será adicionado
* @return object pgs O próprio objeto para que possa ser concatenado a outro comando dele mesmo
*/
function adicionar($item) {
if ('array' !== gettype($item))
return $this->error("Item precisa ser um array.");
if(isset($item[0]) && 'array' === gettype($item[0])){
foreach ($item as $elm) {
if('array' === gettype($elm)) {
$this->adicionar($elm);
}
}
return $this;
}
$tipos=array(
"id" => array(1,"string", '@\w@' ),
"quantidade" => array(1,"string,integer", '@^\d+$@' ),
"valor" => array(1,"double,string,integer", '@^\d*\.?\d+$@'),
"descricao" => array(1,"string", '@\w@' ),
"frete" => array(0,"string,integer", '@^\d+$@' ),
"peso" => array(0,"string,integer", '@^\d+$@' ),
);
foreach($tipos as $elm=>$valor){
list($obrigatorio,$validos,$regexp)=$valor;
if(isset($item[$elm])){
if(strpos($validos,gettype($item[$elm])) === false ||
(gettype($item[$elm]) === "string" && !preg_match($regexp,$item[$elm]))){
return $this->error("Valor invalido passado para $elm.");
}
}elseif($obrigatorio){
return $this->error("O item adicionado precisa conter $elm");
}
}
$this->_itens[] = $item;
return $this;
}
/**
* cliente
*
* Define o cliente a ser inserido no sistema.
* Recebe como parametro um array associativo contendo os dados do cliente.
*
* Ex:
* <code>
* array (
* 'nome' => 'José de Arruda',
* 'cep' => '12345678',
* 'end' => 'Rua dos Tupiniquins',
* 'num' => 37,
* 'compl' => 'apto 507',
* 'bairro' => 'Sto Amaro',
* 'cidade' => 'São Camilo',
* 'uf' => 'SC',
* 'pais' => 'Brasil',
* 'ddd' => '48',
* 'tel' => '55554877',
* 'email' => 'josearruda@teste.com',
* )
* </code>
*
* @access public
* @param array $args Dados sobre o cliente, se não forem passados os dados corretos,
* o pagseguro se encarrega de perguntar os dados ao cliente
* @return void
*/
function cliente($args=array()) {
if ('array'!==gettype($args)) return;
$this->_cliente = $args;
}
/**
*
* mostra
*
* Mostra o formulário de envio de post do PagSeguro
*
* Após configurar o objeto, você pode usar este método para mostrando assim o
* formulário com todos os inputs necessários para enviar ao pagseguro.
*
* <code>
* array (
* 'print' => false, // Cancelará o evento de imprimir na tela, retornando o formulário
* 'open_form' => false, // Não demonstra a tag <form target="pagseguro" ... >
* 'close_form' => false, // Não demonstra a tag </form>
* 'show_submit' => false, // Não mostra o botão de submit (imagem ou um dos 5 do pagseguro)
* 'img_button' => 'imagem.jpg', // Usa a imagem (url) para formar o botão de submit
* 'btn_submit' => 1, // Mostra um dos 5 botões do pagseguro no botão de submit
* )
* </code>
*
* @access public
* @param array $args Array associativo contendo as configurações que você deseja alterar
*/
function mostra ($args=array()) {
$default = array (
'print' => true,
'open_form' => true,
'close_form' => true,
'show_submit' => true,
'img_button' => false,
'bnt_submit' => false,
);
$args = $args+$default;
$_input = ' <input type="hidden" name="%s" value="%s" />';
$_form = array();
if ($args['open_form'])
$_form[] = '<form target="pagseguro" action="https://pagseguro.uol.com.br/security/webpagamentos/webpagto.aspx" method="post">';
foreach ($this->_config as $key=>$value)
$_form[] = sprintf ($_input, $key, $value);
foreach ($this->_cliente as $key=>$value)
$_form[] = sprintf ($_input, "cliente_$key", $value);
$assoc = array (
'id' => 'item_id',
'descricao' => 'item_descr',
'quantidade' => 'item_quant',
);
$i=1;
foreach ($this->_itens as $item) {
foreach ($assoc as $key => $value) {
$sufixo=($this->_config['tipo']=="CBR")?'':'_'.$i;
$_form[] = sprintf ($_input, $value.$sufixo, $item[$key]);
unset($item[$key]);
}
$_form[] = str_replace ('.', '', sprintf (' <input type="hidden" name="%s" value="%.2f" />', "item_valor$sufixo", $item['valor']));
unset($item['valor']);
foreach ($item as $key=>$value)
$_form[] = sprintf ($_input, "item_{$key}{$sufixo}", $value);
$i++;
}
if ($args['show_submit']) {
if ($args['img_button']) {
$_form[] = sprintf(' <input type="image" src="%s" name="submit" alt="Pague com o PagSeguro - é rápido, grátis e seguro!" />', $args['img_button']);
} elseif (@$args['btn_submit']) {
switch ($args['btn_submit']) {
case 1: $btn = 'btnComprarBR.jpg'; break;
case 2: $btn = 'btnPagarBR.jpg'; break;
case 3: $btn = 'btnPagueComBR.jpg'; break;
case 4: $btn = 'btnComprar.jpg'; break;
case 5: $btn = 'btnPagar.jpg'; break;
default: $btn = 'btnComprarBR.jpg';
}
$_form[] = sprintf (' <input type="image" src="https://pagseguro.uol.com.br/Security/Imagens/%s" name="submit" alt="Pague com o PagSeguro - é rápido, grátis e seguro!" />', $btn);
} else {
$_form[] = ' <input type="submit" value="Pague com o PagSeguro" />';
}
}
if($args['close_form']) $_form[] = '</form>';
$return = implode("\n", $_form);
if ($args['print']) print ($return);
return $return;
}
}
?>
retorno.php:
<?php if (!defined('TOKEN')) define ('TOKEN', '8ACB5ADADEAD484AB8C1A9F993AE2022');
class RetornoPagSeguro {
/**
* _preparaDados
*
* Prepara os dados vindos do post e converte-os para url, adicionando
* o token do usuario quando necessario.
*
function _preparaDados($post, $confirmacao=true) {
if ('array' !== gettype($post)) $post=array();
if ($confirmacao) {
$post['Comando'] = 'validar';
$post['Token'] = TOKEN;
}
$retorno=array();
foreach ($post as $key=>$value){
if('string'!==gettype($value)) $post[$key]='';
$value=urlencode(stripslashes($value));
$retorno[]="{$key}={$value}";
}
return implode('&', $retorno);
}
function _tipoEnvio() {
global $_retPagSeguroErrNo, $_retPagSeguroErrStr;
if (function_exists('curl_exec'))
return array('curl', 'https://pagseguro.uol.com.br/Security/NPI/Default.aspx');
elseif ((PHP_VERSION >= 4.3) && ($fp = @fsockopen('ssl://pagseguro.uol.com.br', 443, $_retPagSeguroErrNo, $_retPagSeguroErrStr, 30)))
return array('fsocket', '/Security/NPI/Default.aspx', $fp);
elseif ($fp = @fsockopen('pagseguro.uol.com.br', 80, $_retPagSeguroErrNo, $_retPagSeguroErrStr, 30))
return array('fsocket', '/Security/NPI/Default.aspx', $fp);
return array ('', '');
}
function not_null($value) {
if (is_array($value)) {
if (sizeof($value) > 0) {
return true;
} else {
return false;
}
} else {
if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) {
return true;
} else {
return false;
}
}
}
function verifica($post, $tipoEnvio=false) {
global $_retPagSeguroErrNo, $_retPagSeguroErrStr;
if ('array' !== gettype($tipoEnvio))
$tipoEnvio = RetornoPagSeguro::_tipoEnvio();
$spost=RetornoPagSeguro::_preparaDados($post);
if (!in_array($tipoEnvio[0], array('curl', 'fsocket')))
return false;
$confirma = false;
if ($tipoEnvio[0] === 'curl') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tipoEnvio[1]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $spost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($ch);
if (!RetornoPagSeguro::not_null($resp)) {
curl_setopt($ch, CURLOPT_URL, $tipoEnvio[1]);
$resp = curl_exec($ch);
}
curl_close($ch);
$confirma = (strcmp ($resp, 'VERIFICADO') == 0);
} elseif ($tipoEnvio[0] === 'fsocket') {
if (!$tipoEnvio[2]) {
die ("{$_retPagSeguroErrStr} ($_retPagSeguroErrNo)");
} else {
$cabecalho = "POST {$tipoEnvio[1]} HTTP/1.0\r\n";
$cabecalho .= "Content-Type: application/x-www-form-urlencoded\r\n";
$cabecalho .= "Content-Length: " . strlen($spost) . "\r\n\r\n";
$resp = '';
fwrite ($tipoEnvio[2], "{$cabecalho}{$spost}");
while (!feof($tipoEnvio[2])) {
$resp = fgets ($tipoEnvio[2], 1024);
if (strcmp ($resp, 'VERIFICADO') == 0) {
$confirma = (strcmp ($resp, 'VERIFICADO') == 0);
$confirma=true;
break;
}
}
fclose ($tipoEnvio[2]);
}
}
if ($confirma && function_exists('retorno_automatico')) {
$itens = array (
'VendedorEmail', 'TransacaoID', 'Referencia', 'TipoFrete',
'ValorFrete', 'Anotacao', 'DataTransacao', 'TipoPagamento',
'StatusTransacao', 'CliNome', 'CliEmail', 'CliEndereco',
'CliNumero', 'CliComplemento', 'CliBairro', 'CliCidade',
'CliEstado', 'CliCEP', 'CliTelefone', 'NumItens',
);
foreach ($itens as $item) {
if (!isset($post[$item])) $post[$item] = '';
if ($item=='ValorFrete') $post[$item] = str_replace(',', '.', $post[$item]);
}
$produtos = array ();
for ($i=1;isset($post["ProdID_{$i}"]);$i++) {
$produtos[] = array (
'ProdID' => $post["ProdID_{$i}"],
'ProdDescricao' => $post["ProdDescricao_{$i}"],
'ProdValor' => (double) (str_replace(',', '.', $post["ProdValor_{$i}"])),
'ProdQuantidade' => $post["ProdQuantidade_{$i}"],
'ProdFrete' => (double) (str_replace(',', '.', $post["ProdFrete_{$i}"])),
'ProdExtras' => (double) (str_replace(',', '.', $post["ProdExtras_{$i}"])),
);
}
retorno_automatico (
$post['VendedorEmail'], $post['TransacaoID'], $post['Referencia'], $post['TipoFrete'],
$post['ValorFrete'], $post['Anotacao'], $post['DataTransacao'], $post['TipoPagamento'],
$post['StatusTransacao'], $post['CliNome'], $post['CliEmail'], $post['CliEndereco'],
$post['CliNumero'], $post['CliComplemento'], $post['CliBairro'], $post['CliCidade'],
$post['CliEstado'], $post['CliCEP'], $post['CliTelefone'], $produtos, $post['NumItens']
);
}
return $confirma;
}
}
if ($_POST) {
RetornoPagSeguro::verifica($_POST);
die();
}
?> Ele conecta tudo certo, eu recebo os valores tudo normal (pagamento confirmado) Mas queria que atualizadasse automaticamente o status, o que eu teria que fazer??? Tipo, como eu sei que já foi confirmado o pagamento para liberar no banco de dados? Como seria se fosse por cartão de crédito, onde demora mais um pouco para liberar? Por favor me ajudem!!