1

我正在上课用贝宝付款。

通过该函数获取令牌是getToken()有效的,它会产生一个很好的响应(根据文档)。

但是,当我使用该令牌建立与令牌相同的付款时sendAPICall();它只返回一个空字符串(根据 var_dump() )。

如果我从 api-information 复制确切的 curl 命令并粘贴 Beare-token;有用。所以我的 API 调用出了点问题......

显然我错过了一些东西。谁能指出我的错误?

获取 Bearer-token 的函数:

public function getToken(){

    $headers = array(
        "Accept-Language" => 'en_US',   
        "Accept" => "application/json"
        );

    $t = json_decode($this->sendAPICall('grant_type=client_credentials', '/oauth2/token', $headers, true));
    if($t->error){
        $this->error = $t->error_description;
        $this->token = NULL;
        return false;
    }else{
        $this->token = $t; 
        return true;
    }

}

检查是否有可用令牌后应付款的功能。

public function makePayment(){
    $this->getToken();

  if($this->error){
      return false;
  }else{

        $d = '{"intent":"sale",
                  "redirect_urls":{
                    "return_url":"'.$this->config['returnURL'].'",
                    "cancel_url":"'.$this->config['cancelURL'].'"
                  },
                  "payer":{
                    "payment_method":"paypal"
                  },
                  "transactions":[
                    {
                      "amount":{
                        "total":"'.$this->amount.'",
                        "currency":"'.$this->config['currency'].'"
                      },
                        "description":"'.$this->description.'"
                    }
                  ]
                }';
        $headers = array(   "Authorization" => $this->token->token_type . ' ' . $this->token->access_token, 
                            "Content-type" => "application/json"
                            );
        return $this->sendAPICall(urlencode($d), '/payments/payment', $headers, false);

    }
 }

当然,与 paypal API 的连接,我使用 $auth 布尔值来区分发送 userpwd 或使用令牌:

private function sendAPICall($data, $url, $headers, $auth=true){
    $ch = curl_init();
    $options = array(   CURLOPT_URL => $this->config['endpoint'].$url,
                        CURLOPT_POST => true,
                        CURLOPT_POSTFIELDS => $data,
                        CURLOPT_RETURNTRANSFER => true

                    );
        if($auth){
            $options[CURLOPT_USERPWD] = $this->config['client_id'].':'.$this->config['client_secret'];
        };
    curl_setopt_array($ch, $options);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    return curl_exec($ch);



}
4

1 回答 1

0

看起来此代码段未正确传递 HTTP 标头。CURLOPT_HTTPHEADER 采用具有“headername: value”形式的值的单维度数组。你需要

$headers = array( "授权:" . $this->token->token_type . ' ' . $this->token->access_token, "Content-type: application/json" );

还要考虑

  1. 检查 curl_errno($ch) / curl_error($ch) 和 HTTP 响应代码 (curl_getinfo($ch, CURLINFO_HTTP_CODE)) 以查看调用是否成功。
  2. 将请求数据创建为关联数组并在调用 sendAPICall() 时使用 json_encode($data)。这比手动操作 JSON 字符串要容易得多。
于 2013-08-29T09:10:40.550 回答