简体   繁体   中英

How to Transform this cURL code to PHP (PayPal API)

I have the following code

curl -v https://api.sandbox.paypal.com/v1/payments/payment \
-H 'Content-Type:application/json' \
-H 'Authorization:Bearer EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBV_WxVvgmsG' \
-d '{
  "intent":"sale",
  "redirect_urls":{
    "return_url":"http://example.com/your_redirect_url/",
    "cancel_url":"http://example.com/your_cancel_url/"
  },
  "payer":{
    "payment_method":"paypal"
  },
  "transactions":[
    {
      "amount":{
        "total":"7.47",
        "currency":"USD"
      }
    }
  ]
}'

I have been trying to convert it, but I don't know which parameters to use.

How can I convert it to PHP?

Looks like you'd need to do this. Note that because you're passing a JSON header, PayPal is (likely) requiring the body data to be sent as JSON, rather than form/value pairs. If you're passing a complex set of data, you may find it easier to define $data as an array, and use json_encode($data) to transform it for the CURLOPT_POSTFIELDS property.

$header = array();
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: Bearer EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBV_WxVvgmsG';

$url = 'https://api.sandbox.paypal.com/v1/payments/payment';

$data ='{
  "intent":"sale",
  "redirect_urls":{
    "return_url":"http://example.com/your_redirect_url/",
    "cancel_url":"http://example.com/your_cancel_url/"
  },
  "payer":{
    "payment_method":"paypal"
  },
  "transactions":[
    {
      "amount":{
        "total":"7.47",
        "currency":"USD"
      }
    }
  ]
}';

//open connection
$ch = curl_init();

//set connection properties
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

You can use json_decode to do the leg work for you.

Simply feed it the string that cURL passes back to you and it will in turn convert your JSON into a php usable array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM