Tips for creating a cURL request with basic authentication in Laravel version 8

I am working with the PayPal Payout SDK and using the code below to obtain access tokens from the PayPal API.

curl -v POST https://api-m.sandbox.paypal.com/v1/oauth2/token \
  -H "Accept: application/json" \
  -H "Accept-Language: en_US" \
  -u "CLIENT_ID:SECRET" \
  -d "grant_type=client_credentials"

In order to retrieve the access token, I have experimented with the following methods.

$client_id = "AWN5555";
$secret = "44444";
$url = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
$data = ['grant_type:client_credentials'];

$response = Http::withHeaders([
    'Accept:application/json',
    'Accept-Language:en_US',
    "Content-Type: application/x-www-form-urlencoded"
])->withBasicAuth($client_id, $secret)
    ->post($url, $data);

// OR

$response = $client->request('POST', $url, [
    'headers' => [
        'Accept' => 'application/json',
        'Accept-Language' => 'en_US',
        'Authorization ' => ' Basic ' .
            base64_encode($client_id . ':' . $secret)
    ],
    'form_params' => [
        'grant_type' => 'client_credentials',
    ]
]);

Answer №1

For Laravel version 7 or 8:

$client_id = "AWN5555";
$secret = "44444";
$url = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
$data = [
            'grant_type' => 'client_credentials',
        ];

$response =  Http::asForm()
                            ->withBasicAuth($client_id, $secret)
                            ->post($url, $data);

Alternatively, for a PHP native approach:

$client_id = "AWN5555";
$secret = "44444";
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api-m.sandbox.paypal.com/v1/oauth2/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
CURLOPT_HTTPHEADER => [
    'Authorization: Basic '.base64_encode($client_id.':'.$secret)
  ],
]);

$response = curl_exec($curl);

curl_close($curl);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to remotely access a file stored on a Windows drive from Ubuntu using PHP

In my Windows environment, I had the following command: exec('copy /V "'.$file.'" "'.$dest.'"'); where $file is a REMOTE file in a windows drive such as: \\server\dr1$\folder\file \\serv ...

Guide to authenticating users using Vue JS and Django

Currently, I am collaborating on a compact university venture utilizing Vue JS, Django2, and Django Rest Framework. The project involves two distinct user roles with varying actions within the application. The aspect that is leaving me puzzled is the logi ...

Error: Unexpected syntax error encountered, the script is looking for a different syntax ("=>")

I encountered this error message "Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')'" , when attempting to create a 2D array in order to pass two keys into a foreach loop. $productIds = array ( [0] =&g ...

Transforming the output from fetchAll() into a well-

Currently, I'm utilizing fetchAll(PDO::FETCH_ASSOC) to query my self-made database using an SQL statement. In order to visualize the retrieved data, I am employing print_r(). The values returned by print_r() look like this: Array ( [0] => Array ( ...

Running PHP scripts from JavaScript

Currently working on a PHP project that involves a dropdown select button in a webpage. The goal is to call a JavaScript function whenever the value of the dropdown changes, and then pass this selected value to retrieve additional details from a MySQL da ...

Ajax request causing bootstrap success message to have shorter visibility

I encountered an issue with my ajax form that retrieves data using the PHP post method. Instead of utilizing the alert function in JavaScript, I decided to use a bootstrap success message. However, there is a problem as the message only appears for less th ...

Having difficulty accessing all documents through "zip_read" function from ZIP archive

I am working on a task to iterate through all the files within a zip file that has approximately 65000 files. However, I am only able to read 315 files out of them. Despite checking the error log, I can't seem to figure out the reason for this issue. ...

Engaging with a JSON data structure

I have experience using ajax for writing to sessions and performing inserts, but now I need to receive a response. While I've managed to get it working somewhat by going through examples, I'm currently stuck at a certain point. I am in search of ...

The Prestashop feature RenderView within the backOffice Controller

Currently working on a Prestashop module, I found myself in need of a new controller. After creating it without any issues, I encountered some problems when trying to display information within it. The code snippet I have so far is as follows: class Pin ...

Guide to setting up npm pug-php-filter in conjunction with gulp

I'm having trouble setting up pug-php-filter (https://www.npmjs.com/package/pug-php-filter) with gulp in order to enable PHP usage in my Pug files. Any assistance would be greatly appreciated. ...

Show the username of the currently logged-in user

I am attempting to show the username of the currently logged-in user. The table structure is as follows: Table Name: system_users, u_userid - stores the id, u_username - stores the username Currently, it displays all users instead of just the logged user ...

Solving the Conundrum: User Authentication Failure in Yii

When I try to log into an application built on the Yii framework, it appears that the login process gets stuck at either the validation or the login function in my site controller. The login never goes through and nothing useful happens. There are no error ...

Removing a feature through AJAX in CodeIgniter

Issue Resolved.. I have updated my code accordingly.. Thanks to everyone for the help Description: My code displays an array of message traces (each message is displayed in a grey panel). Users can delete unwanted messages by clicking on the delete button ...

An algorithm designed to evenly distribute items among multiple arrays when the number of items is less than the number of arrays

Looking for an algorithm in PHP that can evenly distribute items across multiple arrays while skipping arrays if the number of items is less than the number of arrays. Here's a hypothetical scenario to illustrate my problem: Scenario: Imagine there ...

Managing the AJAX response from a remote CGI script

I'm currently working on a project that involves handling the response of a CGI script located on a remote machine within a PHP generated HTML page on an apache server. The challenge I am facing relates to user authentication and account creation for ...

Display conceal class following successful ajax response

Upon clicking the button, the following script is executed: $.ajax({ url: "<?php echo CHILD_URL; ?>/takeaway-orders.php", type: 'POST', async:false, data: 'uniq='+encodeURIComponent(uniq)+'&menu_id=' ...

Receiving an incorrect UTF-8 sequence in the JSON input

I currently have an ec2 server running with PHP version 5.3, hosting 2 virtual hosts: one for development and one for live production. Interestingly, on the development host, if someone uploads a file containing invalid UTF-8 characters, it simply ignores ...

Efficient PHP caching solution for optimizing JavaScript and CSS performance

I'm facing a unique challenge that I can't seem to solve through typical Google searches. I'm in the process of consolidating all my javascript and css into separate php files using require_once() to pull in the content. The structure of my ...

Generate a standard Wordpress menu containing all pages without the need to manually add each page in the menu editor

I'm struggling to figure out how to display all pages in WordPress without manually adding them to a menu. Instead of creating a new menu and selecting specific pages, I want to automatically show all existing pages in the menu. For example, if I ha ...

Is there a way to prevent this picture from shifting?

I am currently revamping the content on my work website using Joomla. I have received the old copy and now I need to enhance it. The website in question is 24x7cloud.co.uk. At the bottom of the page, I aim to include an "Accreditation's" section. Howe ...