PHP - Paypal支付

<?php

namespace app\common\service;

/**
 * Paypal
 * @package app\common\service
 */
class Paypal
{
    var  $config;

    public function __construct()
    {
        $this->config = array(

                'clientId' => '',
                'clientSecret' => '',
                'urlDomain' => 'https://api-m.sandbox.paypal.com'        

        );
    }

    /**
     * 统一下单接口
     * @param $order
     * @param string $trade_type
     * @return array
     */
    function generateTrade($order)
    {

        $arr = [
            'purchase_units' => [
                [
                    'reference_id' => $order['order_no'],//订单号
                    'amount' => [
                        'currency_code' => 'HKD',
                        'value' => $order['amount']
                    ]
                ]
            ],
            'intent' => 'CAPTURE',
            'payment_source' => [
                'paypal' => [
                    'experience_context' => [
                        'payment_method_preference' => 'IMMEDIATE_PAYMENT_REQUIRED',
                        'payment_method_selected' => 'PAYPAL',
                        'brand_name' => 'TEST',
                        'landing_page' => 'GUEST_CHECKOUT',//直接付款
                        'user_action' => 'PAY_NOW',
                        'return_url' => '',//付款后回调地址
                        'cancel_url' => ''//取消付款后回调地址
                    ]
                ]
            ]
        ];

        $result = $this->post(
            $this->config['urlDomain'].'v2/checkout/orders',
            ['Content-Type: application/json','Authorization: Bearer '.$this->getPaypalToken(),'PayPal-Request-Id: '.'TEST-'.$order['order_no']],
            json_encode($arr)
        );

        if(isset($result['id'])){
            return array('code' => 1, 'msg' => '创建订单成功', 'data' => $result);
        }else{

            return array('code' => 0, 'data' => $result['message']);
        }
        
        
    }

    /**
     * paypal 回调后 捕获订单付款
     */
    function paypalOrderCapture($id){

        $result = $this->post(
            $this->config['urlDomain'].'v2/checkout/orders/'.$id.'/capture',
            ['Content-Type: application/json','Authorization: Bearer '.$this->getPaypalToken(),'PayPal-Request-Id: '.'TEST-'.$id]
        );

        return $result['status'] == 'COMPLETED' ? $result : false;

    }

    /**
     * 获取paypal AccessToken
     */
    function getPaypalToken(){

        $paypal_token_config = cache("paypal-token");

        $end_time = time();


        if($paypal_token_config)
        {
            $result = $paypal_token_config;
            $end_time = $result['time'] + $result['expires_in'];
        }

        if($end_time - time() < 1800){ //更新access token

            $result = $this->post(
                $this->config['urlDomain'].'v1/oauth2/token',
                [
                    'Content-Type: application/x-www-form-urlencoded',
                    'Authorization:Basic '.base64_encode($this->config['clientId'].":".$this->config['clientSecret'])
                ],
                http_build_query(['grant_type' => 'client_credentials'])
            );

            if(isset($result['app_id'])){
                $result['time'] = time();
                cache("paypal-token",json_encode($result),3600);
            }
        }

        return isset($result['access_token']) ? $result['access_token'] : false;
    }

    /**
     * 发起POST请求
     */
    public function post($url, $headers, $request = array())
    {

        $header_res = [];
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADERFUNCTION,
            function ($curl, $header) use (&$header_res) {
                $len = strlen($header);
                $header = explode(':', $header, 2);
                if (count($header) < 2) // ignore invalid headers
                    return $len;

                $header_res[strtolower(trim($header[0]))][] = trim($header[1]);

                return $len;
            }
        );

        $response_data = curl_exec($curl);
        curl_close($curl);

        $result = json_decode($response_data, true);

        return $result;
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值