www.webdeveloper.com
Results 1 to 13 of 13

Thread: Help finding the cause of this error

  1. #1
    Join Date
    Feb 2012
    Posts
    102

    Question Help finding the cause of this error

    Hello

    I am working with Paypal REST apis and I am having a hard time finding my error. I have read all the documentation and cant seem to find a solution so I thought I would try you guys for some help. I have this code to process my calls and I am getting the error unexpected T_PUBLIC on the line that starts the process payment function. If anyone can figure out why as I have made sure all of my closing brackets are there so I do not understand where this error is coming from.

    PHP Code:
    class paypal {
            private 
    $access_token;
            private 
    $token_type;
            
            
    /**
            * Constructor
            *
            * Handles oauth 2 bearer token fetch
            * @link https://developer.paypal.com/webapps/developer/docs/api/#authentication--headers
            */
            
    public function __construct(){
                
    $postvals "grant_type=client_credentials";
                
    $uri PAYMENT_URI "v1/oauth2/token";
                
                
    $auth_response self::curl($uri'POST'$postvalstrue);
                
    $this->access_token $auth_response['body']->access_token;
                
    $this->token_type $auth_response['body']->token_type;
            }
         
            
    /**
            * cURL
            *
            * Handles GET / POST requests for auth requests
            * @link http://php.net/manual/en/book.curl.php
            */
            
    private function curl($url$method 'GET'$postvals null$auth false){
                
    $ch curl_init($url);
                
                
    //if we are sending request to obtain bearer token
                
    if ($auth){
                    
    $headers = array("Accept: application/json""Accept-Language: en_US");
                    
    curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_BASIC);
                    
    curl_setopt($chCURLOPT_USERPWDCLIENT_ID ":" .CLIENT_SECRET);
                    
    curl_setopt($chCURLOPT_SSLVERSION3);
                    
    curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
                    
    curl_setopt($chCURLOPT_SSL_VERIFYHOST2);
                
    //if we are sending request with the bearer token for protected resources
                
    } else {
                    
    $headers = array("Content-Type:application/json""Authorization:{$this->token_type} {$this->access_token}");
                }
                   
                
    $options = array(
                    
    CURLOPT_HEADER => true,
                    
    CURLINFO_HEADER_OUT => true,
                    
    CURLOPT_HTTPHEADER => $headers,
                    
    CURLOPT_RETURNTRANSFER => true,
                    
    CURLOPT_VERBOSE => true,
                    
    CURLOPT_TIMEOUT => 10
                
    );
                
                if (
    $method == 'POST'){
                    
    $options[CURLOPT_POSTFIELDS] = $postvals;
                    
    $options[CURLOPT_CUSTOMREQUEST] = $method;
                }
                
                
    curl_setopt_array($ch$options);
             
                
    $response curl_exec($ch);
                
    $header substr($response0curl_getinfo($ch,CURLINFO_HEADER_SIZE));
                
    $body json_decode(substr($responsecurl_getinfo($ch,CURLINFO_HEADER_SIZE)));
                
    curl_close($ch);
                
                return array(
    'header' => $header'body' => $body);
            }
        }
        
        
    // Function for Processing Payment
        
    public function process_payment($request) {
            
    $postvals $request;
            
    $uri PAYMENT_URI "v1/payments/payment";
            return 
    self::curl($uri'POST'$postvals);
        } 
    *If I take public out then I get a different error stating "Fatal error: Cannot access self:: when no class scope is active" I do not understand that error either.

    Any help would be great.

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,609
    Because the function definition is outside of the class definition. Presumably you want the last "}" right before it to be moved to after that method?
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Feb 2012
    Posts
    102
    Quote Originally Posted by NogDog View Post
    Because the function definition is outside of the class definition. Presumably you want the last "}" right before it to be moved to after that method?
    So would I move my entire call to the api inside the class then? I am confused as I have never used the class system.

    Can I do this without using the class and public/private functions or will my code be in trouble?
    Last edited by mcco; 10-09-2013 at 02:01 PM.

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,609
    Since I don't 100% know what you are intending to do, all I can say is that a typical usage might be to move that function definition inside the class, then you would access it from outside of the class something like:
    PHP Code:
    $paypal = new PayPal();
    $result $paypal->process_payment($request); // whatever $request is supposed to be 
    However, if I were going to do this, then the process_payment() method should use $this->curl() instead of self::curl(). (curl() is not defined as static, so should not be referenced statically.)
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  5. #5
    Join Date
    Feb 2012
    Posts
    102
    Sorry for not being clear. I am trying to send a payment request using the Paypal REST Api system with a payment method of paypal. I am getting it to work using your last code to process the payment but now I am getting a malformed JSON error message can you help me with that? Here is my code I use to make the JSON request:

    PHP Code:
    $request = array(
                
    'intent' => 'sale',
                
    'redirect_urls' => array(
                    
    'return_url' =>'http://test.sportdirections.com/',
                    
    'cancel_url' =>'http://test.sportdirections.com/cart'
                
    ),
                
    'payer' => array(
                    
    'payment_method' =>'paypal'
                
    ),
                
    'transactions' => array(
                    
    'amount' => array(
                        
    'total' =>''.number_format($order_total,2).'',
                        
    'currency' =>'USD',
                        
    'details' => array(
                            
    'subtotal' =>''.number_format($subtotal,2).'',
                            
    'shipping' =>''.number_format($shipping,2).''
                        
    ),
                        
    'item_list' => array(
                            
                        )
                    ),
                    
    'description' =>'Order ID #'.$order_id.''
                
    )
            );
            
            while (
    $items mysqli_fetch_array($rMYSQLI_ASSOC)) {
            
                
    $newitems = array(
                    
    'quantity' =>''.$items['quantity'].'',
                    
    'name' =>''.$items['name'].'',
                    
    'price' =>''.get_price($items['price'],$items['sales_price']).'',
                    
    'currency' =>'USD'
                
    );
                
    array_push($request['transactions']['amount']['item_list']['items'], $newitems);
            }
            
            
    $request json_encode($request); 
    Any Ideas?

  6. #6
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,609
    Not without knowing the exact error message and its source. (Is it a local PHP error or an error response from the PayPal API?)

    If the latter, print out $request after you json_encode() it, copy/paste it at http://jsonlint.com/ to validate its structure and to format it into something readable, then compare that output to what the API says is the expected format.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  7. #7
    Join Date
    Feb 2012
    Posts
    102
    Ok so I have traced my problem back to where I try to dynamically add items to the array with array_push. It seems my json string says null where it is supposed to have the information. Using the code I added above what am I doing wrong with my use of array_push?

  8. #8
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,609
    When you say null values, are you getting nothing at all for the "items" section, or something like:
    Code:
    "items: [
      {
        "quantity": NULL,
        "name" NULL,
        "price": NULL,
        "currency": NULL
      }
    ]
    If you're getting nothing at all, then my first suspect would be that the DB query didn't return anything. If you're getting actual but NULL values, then I don't immediately see why that would be.

    PS: assigning variable values concatenated within empty strings should not be necessary:
    PHP Code:
    $foo ''.$bar.'';
    // can just be
    $foo $bar
    If you want to force it to be a string, I think it's a bit cleaner to do
    PHP Code:
    $foo = (string) $bar
    Not that I think that has anything to do with your problem.

    For that matter, you don't really need to use array_push(), as you can get the same thing with empty bracket notation:
    PHP Code:
    $request['transactions']['amount']['item_list']['items'][] = $newitems
    But that's really just personal preference, I guess.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  9. #9
    Join Date
    Feb 2012
    Posts
    102
    Ok we are making some headway but I am still receiving the same error message. I check with your json link above and my json is valid. here is the error message I am receiving from Paypal in response:

    array(2) { ["header"]=> string(287) "HTTP/1.1 400 Bad Request Server: Apache-Coyote/1.1 PayPal-Debug-Id: 25fc73e815340 Content-Type: application/json Content-Length: 213 DC: origin2-api.sandbox.paypal.com Date: Wed, 09 Oct 2013 22:08:01 GMT Connection: close Set-Cookie: DC=origin2-api.sandbox.paypal.com; secure " ["body"]=> object(stdClass)#4 (4) { ["name"]=> string(17) "MALFORMED_REQUEST" ["message"]=> string(49) "Incoming JSON request does not map to API request" ["information_link"]=> string(74) "https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST" ["debug_id"]=> string(13) "25fc73e815340" } }

    Anyone that can decode that would be very helpful.

  10. #10
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,609
    I think you have the item_list array at the wrong level. It should be part of the "transactions" array, not the "amount" array within transactions:
    PHP Code:
    $request = array(
        
    'intent' => 'sale',
        
    'redirect_urls' => array(
            
    'return_url' =>'http://test.sportdirections.com/',
            
    'cancel_url' =>'http://test.sportdirections.com/cart'
        
    ),
        
    'payer' => array(
            
    'payment_method' =>'paypal'
        
    ),
        
    'transactions' => array(
            
    'amount' => array(
                
    'total' =>''.number_format($order_total,2).'',
                
    'currency' =>'USD',
                
    'details' => array(
                    
    'subtotal' =>''.number_format($subtotal,2).'',
                    
    'shipping' =>''.number_format($shipping,2).''
                
    )
            ),
            
    'item_list' => array(

            ),
            
    'description' =>'Order ID #'.$order_id.''
        
    )
    ); 
    So then you'd be adding $newitems to $request['transactions']['item_list']['items']
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  11. #11
    Join Date
    Feb 2012
    Posts
    102
    Sorry I forgot to post but I noticed that and fixed it and I am still getting the same error here is my print_r of my json request:

    Code:
    {
        "intent": "sale",
        "redirect_urls": {
            "return_url": "http://www.example.com/",
            "cancel_url": "http://www.example.com/cart"
        },
        "payer": {
            "payment_method": "paypal"
        },
        "transactions": {
            "amount": {
                "total": "929.75",
                "currency": "USD",
                "details": {
                    "subtotal": "889.80",
                    "shipping": "39.95"
                }
            },
            "description": "Mike and Maureen Photography - Order ID #5",
            "item_list": {
                "items": [
                    {
                        "quantity": "1",
                        "name": "40 Steps and a View-20\" x 24\" - 1.5\" thick gallery wrap canvas",
                        "price": "204.95",
                        "currency": "USD",
                        "sku": "7 - 10"
                    },
                    {
                        "quantity": "1",
                        "name": "Emerald Bay-24\" x 36\" - 0.75\" thin gallery wrap canvas",
                        "price": "219.95",
                        "currency": "USD",
                        "sku": "8 - 5"
                    },
                    {
                        "quantity": "1",
                        "name": "Life on the Beach-36\" x 48\" - 0.75\" thin gallery wrap canvas",
                        "price": "299.95",
                        "currency": "USD",
                        "sku": "2 - 6"
                    },
                    {
                        "quantity": "1",
                        "name": "View from the Mountain Tops-16\" x 20\" - 0.75\" thin gallery wrap canvas",
                        "price": "167.95",
                        "currency": "USD",
                        "sku": "5 - 3"
                    }
                ]
            }
        }
    }

  12. #12
    Join Date
    Feb 2012
    Posts
    102
    Ok so we have good news! I have figured out the problem as it was that transactions in the json request was not an array but an object so I had to use
    PHP Code:
    $request['transactions'][0] = array( 
    so that is solved. Now, I have json_decoded the result and I get two arrays but for some reason I cant figure out how to select a specific item from the array. Here is the array:
    Code:
    array(2) { ["header"]=> string(289) "HTTP/1.1 201 Created Server: Apache-Coyote/1.1 PayPal-Debug-Id: efa9e153db09a Content-Type: application/json Content-Length: 1070 DC: origin2-api.sandbox.paypal.com Date: Thu, 10 Oct 2013 21:04:12 GMT Connection: keep-alive Set-Cookie: DC=origin2-api.sandbox.paypal.com; secure " ["body"]=> object(stdClass)#4 (8) { ["id"]=> string(28) "PAY-66H55814MW6722501KJLRMSY" ["create_time"]=> string(20) "2013-10-10T21:04:11Z" ["update_time"]=> string(20) "2013-10-10T21:04:12Z" ["state"]=> string(7) "created" ["intent"]=> string(4) "sale" ["payer"]=> object(stdClass)#5 (2) { ["payment_method"]=> string(6) "paypal" ["payer_info"]=> object(stdClass)#6 (0) { } } ["transactions"]=> array(1) { [0]=> object(stdClass)#7 (3) { ["amount"]=> object(stdClass)#8 (3) { ["total"]=> string(6) "500.85" ["currency"]=> string(3) "USD" ["details"]=> object(stdClass)#9 (2) { ["subtotal"]=> string(6) "460.90" ["shipping"]=> string(5) "39.95" } } ["description"]=> string(43) "Mike and Maureen Photography - Order ID #10" ["item_list"]=> object(stdClass)#10 (1) { ["items"]=> array(2) { [0]=> object(stdClass)#11 (5) { ["name"]=> string(48) "The Bean-8" x 10" - floating frame - black frame" ["sku"]=> string(7) "20 - 13" ["price"]=> string(6) "160.95" ["currency"]=> string(3) "USD" ["quantity"]=> string(1) "1" } [1]=> object(stdClass)#12 (5) { ["name"]=> string(62) "40 Steps and a View-36" x 48" - 0.75" thin gallery wrap canvas" ["sku"]=> string(5) "7 - 6" ["price"]=> string(6) "299.95" ["currency"]=> string(3) "USD" ["quantity"]=> string(1) "1" } } } } } ["links"]=> array(3) { [0]=> object(stdClass)#13 (3) { ["href"]=> string(79) "https://api.sandbox.paypal.com/v1/payments/payment/PAY-66H55814MW6722501KJLRMSY" ["rel"]=> string(4) "self" ["method"]=> string(3) "GET" } [1]=> object(stdClass)#14 (3) { ["href"]=> string(94) "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-60F64930CV6390923" ["rel"]=> string(12) "approval_url" ["method"]=> string(8) "REDIRECT" } [2]=> object(stdClass)#15 (3) { ["href"]=> string(87) "https://api.sandbox.paypal.com/v1/payments/payment/PAY-66H55814MW6722501KJLRMSY/execute" ["rel"]=> string(7) "execute" ["method"]=> string(4) "POST" } } } }
    How do I select the ['state'] out of that mess? I am usually pretty good with PHP but for some reason I cant figure this out.

  13. #13
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,609
    When you do your json_decode(), if you add the optional 2nd parameter as true, then everything will be an array, and you won't have to worry about having objects mixed in with arrays.

    PS: If you print the resulting array out within <pre> tags, it will be easier to see the structure, too:
    PHP Code:
    echo "<pre>".print_r($the_arraytrue)."</pre>"
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles