TransWikia.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!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP