Skip to content

Instantly share code, notes, and snippets.

@it-cast
Last active June 25, 2018 16:17
Show Gist options
  • Save it-cast/f724ff2b533331ccf2fbb3481788c408 to your computer and use it in GitHub Desktop.
Save it-cast/f724ff2b533331ccf2fbb3481788c408 to your computer and use it in GitHub Desktop.
<?php
class pedido_PagSeguro {
static private $_url = 'https://ws.pagseguro.uol.com.br/v2/';
// static private $_url = 'https://ws.sandbox.pagseguro.uol.com.br/v2/';
static private $_error;
static public function getError(){
return static::$_error;
}
static private function logFile($logText){
$file = './log_pagseguro.txt';
$date = date('Y-m-d H:i:s');
file_put_contents($file, $date.' - '.$logText."\n",FILE_APPEND);
}
static private function curlPagSeguro($action, $fields, $method='post'){
$url = static::$_url.$action;
//open connection
$ch = curl_init();
if ( $method=='post' or $method==1){
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
} else {
curl_setopt($ch, CURLOPT_URL, $url.'?'.$fields);
}
// receive server response ...
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
static public function getSession($empresa_id){
$Empresa = new empresa_Model_Empresa();
$empresa = $Empresa->getDadosPagSeguro($empresa_id);
//set POST variables
$fields = "email=".$empresa['pagseguro_email']."&token=".$empresa['pagseguro_token'];
$result = static::curlPagSeguro('sessions',$fields);
if($result == 'Unauthorized'){
static::$_error = 'Forma de Pagamento não autorizada';
return false;
}
$dados = simplexml_load_string($result);
if(count($dados->error) > 0){
static::$_error = $dados->error;
return false;
}
return $dados;
}
static public function addPayment($data){
// $data content
// [pedido] => 27
// [cardNumber] => 5162208596752032
// [cvv] => 801
// [expirationMonth] => 07
// [expirationYear] => 2019
// [brand] => mastercard
// [nome] => emilio
// [cpf] => 11231266740
// [dataNascimento] => 17/05/1985
// [hashVendedor] => a57251ee36b1610057a0ea699a62cfc2da55a8b4e5c270c584e4d78f5cf62139
// [hashCard] => 07c5c398239c451b9712116fe770474e
$Pedido = new pedido_Model_Pedido();
$dados = $Pedido->getPedidoPagseguro($data['pedido']);
if ($dados){
//--apenas com numeros
$dados['telefone'] = preg_replace( '/[^0-9]/','',$dados['telefone']);
$data['cpf'] = preg_replace( '/[^0-9]/','',$data['cpf']);
$fields = "email=".$dados['pagseguro_email'].
"&token=".$dados['pagseguro_token'].
"&paymentMode=default".
"&paymentMethod=creditCard".
"&currency=BRL".
"&receiverEmail=".$dados['pagseguro_email'].
"&itemId1=1".
"&itemDescription1=Compra".
"&itemAmount1=".number_format($dados['valortotal'],2).
"&itemQuantity1=1".
"&notificationURL=http://***/aplicativo/pagsegnotifica/{$dados['empresa_id']}".
"&senderName=".$data['nome'].
"&senderCPF=".$data['cpf'].
"&senderAreaCode=".substr($dados['telefone'],0,2).
"&senderPhone=".substr($dados['telefone'],2,9).
// "&[email protected]".
"&senderEmail=".$dados['email'].
"&senderHash=".$data['hashVendedor'].
"&shippingAddressRequired=false".
"&installmentQuantity=1".
"&installmentValue=".number_format($dados['valortotal'],2).
"&creditCardToken=".$data['hashCard'].
"&creditCardHolderName=".$data['nome'].
"&creditCardHolderCPF=".$data['cpf'].
"&creditCardHolderBirthDate=".$data['dataNascimento'].
"&creditCardHolderAreaCode=".substr($dados['telefone'],0,2).
"&creditCardHolderPhone=".substr($dados['telefone'],2,9).
"&billingAddressStreet=".$dados['endereco'].
"&billingAddressNumber=".$dados['numero'].
"&billingAddressComplement=".$dados['complemento'].
"&billingAddressDistrict=".$dados['bairro'].
"&billingAddressPostalCode=".$dados['cep'].
"&billingAddressCity=".$dados['cidade'].
"&billingAddressState=".$dados['uf'].
"&billingAddressCountry=BRA";
$result = static::curlPagSeguro('transactions', $fields);
if($result == 'Unauthorized'){
static::$_error = 'Forma de Pagamento não autorizada';
return false;
}
$dados = simplexml_load_string($result);
if(count($dados->error) > 0){
foreach ($dados->error as $err) static::$_error[] = (string) $err->message[0];
return false;
}
//--Atualiza pedido
$confirm = $Pedido->update(array(
'pagseguro_code' => $dados->code,
'pagseguro_taxa' => $dados->feeamount,
'situacao_pgto' => $dados->status
));
if (!$confirm){
//--tratar erro de atualização no banco
}
return true;
} else {
static::$_error = 'Pedido não encontrado!';
return false;
}
}
static public function receiveNotificationCode($empresa_id=14,$notificationCode){
$Empresa = new empresa_Model_Empresa();
$dados = $Empresa->getDadosPagSeguro($empresa_id);
if ($dados){
$log = 'EMPRESA=>'.$empresa_id.' - notificationCode=>'.$notificationCode;
$fields = "email=".$dados['pagseguro_email']."&token=".$dados['pagseguro_token'];
$url = "transactions/notifications/".$notificationCode;
$result = static::curlPagSeguro($url, $fields, 'get');
if($result == 'Unauthorized'){
$log .= ' - RESULT Unauthorized';
static::logFile($log);
return false;
}
$dados = simplexml_load_string($result);
if(count($dados->error) > 0){
$log .= ' - ERROR=>'.$dados->error;
static::logFile($log);
return false;
}
$Pedido = new pedido_Model_Pedido();
if ( $Pedido->updateStatusPgto($dados) ){
$log .= ' - UPDATE OK';
static::logFile($log);
return true;
} else {
$error = $Pedido->getErrorInfo();
$log .= ' - UPDATE ERROR - SENTENCE->'.$Peidido->getSentence();
$log .= ' - ERROR INFO->'.$error[2];
static::logFile($log);
return false;
}
} else {
static::$_error = 'Empresa não configurou o cadastro no pagseguro!';
return false;
}
}
}
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController, ViewController, AlertController } from 'ionic-angular';
import {HttpService} from '../../services/http-service'
import {Observable} from 'rxjs/Observable';
import scriptjs from 'scriptjs';
declare var PagSeguroDirectPayment;
/**
* Generated class for the PagSeguroPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-pagseguro',
templateUrl: 'pagseguro.html',
})
export class PagSeguroPage {
status:boolean = false;
session: any;
credentials:any;
empresa_id:any;
dados = {
'empresa' : '',
'pedido' : '',
'cardNumber' : '',
'cvv' : '',
'expirationMonth': '',
'expirationYear' : '',
'brand' : '',
'nome' : '',
'cpf' : '',
'dataNascimento' : '',
}
returnData:any = false;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public httpService: HttpService,
public loading: LoadingController,
public viewCtrl: ViewController,
public alertCtrl: AlertController
) {
//--Recebe dados do pedido por parameto
this.dados.pedido = this.navParams.get('pedido');
this.dados.empresa = this.navParams.get('empresa');
this.returnData = this.navParams.get('returnData') || false;
//--INICIA SESSAO NO PAGSEGUTO
let loader = this.loading.create({content: 'Iniciando sessão...',});
loader.present();
this.startSession(this.dados.empresa).then(result => {
loader.dismiss();
if (!result)
this.viewCtrl.dismiss({error:'Falha ao iniciar sessão! Tente novamente por favor!'});
});
}
startSession(empresa_id){
this.empresa_id = empresa_id;
return new Promise( (resolve) => {
scriptjs('https://stc.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js', () => {
this.getSession(resolve);
})
})
}
private getSession(resolve){
let data = {'id':this.empresa_id};
this.httpService.postData(data,'pagsegsessao')
.subscribe(
(dados: any)=>{
if (dados[0]==1) {
this.session = dados[1];
console.log(this.session.id);
PagSeguroDirectPayment.setSessionId(this.session.id);
resolve(true);
} else {
resolve(false);
}
},(err)=>{
console.log(err);
resolve(false);
}
);
}
buscaBandeira(){
if (this.dados.cardNumber.trim().length){
console.log(this.dados.cardNumber);
this.getBrand(
this.dados.cardNumber,
(response) => {
this.dados.brand = response.brand.name;
console.log('Bandeira do cartão: ' + this.dados.brand);
},
(response) => {
console.log(response);
}
);
}
}
getBrand(numCard,success,error){
PagSeguroDirectPayment.getBrand({
cardBin: numCard,
success: success,
error: error
});
}
finaliza(){
let loader = this.loading.create({content: 'Verificando dados...'});
loader.present();
this.createCardToken(this.dados).then(
(dados)=>{
loader.dismiss();
if (this.returnData){
this.viewCtrl.dismiss(this.getDataPayment());
} else {
this.postPayment();
}
}, (err)=>{
console.log(err);
let error = [];
for (let prop in err.errors ) error.push(err.errors[prop]);
let alert = this.alertCtrl.create({
title: 'Erro!',
message: error.join(', '),
buttons: ['Ok']
});
loader.dismiss();
alert.present();
}
);
}
createCardToken(credentials){
credentials['hashVendedor'] = PagSeguroDirectPayment.getSenderHash();
return new Promise((response,reject)=>{
PagSeguroDirectPayment.createCardToken({
cardNumber: credentials.cardNumber.replace(/\D/g,''),
cvv: credentials.cvv,
expirationMonth: credentials.expirationMonth,
expirationYear: credentials.expirationYear,
brand: credentials.brand,
success: data => {
credentials['hashCard'] = data.card.token;
this.credentials = credentials;
response(credentials);
},
error: reject,
});
});
}
getDataPayment(){
return {
'pedido' : this.credentials.pedido,
'brand' : this.credentials.brand,
'nome' : this.credentials.nome,
'cpf' : this.credentials.cpf.replace(/\D/g,''),
'dataNascimento' : this.credentials.dataNascimento,
'hashVendedor' : this.credentials.hashVendedor,
'hashCard' : this.credentials.hashCard
}
}
postPayment(){
//--Enviando pagamento para servidor
let loader = this.loading.create({content: 'Realizando pagamento...'});
loader.present();
let hashData = this.getDataPayment();
this.httpService.postData(hashData,'pagsegend')
.subscribe((dados)=>{
if (dados[0]==1){
this.viewCtrl.dismiss();
}else{
console.log(dados[1]);
//--Aviso de erro!
let erro = '';
if (Array.isArray(dados[1]) ) erro = dados[1].join(',<br>');
else erro = dados[1];
//--Exibe erros
this.alertCtrl.create({
title: 'Erro!',
message: erro,
buttons: ['Ok']
}).present();
}
loader.dismiss();
},(err)=>{
loader.dismiss();
console.log(err);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment