3

I have to send the data from PHP to Salesforce and save the data in Salesforce. I have tried with the following code:

$curlurl    = "https://www.mysalesforce.com/services/apexrest/Contact?email={$email}&lastname={$lastname}&firstname={$firstname}&telephone={$telehone_number}&phone={$phone_number}&title={$title}&companyname={$companyname}";
$params     = "&grant_type=refresh_token&client_id={$id}&client_secret={$secret}&username={$username}&password={$password}&refresh_token={$token}";
$ch         = curl_init( $curlurl );  

curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );   
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );   
curl_setopt( $curl, CURLOPT_HEADER, $params );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );                                                               
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );                                                                     
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );

$json_value = curl_exec( $ch );
$info       = @curl_getinfo( $ch );

print_r( $info );

if( FALSE === $json_value ) {
    //post failed
    die( curl_error( $ch ) );

} else {
    echo "Response {$json_value}";
}

curl_close( $ch );

In return when I send the data I'm getting a response like this:

Array (
    [url]                       => https://mysalesforce.com/services/apexrest/Contact?email=asd@123.cox&lastname=asd&firstname=asd&telephone=1234567890&phone=1234567890&title=asd&companyname=asd
    [content_type]              => application/json;charset=UTF-8
    [http_code]                 => 401
    [header_size]               => 165
    [request_size]              => 193
    [filetime]                  => -1
    [ssl_verify_result]         => 20
    [redirect_count]            => 0
    [total_time]                => 1.609
    [namelookup_time]           => 0.015
    [connect_time]              => 0.265
    [pretransfer_time]          => 1.015
    [size_upload]               => 0
    [size_download]             => 75
    [speed_download]            => 46
    [speed_upload]              => 0
    [download_content_length]   => -1
    [upload_content_length]     => 0
    [starttransfer_time]        => 1.265
    [redirect_time]             => 0
    [certinfo]                  => Array ( )
    [primary_ip]                => 96.43.148.104 
    [primary_port]              => 443
    [local_ip]                  => 10.176.236.70
    [local_port]                => 2940
    [redirect_url]              =>
)

Response[{
    "message"   : "Session expired or invalid",
    "errorCode" : "INVALID_SESSION_ID"
}]

HTTP - Code 401 states that:

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource

1

Seems like you are not authenticating properly before making the callout to create the records in salesforce. Looking at your code, you need to obtain an access token which you need to pass in your request headers which will allow you access in order to be able to start making subsequent callouts.

Here is a good example of how to configure oAuth 2.0 for PHP integration with Salesforce. Also have a read here and here

0

I'm authenticating to the ERP using OAuth2. I request the server a token code that allows me to perform all the API requests I need, I only need to authenticate an user in order to receive a valid token.

Here is the code I use:

private static function getAccess()
    {
        $curl = curl_init();
        curl_setopt_array(
            $curl,
            array(
                CURLOPT_RETURNTRANSFER => TRUE,
                CURLOPT_URL            => LOGIN_URI . "/services/oauth2/token",
                CURLOPT_POST           => TRUE,
                CURLOPT_POSTFIELDS     => http_build_query(
                    array(
                        'grant_type'    => GRANT_TYPE,
                        'client_id'     => CLIENT_ID,
                        'client_secret' => CLIENT_SECRET,
                        'username'      => END_USERNAME,
                        'password'      => END_PASSWORD . TOKEN
                    )
                )
            )
        );

        $response = json_decode(curl_exec($curl));
        curl_close($curl);

        $access_token = (isset($response->access_token) && $response->access_token != "") ? $response->access_token : die("Error - access token missing from response!");
        $instance_url = (isset($response->instance_url) && $response->instance_url != "") ? $response->instance_url : die("Error - instance URL missing from response!");

        return array(
            "accessToken" => $access_token,
            "instanceUrl" => $instance_url
        );
    }

Where LOGIN_URI is the instance URL of your org (https://YOURORG.my.salesforce.com), GRANT_TYPE is "password", CLIENT_ID and CLIENT_SECRET are the alphanumeric strings you've got from your org, END_USERNAME is the username you are using to authenticate in your org, END_PASSWORD is the user's password, TOKEN is the user's personal token.

Once your user get authorized, you receive a token from the server and you can perform any API request using cURL:

private static function exec($url)
    {
        $credentials = self::getAccess();

        $curl = curl_init($credentials['instanceUrl'].$url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth ".$credentials['accessToken']));

        $json_response = curl_exec($curl);
        curl_close($curl);

        return $json_response;
    }

In this case, you only need to authorize once your user to access the org via APIs, every other request you make you just need to use the token you've received from the server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.