How to get header data in PHP post

Asked

Viewed 798 times

-2

Guys, I’m having a hard time getting a specific header data sent by Pagar..

When sending a postback to the site server, I need to use the signature sent in Header, in case the X-Hub-Signature containing sha1=435634896597u46y34t5gfds2891374.

But I don’t know how to get the contents of X-Hub-Signature. I tried to use the getallheaders() with a foreach to try to seek, but without success.

I also tried to get it from the json, since they have an api with this option too, which is also there, but I couldn’t get the content.

Below, I’ll put the code in json also for you to see.

[{"object":"postback","status":"success","model":"transaction","model_id":"8887765","headers":"{\"Content-Type\":\"application/x-www-form-urlencoded\",\"X-PagarMe-Event\":\"transaction_status_changed\",\"X-Hub-Signature\":\"sha1=435634896597u46y34t5gfds2891374\",\"User-Agent\":\"PagarMe-Hookshot/1.0\"}....

I hope you can help me.

2 answers

1


I would do something like this in front with javascript:

 var TRANSACTION_TYPE = 'boleto', 
     ENCRYPTION_KEY = 'SUA_ENCRYPTION_KEY',
     URL_POST_BACK = 'url-retorno-que-marca-pago',
     URL_PAGAMENTO = 'url-pagamento',
     PAYMENT_PRICE = 20.00,
     ID_PRODUTO = '123',
     TITULO_PRODUTO = 'Produto XYZ',
     DISPLAY_SUCCESS = { /* variável para mostrar layout 
                            de sucesso para a forma de pagamento 
                           (no caso do boleto, mostraria o botão do boleto) 
                      */
        is_boleto:false,
        is_credit_card:false
        };


      var registerPayment = function(data) {
                if (data.transaction_type == 'credit_card') {
                    DISPLAY_SUCCESS.is_credit_card = true;
                } 
         var xhttp = new XMLHttpRequest();
             xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                      var rtn = JSON.parse(this.responseText);
                      if (data.transaction_type == 'credit_card') {
                           if (rtn.status_payment == 'paid') {
                               alert('Pagamento foi efetuado com sucesso');
                                DISPLAY_SUCCESS.is_credit_card = true;

                             } else if(rtn.status_payment == 'authorized') {
                                 postBackCaptureResultCreditCard(data);
                             } else {
                                 //entra num loop até concluir o pagamento (caso haja um retorno diferente de pago que não seja um erro)...
                                 postBackCaptureResultCreditCard(data);
                             }

                        } else {
                            //boleto
                            if (rtn.status_payment == 'paid') {
                               alert('Pagamento foi efetudo com sucesso');
                             } else {
                               DISPLAY_SUCCESS.is_boleto = true;  
                               $scope.form.boleto_url = rtn.boleto_url;
                               $scope.form.boleto_code = rtn.boleto_barcode;
                             }
                        } 
               }
             xhttp.open("POST",URL_PAGAMENTO, true);
             xhttp.send();
    };

    function paymentAction() {

           var checkout = new PagarMeCheckout.Checkout({
              encryption_key: ENCRYPTION_KEY,
              success: function(data) {

               var saveData = {
                         post_back_url: URL_POST_BACK,
                         transaction_token: data.token,
                         price:PAYMENT_PRICE,
                         transaction_type:TRANSACTION_TYPE,
                         api_payment:URL_PAGAMENTO,
               }
               registerPayment(saveData);
           },
           error: function(err) {
             console.log(err);
           },
           close: function() {
            console.log('Fecha janela modal de pagamento');
           });

          var amount = Number(
              parseFloat(PAYMENT_PRICE)
              .toFixed(2)
              .replace('.', '')
         );


        // Obs.: é necessário passar os valores boolean como string
        checkout.open({
                       amount: amount,
                       buttonText: 'Pagar',
                       buttonClass: 'botao-pagamento',
                       customerData: 'true',
                       createToken: 'true',
                       maxInstallments: 10,
                       freeInstallments: 10,
                       defaultInstallment: 1,
                       uiColor:'#1E90FF',
                       paymentMethods: 'credit_card,boleto',
                       postback_url:URL_POST_BACK,
                       items: [
                                  {
                                     id: ID_PRODUTO,
                                     title: TITULO_PRODUTO,
                                     unit_price: amount,
                                     quantity: 1,
                                     tangible: true
                                  }
                      ]

        }); 

    }

And in the backend on the Model layer:

    namespace App\Http\Services;

        use PagarMe;
        use App\EntidadeBancoDados;

        class PagarmeServices
        {

            protected $pagarme;

            public function __construct()
            {
                $api_key = getenv('PAGARME_API_KEY');
                $this->pagarme = new PagarMe\Client($api_key);

            }

            public function transaction($data)
            {
                $data_pagarme = false;
                $return["status"] = false;

                EntidadeBancoDados::insertTransaction($data);

                $data_pagarme = $this->getTransactionById($data['transaction_id']);
                if($data_pagarme->status == 'authorized'){
                    $data_pagarme = $this->pagarme->transactions()->capture([
                        'id' => $data['transaction_id'],
                        'amount' => $data['amount']
                    ]);
                }

                if ($data_pagarme) {

       EntidadeBancoDados::updateTypeTransactionAndBillet($data['id'], $data_pagarme->status ,$data_pagarme->tid, $data_pagarme->boleto_url);
                    $return["status"] = true;
                    $return["status_payment"] = $data_pagarme->status;
                    $return["payment_method"] = $data_pagarme->payment_method;
                    $return["boleto_url"] = $data_pagarme->boleto_url;
                    $return["boleto_barcode"] = $data_pagarme->boleto_barcode;

                }

                return $return;

            }

            public function postback($data)
            {

                $id = isset($data['id']) ? $data['id'] : false;
                $current_status = isset($data['current_status']) ? $data['current_status'] : false;

                if ($id && $current_status) { 

 EntidadeBancoDados::updateTypeTransaction($id,$current_status);
                }             
            }

            public function getTransactionById($id){
                try{

                    $transaction = $this->pagarme->transactions()->get([
                        'id' => $id 
                    ]);

                    return $transaction;
                } catch (\Throwable $th) {
                    return false;
                }

            }   

        }

0

To solve, I tried to use $_SERVER['X-Hub-Signature'] ended up working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.