Search code examples
phpcurlpaypal-sandbox

Error while connecting to PayPal using REST API


While using connect with paypal on sandbox credential during token api call i always get the err

Array ( [error] => invalid_client [error_description] => Client Authentication failed ) 

Below shown is the CURL call i am using. please help me out

       $code = $_GET['code'];
       $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://api.sandbox.paypal.com/v1/oauth2/token');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=authorization_code&code=".$code."");
        
        $headers = array();
        $headers[] = 'Authorization: Basic client_id:client_secret';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);
        $output = json_decode($result,true);
        print_r($output);

Solution

  • As a comment mentions, CURLOPT_USERPWD is the simplest strategy, let curl do the work for you

    If you were to be setting the Authorization header yourself, client_id:client_secret would need to be Base64 encoded


    As a side note, when using curl on the command line the equivalent is the -u flag