AnswerBun.com

Calling REST APIs from PHP with curl

Salesforce Asked by Mike Lacourse on October 9, 2020

I’ve successfully received an access token thru the API, but no matter what I do I keep getting this “INVALID_SESSION_ID”. Does this mean the access key is invalid? I’ve tried lots of suggestions from StackExchange here but nothing has worked. Is there anything wrong with my code?

    $data = [[
        'FirstName' => 'Johnny',
        'LastName' => 'Appleseed',
    ]];

    $token = 'XXX';
    $instance = 'https://XXX.salesforce.com';

    // Initialize
    $request = curl_init( $instance . '/services/data/v42.0/sobjects/Contact' );

    // Set Options
    curl_setopt($request, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $token ]);
    curl_setopt($request, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]);
    curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($request, CURLOPT_TIMEOUT, 10);
    curl_setopt($request, CURLOPT_POST, 1);
    curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($request, CURLOPT_POSTFIELDS, json_encode($data) );

    // Make Request
    $response = json_decode(curl_exec($request));

    // Close Request
    curl_close($request);

One Answer

The issue was that I needed to include all headers as an array. Apparently you can't have multiple CURLOPT_HTTPHEADER options, they need to be included in a single array!

curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization: OAuth '.$token,
        'Content-Type: application/json', 'X-PrettyPrint: 1' ));

Answered by Mike Lacourse on October 9, 2020

Add your own answers!

Related Questions

GraphQL and Salesforce Development

2  Asked on November 25, 2021 by tekill

       

DataLoader Command Line – Error

1  Asked on November 25, 2021 by vishal-nayak

 

Error while Download excel file using vf page

0  Asked on November 25, 2021 by sai-venkat-prakash

 

Store Output Values tab missing from flow builder

1  Asked on November 25, 2021 by sfdc-dev-27

 

EventLog File Enable Hourly Logging

1  Asked on November 25, 2021 by maestro

 

The QS parameter in marketing cloud

1  Asked on November 25, 2021 by ciouz

 

Most robust way to parse CSV file via Apex code

1  Asked on November 23, 2021 by laureant

     

Lightning navigation new tab

1  Asked on November 23, 2021 by sfdcnoob

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP