Подтвердить что ты не робот

Что является проблемой в моем коде Sandbox paypal будущий платеж

У меня есть alredy, чтобы разрешить разрешение будущих платежей в моем приложении и с помощью панели разработчика dashboard.but, но пока не работает.  http://developer.paypal.com/ и войдите в систему  https://developer.paypal.com/developer/accountStatus там вы можете видеть, что у вас есть.

 $data = array(
                "intent" => "authorize",
                "payer" => array(
                    "payment_method" => "paypal"
                ),
                "transactions" => array(
                    array("amount" => array(
                        "currency" => "USD",
                        "total" => "1.88"
                    ),
                        "description" => "future of sauces")
                ));

        $data_string = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/payments/payment");
        $headers = array(
            'Content-Type: application/json',
            'PayPal-Client-Metadata-Id: d6743cbb53ea4470a53bfe458f0cb885',
            'Authorization: Bearer A103.B7d5318JDS6NA1zGh02avjCx16oxnBPadUat5z9SlGVGEiOhoAeMuqyz0anGSICS.FAkzECypTS1IXfemHcpVa5yyrGu',
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        //curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $result = curl_exec($ch);
        $information = curl_getinfo($ch);
        curl_close($ch);
        print_r($information);
        die;

Выводится здесь

{"name":"PERMISSION_DENIED","message":"No permission for the requested operation","information_link":"https://developer.paypal.com/docs/api/#PERMISSION_DENIED","debug_id":"5b39efd4cf370"}Array
(
    [url] => https://api.sandbox.paypal.com/v1/payments/payment
    [content_type] => application/json
    [http_code] => 403
    [header_size] => 592
4b9b3361

Ответ 1

Поскольку я не получал никакого решения от кого-либо, поэтому я пошагово входил в мой код и нашел решение.

function paypalFuturePayment($userID,$amount)
{
    $amount=number_format($amount,2);
    /* paypal App truxx dev client and secret key*/
    if($userID && $amount){
    $userData = selectById('tbl_users','*',"id='".$userID."'");
    $refresh_token = $userData['paypal_refresh_tokens'];
    $Metadata_id = $userData['paypal_metadata_id'];
    if($refresh_token && $Metadata_id){
        if ($_SERVER['SERVER_NAME'] == 'syonserver.com') {

            $clientId = "xxxxx";
            $secret = "xxx";

            $url1="https://api.sandbox.paypal.com/v1/oauth2/token";
            $url2="https://api.sandbox.paypal.com/v1/payments/payment";

        }else{
            $account = 0; // 0 for sandbox ,1 for live
            if ($account == 1) {
                //client live
                $clientId = "xxx";
                $secret = xxx";
                $url1 = "https://api.paypal.com/v1/oauth2/token";
                $url2 = "https://api.paypal.com/v1/payments/payment";
            } else {
                //client sandbox
                $clientId = "xxx";
                $secret = "xxx";
                $url1 = "https://api.sandbox.paypal.com/v1/oauth2/token";
                $url2 = "https://api.sandbox.paypal.com/v1/payments/payment";
        }
    }



//print_r($refresh_token);die;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url1);
        curl_setopt($ch, CURLOPT_HEADER, "Content-Type: application/x-www-form-urlencoded");
        curl_setopt($ch, CURLOPT_USERPWD, $clientId . ":" . $secret);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=refresh_token&refresh_token=" . $refresh_token);
        $result = curl_exec($ch);
        curl_close($ch);
        $result=json_decode($result);

       //11111111   for payment Authorize: For example, to first authorize the payment, use a request similar to this:

        $access_token =  $result->access_token;
        $data = array(
            "intent" => "authorize",
            "payer" => array(
                "payment_method" => "paypal"
            ),
            "transactions" => array(
                array("amount" => array(
                    "currency" => "USD",
                    "total" => $amount
                ),
                    "description" => "future of sauces")
            ));

        $data_string = json_encode($data);
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url2);
        $headers = array(
            'Content-Type: application/json',
            'PayPal-Client-Metadata-Id: '.$Metadata_id,
            'Authorization: Bearer '.$access_token,
            'Content-Length: ' . strlen($data_string)
        );
        curl_setopt($ch1, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch1, CURLOPT_POST, true);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $data_string);
        $result1 = curl_exec($ch1);
        curl_close($ch1);

        $result1=json_decode($result1);
        $message  = $result1->message;

       if($result1->state=='approved'){
           $access_id=  $result1->transactions[0]->related_resources[0]->authorization->id;

       }else{
           if(empty($message)){
               $message ='Authorization error, Please try again.';
           }
           return array('response' => '', 'success' => '0','message'=>$message);
       }

       // print_r($result1);die;

      //2222222   capture the payment:
        $data =  array("amount" => array(
            "currency" => "USD",
            "total" => $amount
        ),
            "is_final_capture" => "true"
        );
        $data_string = json_encode($data);
        $ch2 = curl_init();
        if ($_SERVER['SERVER_NAME'] == 'syonserver.com') {
            curl_setopt($ch2, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/payments/authorization/$access_id/capture");
        }else {
            $account = 0; // 0 for sandbox ,1 for live
            if ($account == 1) {
                //client live
             curl_setopt($ch2, CURLOPT_URL, "https://api.paypal.com/v1/payments/authorization/$access_id/capture");
        }else{
                curl_setopt($ch2, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/payments/authorization/$access_id/capture");
            }
        }

        $headers = array(
            'Content-Type: application/json',
            'Authorization: Bearer '.$access_token,
            'Content-Length: ' . strlen($data_string)
        );
        curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch2, CURLOPT_POST, true);
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch2, CURLOPT_POSTFIELDS, $data_string);
        $response = curl_exec($ch2);
        curl_close($ch2);

        $response_a = json_decode($response, true);
        $state = $response_a['state'];
        $message = $response_a['message'];
        if(!empty($response_a)){
            if($state=='completed') {
                return array('response' => $response_a, 'success' => '1','message'=>'Data received');
            }else{
                if(empty($message)){
                    $message ='Payment authorization error, Please try again.';
                }
                return array('response' => '', 'success' => '0','message'=>$message);
             }
        }
       else{
           return array('response' => '','success'=>'0','message'=>'Response nil');
           }
        }
      else
        {
            return array('response' => '', 'success' => '0','message'=>'Authorization code not available.');
        }
}else{

        return array('response' => '', 'success' => '0','message'=>'Unauthorize request.');

    }
}

