2020 PayPal 最新 php curl 调用接口封装

    技术2022-07-11  69

    场景:在对接PayPal支付时,遇到了很多小坑,因为官方提供的是bash脚本,和php的写法还是有点区别,以此记录保留,望后人少走弯路。(官方文档)

    1.获取access token,这个token是调用其他REST API身份验证的前提。

    public function getAccessToken() { $url = "https://api.sandbox.paypal.com/v1/oauth2/token"; $cient_id = $this->_setting['client_id']; $secret = $this->_setting['secret']; $headers_array[] = "Content-Type: application/json"; $data = array( 'grant_type' => 'client_credentials' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 500); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_array); curl_setopt($ch, CURLOPT_USERPWD, "$cient_id:$secret"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); $response = curl_exec($ch); $nvpResArray = json_decode($response,true); $token = $nvpResArray['access_token']; curl_close($ch); return $token; }

    其中cient_id 和 secret 要登录账号后台获取。

    2.调用其他REST API,用获取到的token进行Bearer身份验证。(例如获取订单的支付信息流水,这里的$id指订单流水,$token就是上面获取到的access token)

    public function getPaymentDetail($id,$token) { $url = "https://api.sandbox.paypal.com/v2/payments/captures/".$id; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 500); $headers_array[] = "Content-Type: application/json"; $headers_array[] = "Authorization: Bearer ".$token; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_array); $response = curl_exec($ch); $nvpResArray = json_decode($response,true); curl_close($ch); return $nvpResArray; }

     

    Processed: 0.010, SQL: 9