2013-10-09 11 views
2

Я новичок в завитках, поэтому я использую код, найденный в блоге разработчиков Paypal, и мне сложно с ним работать. Вот код, я используюPaypal REST Api implmentation

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', $postvals, true); 
     $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($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
      curl_setopt($ch, CURLOPT_USERPWD, CLIENT_ID . ":" .CLIENT_SECRET); 
      curl_setopt($ch, CURLOPT_SSLVERSION, 3); 
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 
     //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($response, 0, curl_getinfo($ch,CURLINFO_HEADER_SIZE)); 
     $body = json_decode(substr($response, curl_getinfo($ch,CURLINFO_HEADER_SIZE))); 
     curl_close($ch); 

     return array('header' => $header, 'body' => $body); 
    } 

    // Function for Processing Payment 
    function process_payment($request) { 
     $postvals = $request; 
     $uri = PAYMENT_URI . "v1/payments/payment"; 
     return self::curl($uri, 'POST', $postvals); 
    } 
} 

if (isset($_SESSION['payment_type']) && ($_SESSION['payment_type'] == 'paypal')) { // User has chosen to pay with Paypal. 


    // Retrive Shopping cart contents 
    $r = mysqli_query($dbc, "CALL get_shopping_cart_contents('$uid')"); 

    $request = array(
     'intent' => 'sale', 
     'redirect_urls' => array(
      'return_url' =>'http://store.example.com/final', 
      'cancel_url' =>'http://store.example.com/payment' 
     ), 
     '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' =>'Mike and Maureen Photography - Order ID #'.$order_id.'' 
     ) 
    ); 

    while ($items = mysqli_fetch_array($r, MYSQLI_ASSOC)) { 

     $newitems = array(
      'quantity' =>''.$items['quantity'].'', 
      'name' =>''.$items['name'].'', 
      'price' =>''.get_price($items['price'],$items['sales_price']).'', 
      'currency' =>'USD' 
     ); 
     $request['transactions']['amount']['item_list']['items'][] = $newitems; 
    } 

    $request = json_encode($request); 

    process_payment($request); 
} 

Я хорошо с PHP, но весь этот класс, открытый/закрытый материал бросает меня. Могу ли я использовать этот код без этого или он откроет меня до неприятностей? Как запустить функцию process_payment без ее возникновения ошибки. Я получаю «Неустранимая ошибка: вызов неопределенной функции process_payment()»

Разве я не определял функцию в классе paypal? Я прочитал документацию на paypal, и я не могу понять, что я делаю неправильно. Любая помощь будет большой.

+1

Вы не можете вызвать 'process_payment()'. Вы должны либо использовать экземпляр класса 'paypal', либо сделать статическую функцию так, чтобы ее можно было вызывать извне класса. –

+0

Хорошо, я понял эту порцию, теперь я получаю сообщение об ошибке: «Входящий запрос JSON не сопоставляется с запросом API» Есть ли способ проверить, должен ли я отправлять свой код здесь? Я использовал $ paypal = новый PayPal(); \t \t $ result = $ paypal-> process_payment ($ request); – McCoy

ответ

0

Функция process_payment() является частью класса paypal. Чтобы назвать это, вам нужно будет сделать один из способов, описанных здесь: https://stackoverflow.com/a/4216347/1715048

+0

Спасибо, я понял, что – McCoy