2

So after alot of searching around I've finally been able to successfully get my Paypal access token using PHP cURL. Now i'm trying to retrieve transaction details based on transaction id. So far i think I've gotten the call URL correct however i think that my post data formatting may be incorrect. The Code used is found below:

<?php

//this function is for handling post call requests
function make_post_call($url, $postdata) {
    global $token;
    $curl = curl_init($url); 
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSLVERSION , 6);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer '.$token,
                'Accept: application/json',
                'Content-Type: application/json'
                ));

    curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); 
    $response = curl_exec( $curl );
    print_r($response); //IM NOW RECEIVING OUTPUT, however symbols are now being replaced by placeholders such as '%40', how can i prevent this?
    if (empty($response)) {
        die(curl_error($curl)); //close due to error
        curl_close($curl); 
    } else {
        $info = curl_getinfo($curl);
        echo "Time took: " . $info['total_time']*1000 . "ms\n";
        curl_close($curl); // close cURL handler
        if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
            echo "Received error: " . $info['http_code']. "\n";
            echo "Raw response:".$response."\n";
            die();
        }
    }
    // Convert the result from JSON format to a PHP array 
    $jsonResponse = json_decode($response, TRUE);
    return $jsonResponse;
}

$token = get_access_token($url,$postArgs); //works and returns a valid access token

//This is the URL for the call
$url = 'https://api-3t.sandbox.paypal.com/nvp';

//This is the data to be sent in the call 
$postdata = array(
'USER' => 'peoplesroewrwwsg_api1.outlook.com', 
'PWD' => 'KR2TVKHGDSHSNDJ6E2', 
'SIGNATURE' => 'AFcWxV21C7fdFHSGGSDGD51G0BJYUWOCSyjUAKPPGs', 
'METHOD' => 'GetTransactionDetails', 
'VERSION' => '123', 
'TransactionID' => '1RE953245246192109'
);

$postdata = http_build_query($postdata); 
//$postdata = json_encode($postdata); //Is this the correct way of formatting? 

$transactionInfo = make_post_call($url, $postdata); //get transaction details NOT WORKING

print_r($transactionInfo); //does not print anything
?> 

im not recieving any cURL errors so i assume that the problem is either the data im sending or how i format it.

A breif Paypal guide on how to do this can be found here-> https://developer.paypal.com/docs/classic/express-checkout/gs_transaction/#tryit However it is written in cURL and not PHP cURL extension so im not sure if im sending the data properly.

Paypal GetTransactionDetails details here-> https://developer.paypal.com/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/

Any guidance regarding data formatting, or any other suggestions are greatly appreciated!

---------------------------------------------------------UPDATE!-----------------------------------------------------------

Now when i'm printing the result as soon as the cURL statement is executed im receiving information like this:

RECEIVERID=GN7SRQEGEREASDV9BQU&EMAIL=peoplesrobotiblabal%40outlook%2ecom&PAYERID=JC5RWUUKWGDFYJYY&PAYERSTATUS=verified&COUNTRYCODE=US&SHIPTONAME=Jane%20Smurf...

As can be seen some symbols such as periods are being replaced by placeholders such as '%40'. Can the sorce of this be identified? is it because i'm expecting a JSON response?

DiscreteTomatoes
  • 769
  • 1
  • 14
  • 30
  • 1
    The documentation clearly stated name => value pairs not JSON. Use `http_build_query()` to build the post data. And what makes you think the response will be in JSON? – frz3993 May 17 '16 at 00:12
  • hello! thank you very much for the suggestion (also i'm just guessing that the response is JSON, im not sure what it is really). I changed it back to `http_build_query()` and added a print statement that printed the cURL result as soon as it was received inside the function and i am now receiving a sorta correct output! how ever some symbols are replaced by place holders such as '%40' – DiscreteTomatoes May 17 '16 at 00:23
  • That is urldecoded string which is required when doing a http request. Can you comment out all `print_r` and just do `var_dump($POST)` after you make the curl request. Please update the question with the result. I think the API will make a return post request. – frz3993 May 17 '16 at 00:32
  • well `var_dump($response)` results in the same string as presented above, and `var_dump($_POST)` results in-> `array(0) { }` EDIT: also sorry if i dont understand u completely, for example i'm not sure a return post request – DiscreteTomatoes May 17 '16 at 00:36
  • 1
    No, that was just my guess because the response looks like a query string. In that case you can try to `parse_str($response, $response_array)`. Where the `$response_array` will contain the response as array elements. – frz3993 May 17 '16 at 00:42
  • will this method solve the problem with the changed symbols? I assume i will have to use a php function such as `preg_replace()` to re-inject the correct symbols, is this true? EDIT: Yes it works well! the symbols have been reverted and everything is in a nice associative array! frz3993 i would gladly accept your answer if u posted one with the information you've posted in these comments! – DiscreteTomatoes May 17 '16 at 00:46

3 Answers3

3

To build a http query string from a PHP array you can use PHP http_build_query(). Example:

$array = ['username' => 'John', 'password' => '123456abc'];
$postdata = http_build_query($array);

The symbol you mentioned is the urlencoded form of special characters. Http request will require the query string to be urlencoded. %40 is the urlencoded form of @. If in the future you require encoding/decoding to/from urlencoded string, you can use rawurldecode(), rawurlencode(), urlencode() and urldecode().

For parsing the response from PAYPAL NVP API. You can use parse_str(). Example 1:

$response = 'status=success&code=02';
parse_str($response, $response_array);
//$response_array will contain the $response as array

Example 2:

$response = 'status=success&code=02';
parse_str($response);
//this will display success
echo $status;
//this will display 02
echo $code;
frz3993
  • 1,595
  • 11
  • 13
3
<?php
function get_transaction_details( $transaction_id ) { 
    $api_request = 'USER=' . urlencode( 'api_username' )
                .  '&PWD=' . urlencode( 'api_password' )
                .  '&SIGNATURE=' . urlencode( 'api_signature' )
                .  '&VERSION=76.0'
                .  '&METHOD=GetTransactionDetails'
                .  '&TransactionID=' . $transaction_id;

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, 'https://api-3t.sandbox.paypal.com/nvp' ); // For live transactions, change to 'https://api-3t.paypal.com/nvp'
    curl_setopt( $ch, CURLOPT_VERBOSE, 1 );

    // Uncomment these to turn off server and peer verification
    // curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
    // curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_POST, 1 );

    // Set the API parameters for this transaction
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $api_request );

    // Request response from PayPal
    $response = curl_exec( $ch );
    // print_r($response);

    // If no response was received from PayPal there is no point parsing the response
    if( ! $response )
        die( 'Calling PayPal to change_subscription_status failed: ' . curl_error( $ch ) . '(' . curl_errno( $ch ) . ')' );

    curl_close( $ch );

    // An associative array is more usable than a parameter string
    parse_str( $response, $parsed_response );

    return $parsed_response;
}
$response = get_transaction_details('transaction_id');
echo "<pre>"; print_r($response);
?>
Chandrika Shah
  • 638
  • 6
  • 6
-1

Receiving information from cURL

$str = RECEIVERID=GN7SRQEGEREASDV9BQU&EMAIL=peoplesrobotiblabal%40outlook%2ecom&PAYERID=JC5RWUUKWGDFYJYY&PAYERSTATUS=verified&COUNTRYCODE=US&SHIPTONAME=Jane%20Smurf...

Please use parse_str("$str"); // add your value here, it will give you proper data format

More details : https://www.w3schools.com/php/func_string_parse_str.asp

Andronicus
  • 25,419
  • 17
  • 47
  • 88