Ответ 2

Я создал модуль Paypal, надеюсь, что этот код вам поможет.

$result_json = json_decode($result);

/* Check if authentication is valid */
if (isset($result_json->access_token))
{
    $enc_data = json_encode($data);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.sandbox.paypal.com/v1/payments/payment');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, !in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')));
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $enc_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer '.$result_json->access_token,
        'PayPal-Client-Metadata-Id: ************'
    ));

    $result = curl_exec($ch);
    $json_result = json_decode($result);
    curl_close($ch);
}

json_encode ($ data) есть дополнительная информация, которая может оказаться непригодной для транзакции, которую вы пытаетесь сделать, но это пример.

{
    "intent": "sale",
    "payer": {
        "payment_method": "credit_card",
        "payer_info": {
            "email": "...",
            "shipping_address": {
                [...]
            }
        },
        "funding_instruments": [
            {
                "credit_card": {
                    [...]
                    }
                }
            }
        ]
    },
    "transactions": [
        {
            "amount": {
                "total": 32.91,
                "currency": "USD"
            },
            "item_list": {
                "items": [
                    {
                        "quantity": 1,
                        "name": "Product Name",
                        "price": 16.51,
                        "currency": "USD"
                    },
                    {
                        "quantity": 1,
                        "name": "Product Name 2",
                        "price": "16.40",
                        "currency": "USD"
                    },
                    {
                        "quantity": 1,
                        "name": "Shipping",
                        "price": 0,
                        "currency": "USD"
                    }
                ],
                "shipping_address": {
                    [...]
                }
            }
        }
    ]
}

Ответ 3

Не могли бы вы мне помочь?

Я хочу использовать вашу функцию, но я не знаю, как я могу получить следующие значения:

$ refresh_token = $ userData ['paypal_refresh_tokens'];

$ Metadata_id = $ userData ['paypal_metadata_id'];

Где вы получаете значение для $ userData ['paypal_refresh_tokens'] и когда вы вставляете это значение в базу данных?

Я сейчас использую этот код

СЦЕНАРИЙ ДЛЯ КНОПКИ PAYPAL

  // Render the PayPal button

  paypal.Button.render({

      // Set your environment

      env: 'sandbox', // sandbox | production

      // Specify the style of the button

      style: {
          layout: 'vertical',  // horizontal | vertical
          size:   'medium',    // medium | large | responsive
          shape:  'rect',      // pill | rect
          color:  'gold'       // gold | blue | silver | black
      },

      // Specify allowed and disallowed funding sources
      //
      // Options:
      // - paypal.FUNDING.CARD
      // - paypal.FUNDING.CREDIT
      // - paypal.FUNDING.ELV

      funding: {
          allowed: [ paypal.FUNDING.CARD, paypal.FUNDING.CREDIT ],
          disallowed: [ ]
      },

      // PayPal Client IDs - replace with your own
      // Create a PayPal app: https://developer.paypal.com/developer/applications/create

      client: {
          sandbox:    'XXX',
          production: '<insert production client id>'
      },

      payment: function(data, actions) {
          return actions.payment.create({
              payment: {
                  transactions: [
                      {
                          amount: { total: '<?php echo (int)$_SESSION['total_carrito']; ?>', currency: 'USD' },
                          description:"Cotizacion"
                      }
                  ]
              }
          });
      },

      onAuthorize: function(data, actions) {
          return actions.payment.execute().then(function() {
              //window.alert('Payment Complete!');
              console.log(data.paymentID);
              window.location="verificador.php?paymentToken="+data.paymentToken+"&paymentID="+data.paymentID;
          });
      }

  }, '#paypal-button-container');

PHP PAGE

<?php
//print_r($_GET);
$ClientID='xxx';
$Secret='xxx';


$Login = curl_init("https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($Login, CURLOPT_RETURNTRANSFER,TRUE);

curl_setopt($Login, CURLOPT_USERPWD,$ClientID.":".$Secret);

curl_setopt($Login, CURLOPT_POSTFIELDS,"grant_type=client_credentials");

$Repuestas = curl_exec($Login);

$objRespuesta = json_decode($Repuestas);

$AccessToken=$objRespuesta->access_token;

//print_r($AccessToken);

$venta = curl_init("https://api.sandbox.paypal.com/v1/payments/payment/".$_GET['paymentID']);

curl_setopt($venta,CURLOPT_HTTPHEADER,array("Content-Type: application/json","Authorization: Bearer ".$AccessToken));
curl_setopt($venta, CURLOPT_RETURNTRANSFER,TRUE);
$RespuestaVenta = curl_exec($venta);
//print_r($RespuestaVenta);

$objDatosTransaccion = json_decode($RespuestaVenta);
print_r($objDatosTransaccion);
?>

Но я получаю следующую ошибку:

Array ( [paymentToken] => EC-5YA740396C956552P [paymentID] => PAY-3VC27070DH7716825LQGLBBA ) stdClass Object ( [name] => PERMISSION_DENIED [message] => No permission for the requested operation [information_link] => https://developer.paypal.com/docs/api/payments/#errors [debug_id] => 60a6d5274efd5 )