Search code examples
phpjsoncurlpaypalhttp-status-code-415

Posting Multidimensional Array through PHP cURL to PayPal


In the PayPal tutorial on making your first call it gives you a JSON string that I've found impossible to post. I've exhausted Google and I just can't seem to figure out how to post this data to PayPal. The code below gives me a 415 error code ("unsupported media type"). I've been stuck on the error for hours and am growing tired of it. I'll be grateful to anyone that can help me. I've tried to make my description clear in case we do find an answer others in the future will be able to find it easily.

        $post_data = array (
            'intent' => 'sale',
            'redirect_urls' => array (
                'return_url' => 'http://example.com/return',
                'cancel_url' => 'http://example.com/cancel'
            ),
            'payer' => array (
                'payment_mehod' => 'paypal'
            ),
            'transactions' => array (
                'amount' => array (
                    'total' => '7.47',
                    'currency' => 'USD'
                )
            )
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/payments/payment");
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $result_array['access_token']]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        $result = curl_exec($ch);

Edit: In the second to last line of provided code I have also used http_build_query and I've also tried just simply sending it as a multidimensional array. The error code 415 returns for both of these.


Solution

  • curl_setopt($ch, CURLOPT_HTTPHEADER, 
       array(
         'Content-Type: application/json', 
         'Authorization: Bearer ' . $result_array['access_token']
       )
    );