/[drupal]/contributions/modules/uc_pagseguro/uc_pagseguro.module
ViewVC logotype

Contents of /contributions/modules/uc_pagseguro/uc_pagseguro.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.5 - (show annotations) (download) (as text)
Fri Sep 18 12:06:37 2009 UTC (2 months, 1 week ago) by pedrofaria
Branch: MAIN
CVS Tags: HEAD
Branch point for: DRUPAL-6--1
Changes since 1.4: +228 -171 lines
File MIME type: text/x-php
Starting a new development branch
1 <?php
2 // $Id: uc_pagseguro.module,v 1.2 2008/12/04 14:09:41 pedrofaria Exp $
3
4 /**
5 * @file
6 * Based on 2Checkout module
7 * Integrates PagSeguro redirected payment service.
8 * Integra o serviço de pagamento do PagSeguro
9 *
10 * Development sponsored by Diego Teixeira. Beta by Marcus VBP.
11 * New version by Marcelo IH aka Vuds.
12 */
13
14 /*******************************************************************************
15 * Hook Functions (Drupal)
16 ******************************************************************************/
17
18 /**
19 * Implementation of hook_menu().
20 */
21 function uc_pagseguro_menu() {
22
23 $items['cart/pagseguro/complete'] = array(
24 'title' => 'Pedido Completo',
25 'page callback' => 'uc_pagseguro_complete',
26 'access callback' => TRUE,
27 'type' => MENU_CALLBACK,
28 );
29
30 return $items;
31 }
32
33 /**
34 * Implementation of hook_form_alter().
35 */
36 function uc_pagseguro_form_alter(&$form, $form_state, $form_id) {
37
38 switch ( $form_id ) {
39 case 'uc_payment_methods_form':
40 if ( variable_get('uc_pagseguro_use_sandbox', 0) )
41 drupal_set_message(t('IMPORTANTE: Usando endereço de teste <strong>!url</strong> para pagamentos via PagSeguro', array('!url' => variable_get('uc_pagseguro_sandbox_url', ''))),
42 'error');
43 break;
44
45 case 'uc_cart_checkout_review_form':
46 if (($order_id = intval($_SESSION['cart_order'])) > 0) {
47 $order = uc_order_load($order_id);
48
49 if ($order->payment_method == 'pagseguro') {
50 drupal_add_css(drupal_get_path('module', 'uc_pagseguro') . '/uc_pagseguro.css');
51
52 unset($form['submit']);
53 $form['#prefix'] = '<table id="review-pagseguro"><tr><td>';
54 $form['#suffix'] = '</td><td>'. drupal_get_form('uc_pagseguro_form', $order) .'</td></tr></table>';
55 }
56 }
57 break;
58
59 // hook_form_alter to keep the delivery information aligned with what UOL needs.
60 case 'uc_cart_checkout_form':
61 drupal_add_css(drupal_get_path('module', 'uc_pagseguro') . '/uc_pagseguro.css');
62
63 $form['panes']['billing']['billing_street1']['#description'] = t('Formato: Rua XYZ, 9999 - Sem n&uacute;mero, use: S/N');
64 $form['panes']['billing']['billing_street1']['#validate'] = array('_uc_pagseguro_validate_address' => array());
65 $form['panes']['billing']['billing_street2']['#description'] = t('Formato: Ap. 12, Bairro - Ou somente o Bairro');
66 $form['panes']['billing']['billing_street2']['#validate'] = array('_uc_pagseguro_validate_district' => array());
67 $form['panes']['billing']['billing_postal_code']['#description'] = t('Formato: Somente N&uacute;meros');
68 $form['panes']['billing']['billing_postal_code']['#validate'] = array('_uc_pagseguro_validate_postal_code' => array());
69 $form['panes']['billing']['billing_postal_code']['#maxlength'] = '8';
70 $form['panes']['billing']['billing_phone']['#description'] = t('Formato: (99) 1234-5678');
71 $form['panes']['billing']['billing_phone']['#validate'] = array('_uc_pagseguro_validate_phone' => array());
72 $form['panes']['billing']['billing_phone']['#maxlength'] = '14';
73
74 $form['panes']['delivery']['delivery_street1']['#description'] = t('Formato: Rua XYZ, 9999 - Sem n&uacute;mero, use: S/N');
75 $form['panes']['delivery']['delivery_street1']['#validate'] = array('_uc_pagseguro_validate_address' => array());
76 $form['panes']['delivery']['delivery_street2']['#description'] = t('Formato: Ap. 12, Bairro - Ou somente o bairro');
77 $form['panes']['delivery']['delivery_street2']['#validate'] = array('_uc_pagseguro_validate_district' => array());
78 $form['panes']['delivery']['delivery_postal_code']['#description'] = t('Formato: Somente N&uacute;meros');
79 $form['panes']['delivery']['delivery_postal_code']['#validate'] = array('_uc_pagseguro_validate_postal_code' => array());
80 $form['panes']['delivery']['delivery_postal_code']['#maxlength'] = '8';
81 $form['panes']['delivery']['delivery_phone']['#description'] = t('Formato: (99) 1234-5678');
82 $form['panes']['delivery']['delivery_phone']['#validate'] = array('_uc_pagseguro_validate_phone' => array());
83 $form['panes']['delivery']['delivery_phone']['#maxlength'] = '14';
84 break;
85 }
86 }
87
88 /*******************************************************************************
89 * Hook Functions (Ubercart)
90 ******************************************************************************/
91
92 //-------------------------- Implementation of hook_uc_message(). - Texto padr&atilde;o das instru&ccedil;&otilde;es/mensagem do módulo
93
94 function uc_pagseguro_uc_message() {
95 $messages['pagseguro_instructions'] = t('O PagSeguro &eacute; um m&eacute;todo de pagamentos fornecido pelo UOL, que permite o pagamento seguro ' .
96 'atrav&eacute;s de cart&atilde;o de cr&eacute;dito, transfer&ecirc;ncia e boleto banc&aacute;rio. ' .
97 '<strong>Nota: o pagamento parcelado em cart&atilde;o de cr&eacute;dito está sujeito a juros estipulados pelo PagSeguro.');
98 return $messages;
99 }
100
101 /**
102 * Implementation of hook_payment_method().
103 */
104 function uc_pagseguro_payment_method() {
105 $path = base_path() . drupal_get_path('module', 'uc_pagseguro');
106 $title = variable_get('uc_pagseguro_method_title', t('PagSeguro'));
107
108 $methods[] = array(
109 'id' => 'pagseguro',
110 'name' => t('PagSeguro'),
111 'title' => $title,
112 'desc' => t('Pagamento por PagSeguro.'),
113 'callback' => 'uc_payment_method_pagseguro',
114 'weight' => 3,
115 'checkout' => TRUE,
116 'backend' => TRUE,
117 'no_gateway'=> TRUE,
118 );
119
120 return $methods;
121 }
122
123
124 /*******************************************************************************
125 * Callback Functions, Forms, and Tables
126 ******************************************************************************/
127
128 /**
129 * Callback for pagseguro payment method settings.
130 */
131 function uc_payment_method_pagseguro($op, &$arg1) {
132 switch ($op) {
133 case 'cart-details':
134 $details = variable_get('uc_pagseguro_instructions', uc_get_message('pagseguro_instructions'));
135 return $details;
136
137 case 'cart-process':
138 $_SESSION['pay_method'] = $_POST['pay_method'];
139 return;
140
141 case 'settings':
142 $form['uc_pagseguro_email_pagseguro'] = array(
143 '#type' => 'textfield',
144 '#title' => t('Email cadastrado no PagSeguro'),
145 '#default_value' => variable_get('uc_pagseguro_email_pagseguro', ''),
146 '#size' => 50,
147 '#maxlength' => 50,
148 '#description' => t('Informe o e-mail que foi utilizado na sua conta do PagSeguro.'),
149 '#required' => TRUE,
150 );
151
152 $form['uc_pagseguro_token_pagseguro'] = array(
153 '#type' => 'textfield',
154 '#title' => t('Token gerado pelo PagSeguro'),
155 '#default_value' => variable_get('uc_pagseguro_token_pagseguro', ''),
156 '#size' => 50,
157 '#maxlength' => 50,
158 '#description' => t('Informe o token gerado para sua conta no PagSeguro. ' .
159 '<strong>Caso utilize esta op&ccedil;&atilde;o, n&atilde;o esque&ccedil;a de configurar o PagSeguro para utilizar o Retorno Autom&aacute;tico de Dados.</strong>'),
160 '#required' => FALSE,
161 );
162
163 $form['uc_pagseguro_frete'] = array(
164 '#type' => 'checkbox',
165 '#title' => t('C&aacute;lculo de frete pelo Ubercart'),
166 '#default_value' => variable_get('uc_pagseguro_frete', '1'),
167 '#description' => t('Marque para o c&aacute;lculo ser realizado no UberCart. Caso contr&aacute;rio, o c&aacute;lculo ser&aacute; feito pelo PagSeguro. ' .
168 '<strong>N&atilde;o esque&ccedil;a de configurar o PagSeguro de acordo com esta op&ccedil;&atilde;o.</strong>'),
169 '#required' => FALSE,
170 );
171
172 $form['uc_pagseguro_checkout_button'] = array(
173 '#type' => 'textfield',
174 '#title' => t('Texto do bot&atilde;o de revis&atilde;o do pedido '),
175 '#description' => t('Informe um texto especial para o bot&atilde;o de enviar na p&aacute;gina de revis&atilde;o do pedido.'),
176 '#default_value' => variable_get('uc_pagseguro_checkout_button', t('Pagar no PagSeguro')),
177 );
178
179 $form['uc_pagseguro_use_sandbox'] = array(
180 '#type' => 'checkbox',
181 '#title' => t('Usar endereço alternativo para testes'),
182 '#description' => t('Marque esta opção para utilizar um endereço alternativo durante os testes de sua instalação, ao invés do endereço oficial do PagSeguro. Veja em <a href="http://visie.com.br/pagseguro/ambientetestes.php">&quot;Ambiente de testes do PagSeguro&quot;</a> como criar seu próprio servidor de testes. Se esta opção estiver desmarcada, o pagamento utilizará o endereço oficial do PagSeguro <strong>https://pagseguro.uol.com.br</strong>.'),
183 '#default_value' => variable_get('uc_pagseguro_use_sandbox', FALSE)
184 );
185
186
187 $form['uc_pagseguro_sandbox_url'] = array(
188 '#type' => 'textfield',
189 '#title' => t('Endereço alternativo para testes'),
190 '#description' => t('Informe o endereço de testes que deverá ser utilizado se a opção "Usar endereço alternativos para testes" acima estiver marcada. Informe apenas o protocolo e nome do <em>host</em>, sem barras no final. Por exemplo: <strong>http://pagseguro.exemplo.com.br<strong>'),
191 '#default_value' => variable_get('uc_pagseguro_sandbox_url', '')
192 );
193
194 return $form;
195 }
196 }
197
198 function _uc_pagseguro_url()
199 {
200 if ( variable_get('uc_pagseguro_use_sandbox', FALSE) )
201 {
202 $url = variable_get('uc_pagseguro_sandbox_url', '');
203 if ( !$url )
204 {
205 watchdog('uc_pagseguro',
206 'Sandbox habilitado mas endereco nao configurado',
207 NULL,
208 WATCHDOG_ERROR);
209 }
210 }
211 else
212 $url = 'https://pagseguro.uol.com.br';
213
214 return $url;
215 }
216
217 // Form to build the submission to pagseguro.com.
218 function uc_pagseguro_form($form_id, $order) {
219 $endereco = $order->billing_street1 ? _uc_pagseguro_extract_address($order->billing_street1) : array();
220 $telefone = $order->billing_phone ? _uc_pagseguro_extract_phone($order->billing_phone) : array();
221 $complementoarray = _uc_pagseguro_extract_district($order->billing_street2);
222 $complemento1 = current ($complementoarray);
223 $complemento2 = next ($complementoarray);
224 $frete = variable_get('uc_pagseguro_frete', '1');
225 $country = uc_get_country_data(array('country_id' => $order->billing_country));
226 if ($country === FALSE) {
227 $country = array(0 => array('country_iso_code_3' => 'USA'));
228 }
229
230 $data = array(
231 'email_cobranca'=> variable_get('uc_pagseguro_email_pagseguro', ''),
232 'tipo' => 'CP',
233 'moeda' => 'BRL',
234 'tipo_frete' => 'SD',
235 'cliente_nome' => _uc_pagseguro_remove_accents($order->billing_first_name) . ' '
236 . _uc_pagseguro_remove_accents($order->billing_last_name),
237 'cliente_end' => _uc_pagseguro_remove_accents(current($endereco)),
238 'cliente_num' => next($endereco),
239 'cliente_compl' => $complemento2 ? _uc_pagseguro_remove_accents($complemento1) : '',
240 'cliente_bairro' => $complemento2 ? _uc_pagseguro_remove_accents($complemento2) : _uc_pagseguro_remove_accents($complemento1),
241 'cliente_ddd' => current($telefone),
242 'cliente_tel' => next($telefone),
243 'cliente_email' => substr($order->primary_email, 0, 200),
244 'cliente_cidade' => _uc_pagseguro_remove_accents(substr($order->billing_city, 0, 100)),
245 'cliente_uf' => uc_get_zone_code($order->billing_zone),
246 'cliente_cep' => substr($order->billing_postal_code, 0, 8),
247 'cliente_pais' => $country[0]['country_iso_code_3'],
248 'ref_transacao' => $order->order_id
249 );
250
251 // PagSeguro only accepts shipping per item, so let's divide the total value between the itens
252 $shipping = 0;
253 foreach ($order->line_items as $item) {
254 if ($item['type'] == 'shipping') {
255 $shipping += $item['amount'];
256 }
257 }
258 $shippingunit = round(($shipping / count ($order->products)), 2);
259 $sumshipping = 0;
260
261 $i = 0;
262 foreach ($order->products as $product) {
263 $i++;
264 // Since PagSeguro don't accept the same products in different lines and Ubercart does,
265 // we have to vary the id with order_product_id
266 $data['item_id_' . $i] = $product->nid . '-' . $product->order_product_id;
267 $data['item_descr_' . $i] = _uc_pagseguro_remove_accents($product->title);
268 $data['item_quant_' . $i] = $product->qty;
269 $data['item_valor_' . $i] = $product->price * 100;
270 if ($frete) {
271 $data['item_frete_' . $i] = $shippingunit * 100;
272 $sumshipping += $shippingunit * 100;
273 }
274 else {
275 $data['item_peso_' . $i] = $product->weight * 100;
276 }
277 };
278 // Giving back the possible shipping value difference to the last item
279 if ($frete) {
280 $diffshipping = ($shipping * 100) - $sumshipping;
281 $data['item_frete_' . $i] += $diffshipping;
282 }
283
284 $form['#action'] = _uc_pagseguro_url() . '/security/webpagamentos/webpagto.aspx';
285 $form['#name'] = 'pagseguro';
286 $form['#target'] = 'pagseguro';
287
288 foreach ($data as $name => $value) {
289 $form[$name] = array('#type' => 'hidden', '#value' => $value);
290 }
291
292 $form['submit'] = array(
293 '#type' => 'submit',
294 '#value' => variable_get('uc_pagseguro_checkout_button', t('Submit Order')),
295 );
296
297 //Saving Order_ID for use after validating
298 $_SESSION['PagSeguro_OrderID'] = $order->order_id;
299 return $form;
300 }
301
302 /**
303 *
304 *Function to complete the process for payment and return user to first page
305 *
306 **/
307 function uc_pagseguro_complete() {
308 // PagSeguro calls this function twice; First for bring $_POST and verify Token;
309 if ( $_SERVER['REQUEST_METHOD'] != 'POST' ) {
310 // Mostra página para o usuário
311 $order = uc_order_load($_SESSION['PagSeguro_OrderID']);
312 unset ($_SESSION['PagSeguro_OrderID']);
313
314 if (uc_order_status_data($order->order_status, 'state') == 'in_checkout') {
315 drupal_set_message(t('Seu pedido est&aacute; sendo processado entre o sistema e o PagSeguro. ' .
316 'Caso tenha optado por pagamento com Boleto, seu pedido ser&aacute; executado somente ap&oacute;s o pagamento do mesmo.'));
317 }
318 else {
319 drupal_set_message('Transa&ccedil;&atilde;o confirmada com o PagSeguro.', 'admin');
320 if (uc_order_status_data($order->order_status, 'state') == 'pending') {
321 drupal_set_message('Aguardando confirma&ccedil;&atilde;o de pagamento com o PagSeguro.', 'admin');
322 }
323 }
324 $cart_id = uc_cart_get_id();
325 uc_cart_empty($cart_id);
326 drupal_goto('<front>');
327 }
328
329 // Antes de fazer qualquer coisa, verifica a confirmacao junto ao PagSeguro
330 $token = variable_get('uc_pagseguro_token_pagseguro', '');
331 if ( !$token )
332 {
333 watchdog('uc_pagseguro',
334 'A verificacao da confirmação do PagSeguro não pôde ser feita porque o token de segurança não está configurado',
335 NULL,
336 WATCHDOG_NOTICE);
337 exit();
338 }
339
340 //if $token is not empty, let's confirm transaction with PagSeguro
341 $retorno = _uc_pagseguro_verify($token);
342
343 if ( $retorno == 'OK' || $retorno == 'FALSO' )
344 {
345 $order = uc_order_load($_POST['Referencia']);
346 if ( !$order )
347 {
348 watchdog('uc_pagseguro',
349 'Nao foi possivel carregar pedido a partir de "@ref"',
350 array('@ref' => $_POST['Referencia']),
351 WATCHDOG_NOTICE);
352 exit();
353 }
354 }
355
356 switch ($retorno) {
357 case 'OK':
358 //uc_order_comment_save($order->order_id, 0, t('Transa&ccedil;&atilde;o confirmada com o PagSeguro'), 'admin');
359 break;
360 case 'CONNECTFAIL':
361 uc_order_comment_save($order->order_id, 0, t('Transa&ccedil;&atilde;o n&atilde;o foi confirmada com o PagSeguro: Problemas de conex&atilde;o.'), 'admin');
362 break;
363 case 'FALSO':
364 default:
365 watchdog('uc_pagseguro',
366 'Transação "@trans" não confirmada pelo PagSeguro',
367 array('@trans'=> $_POST['Referencia']),
368 WATCHDOG_NOTICE);
369 exit();
370 }
371
372 $order = uc_order_load($_POST['Referencia']);
373
374
375 if ( uc_order_status_data($order->order_status, 'state') != 'in_checkout') {
376 uc_order_comment_save($order->order_id, 0, t('Recebida confirmação do PagSeguro para pedido que não está com status de checkout.'), 'admin');
377 exit();
378 }
379
380
381
382 $order->first_name = _uc_pagseguro_strstr($_POST['CliNome'], ' ', TRUE);
383 $order->last_name = _uc_pagseguro_strstr($_POST['CliNome'], ' ');
384 $order->billing_street1 = $_POST['CliEndereco'] . ', ' . $_POST['CliNumero'] . ' - ' .$_POST['CliBairro'];
385 $order->billing_street2 = $_POST['CliComplemento'];
386 $order->city = $_POST['CliCidade'];
387 $order->billing_postal_code = substr($_POST['CliCEP'], 0, 5) . '-' . substr($_POST['CliCEP'], -3);
388 $order->billing_phone = '(' . substr($_POST['CliTelefone'], 0, 2) . ') ' . substr($_POST['CliTelefone'], -8);
389 $order->billing_zone = $_POST['CliEstado'];
390
391 $country_id = db_result(db_query("SELECT country_id FROM {uc_countries} WHERE country_name LIKE '%s'", $_POST['CliPais']));
392 if (!empty($country_id)) {
393 $order->billing_country = $country_id;
394 }
395
396 if (strtolower($_POST['CliEmail']) !== strtolower($order->primary_email)) {
397 uc_order_comment_save($order->order_id, 0, t('Obs.: cliente usou um e-mail diferente durante pagamento no PagSeguro: @email', array('@email' => $_POST['CliEmail'])), 'admin');
398 }
399
400 $total = 0;
401 $i = 1;
402 while ( isset($_POST['ProdId_' . $i]) ) {
403 $total += (_uc_pagseguro_parseval($_POST['ProdValor_' . $i])
404 + _uc_pagseguro_parseval($_POST['ProdFrete_' . $i])
405 + _uc_pagseguro_parseval($_POST['ProdExtras_' . $i]))
406 * intval($_POST['ProdQuantidade_' . $i]);
407 $i++;
408 };
409
410 uc_order_comment_save($order->order_id, 0, t('Recebido status "@status" ("@type") do PagSeguro',
411 array('@type' => $_POST['TipoPagamento'],
412 '@status' => $_POST['StatusTransacao'])),
413 'admin');
414
415 switch (strtolower($_POST['StatusTransacao'])) {
416 case 'completo':
417 $comment = t('Pagamento confirmado pelo PagSeguro ("@type"), transa&ccedil;&atilde;oID PagSeguro #@order, total pago R$ !total.',
418 array('@type' => $_POST['TipoPagamento'],
419 '@order' => $_POST['TransacaoID'],
420 '!total'=> number_format($total, 2, ",", ".")));
421 uc_payment_enter($order->order_id, 'pagseguro', $total, 0, NULL, $comment);
422 uc_cart_complete_sale($order);
423 break;
424
425 case 'aguardando pagto':
426 uc_order_update_status($order->order_id, 'pending');
427 break;
428 case 'aprovado':
429 uc_order_update_status($order->order_id, 'payment_received');
430 break;
431 case 'em análise':
432 uc_order_update_status($order->order_id, 'processing');
433 break;
434 case 'cancelado':
435 uc_order_update_status($order->order_id, 'canceled');
436 break;
437 }
438
439 uc_order_save($order);
440 exit();
441 }
442
443 /*******************************************************************************
444 * Support Functions (Ubercart / PagSeguro)
445 ******************************************************************************/
446 // funcao para remover acentos. pego no modulo accents: http://drupal.org/project/accents
447
448 function _uc_pagseguro_remove_accents($string) {
449
450
451 $chars = array(
452 // Decompositions for Latin-1 Supplement
453 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
454 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
455 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
456 chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
457 chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
458 chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
459 chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
460 chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
461 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
462 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
463 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
464 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
465 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
466 chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
467 chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
468 chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
469 chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
470 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
471 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
472 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
473 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
474 chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
475 chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
476 chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
477 chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
478 chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
479 chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
480 chr(195).chr(191) => 'y',
481 // Decompositions for Latin Extended-A
482 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
483 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
484 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
485 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
486 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
487 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
488 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
489 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
490 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
491 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
492 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
493 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
494 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
495 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
496 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
497 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
498 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
499 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
500 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
501 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
502 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
503 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
504 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
505 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
506 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
507 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
508 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
509 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
510 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
511 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
512 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
513 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
514 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
515 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
516 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
517 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
518 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
519 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
520 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
521 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
522 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
523 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
524 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
525 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
526 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
527 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
528 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
529 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
530 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
531 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
532 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
533 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
534 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
535 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
536 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
537 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
538 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
539 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
540 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
541 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
542 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
543 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
544 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
545 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
546 // Euro Sign
547 chr(226).chr(130).chr(172) => 'E'
548 );
549 $string = strtr($string, $chars);
550 return $string;
551 }
552
553 // Not guaranteed that system is using PHP 5.3, so let's use our own strstr() function
554 function _uc_pagseguro_strstr($haystack, $needle, $before_needle=FALSE) {
555 //Find position of $needle or abort
556 if (($pos=strpos($haystack,$needle))===FALSE) {
557 return FALSE;
558 }
559 if($before_needle) {
560 return substr($haystack,0,$pos);
561 }
562 else {
563 return substr($haystack,$pos+strlen($needle));
564 }
565 }
566
567 function _uc_pagseguro_validate_address(&$element) {
568 if ($element['#value'] != '') {
569 if (!_uc_pagseguro_extract_address($element['#value'])) {
570 form_error($element, t('Endere&ccedil;o em formato n&atilde;o validado. Por favor, verifique o campo marcado.'));
571 }
572 }
573 }
574
575 function _uc_pagseguro_extract_address($address) {
576 // Let's assume that the last part of the address is always the number, in brazilian format
577 // Testing for: Rua X, 999 OR Rua X,999
578 $numero = trim(_uc_pagseguro_strstr($address, ','));
579 if (is_numeric ($numero) || (strtolower($numero) == 's/n')) {
580 return array(trim(_uc_pagseguro_strstr($address, ',', TRUE)), $numero);
581 }
582 else {
583 // TO DO: Study a way to accept address without comma
584 return array();
585 }
586 }
587
588 function _uc_pagseguro_validate_district(&$element) {
589 if ($element['#value'] != '') {
590 if (!_uc_pagseguro_extract_district($element['#value'])) {
591 form_error($element, t('Complemento e Bairro em formato n&atilde;o validado. Por favor, verifique o campo marcado.'));
592 }
593 }
594 }
595
596 function _uc_pagseguro_extract_district($street2) {
597 // Let's assume that the last part of the address is always the number, in brazilian format
598 // Testing for: Rua X, 999 OR Rua X,999
599 $bairro = trim(_uc_pagseguro_strstr($street2, ','));
600 if (! $bairro) {
601 return array (trim ($street2));
602 }
603 else {
604 return array(trim(_uc_pagseguro_strstr($street2, ',', TRUE)), $bairro);
605 }
606 }
607
608
609 function _uc_pagseguro_validate_postal_code(&$element) {
610 if ($element['#value'] != '') {
611 if (! is_numeric (trim ($element['#value']))) {
612 form_error($element, t('CEP em formato n&atilde;o validado. Por favor, verifique o campo marcado.'));
613 }
614 }
615 }
616
617 function _uc_pagseguro_validate_phone(&$element) {
618 if ($element['#value'] != '') {
619 if (!_uc_pagseguro_extract_phone($element['#value'])) {
620 form_error($element, t('Telefone em formato n&atilde;o validado. Por favor, verifique o campo marcado.'));
621 }
622 }
623 }
624
625 function _uc_pagseguro_extract_phone($phone) {
626 // Let's assume brazilian format also for telephone number
627 // Testing for: (99) 1234-5678 OR (99)12345678
628 // Testing first coding area
629 $stripddd = _uc_pagseguro_strstr($phone, ')', TRUE);
630 if( $stripddd !== FALSE ) {
631 $ddd = substr($stripddd, 1, 2);
632 if (! is_numeric ($ddd)) {
633 return FALSE;
634 }
635 // Now testing telephone number
636 elseif (! is_numeric ($numero = (trim ( str_replace ('-', '', _uc_pagseguro_strstr($phone, ')')))))) {
637 return FALSE;
638 }
639 else {
640 return array($ddd, $numero);
641 }
642 }
643 else {
644 return FALSE;
645 }
646 }
647
648 function _uc_pagseguro_verify($token) {
649 // RECEBE O POST ENVIADO PELA PagSeguro E ADICIONA OS VALORES PARA VALIDAÇÃO DOS DADOS
650 $PagSeguro = 'Comando=validar';
651 $PagSeguro .= '&Token=' . $token;
652 $Cabecalho = '';
653 $confirma = '';
654
655 foreach ($_POST as $key => $value) {
656 $value = urlencode(stripslashes($value));
657 $PagSeguro .= "&$key=$value";
658 }
659
660 $r = drupal_http_request(_uc_pagseguro_url() . '/Security/NPI/Default.aspx',
661 array(), 'POST', $PagSeguro);
662 if ( $r->code != 200 )
663 return 'CONNECTFAIL';
664
665 $resp = $r->data;
666
667 /*
668 if (function_exists('curl_exec')) {
669 $curl = true;
670 }
671 elseif ((PHP_VERSION >= 4.3) && ($fp = @fsockopen ('ssl://pagseguro.uol.com.br', 443, $errno, $errstr, 30))) {
672 $fsocket = true;
673 }
674 elseif ($fp = @fsockopen('pagseguro.uol.com.br', 80, $errno, $errstr, 30)) {
675 $fsocket = true;
676 }
677
678 // ENVIA DE VOLTA PARA A PagSeguro OS DADOS PARA VALIDAÇÃO
679 if ($curl == true) {
680 $confirma = FALSE;
681 $ch = curl_init();
682 $resp = '';
683
684 curl_setopt($ch, CURLOPT_URL, 'https://pagseguro.uol.com.br/Security/NPI/Default.aspx');
685 curl_setopt($ch, CURLOPT_POST, true);
686 curl_setopt($ch, CURLOPT_POSTFIELDS, $PagSeguro);
687 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
688 curl_setopt($ch, CURLOPT_HEADER, false);
689 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
690 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
691 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
692
693 $resp = curl_exec($ch);
694 if (!tep_not_null($resp)) {
695 curl_setopt($ch, CURLOPT_URL, 'http://pagseguro.uol.com.br/Security/NPI/Default.aspx');
696 $resp = curl_exec($ch);
697 }
698
699 curl_close($ch);
700 }
701 elseif ($fsocket == true) {
702 $Cabecalho = 'POST /Security/NPI/Default.aspx HTTP/1.0\r\n';
703 $Cabecalho .= 'Content-Type: application/x-www-form-urlencoded\r\n';
704 $Cabecalho .= 'Content-Length: ' . strlen($PagSeguro) . '\r\n\r\n';
705
706 if ($fp || $errno>0) {
707 fputs ($fp, $Cabecalho . $PagSeguro);
708 $confirma = false;
709 $resp = '';
710 while (!feof($fp)) {
711 $res = @fgets ($fp, 1024);
712 $resp .= $res;
713 // Verifica se o status da transação está VERIFICADO
714 if (strcmp ($res, 'VERIFICADO') == 0) {
715 $confirma=true;
716 $resp = $res;
717 break;
718 }
719 }
720 fclose ($fp);
721 }
722 else {
723 uc_order_comment_save($orderid, 0, t('Problemas de comunica&ccedil;&atilde;o com o PagSeguro para verifica&ccedil;&atilde;o: !erro',
724 array( '!erro' => $errstr . '(' . $errno .')')), 'admin');
725 $confirma = 'CONNECTFAIL';
726 }
727 }
728 */
729 switch ($resp) {
730 case 'VERIFICADO':
731 $confirma = 'OK';
732 break;
733 case 'FALSO':
734 $confirma = 'FALSO';
735 break;
736 default:
737 $confirma = 'CONNECTFAIL';
738 break;
739 }
740
741 return $confirma;
742 }
743
744 function _uc_pagseguro_parseval($s)
745 {
746 // Retorna valor decimal de string com "," no lugar do ponto
747 // decimal (como os retornados pelo PagSeguro
748 return strtr($s, ',', '.') + 0;
749 }

  ViewVC Help
Powered by ViewVC 1.1.2