PaypalPayment.php 1.86 KB
<?php
/**
 * Created by PhpStorm.
 * User: lishuai
 * Date: 2022/2/15
 * Time: 4:23 PM
 */

namespace App\Payment;

use App\Models\Order;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Redis;

class PaypalPayment implements PaymentInterface
{

    const IS_SANDBOX = true;

    public $authUrl = 'https://api-m.sandbox.paypal.com/v1/oauth2/token';

    public $paySandboxUrl = 'https://api-m.sandbox.paypal.com';

    public $payUrl = 'https://api-m.paypal.com';

    public $clientId = 'AdDRE91WSp5q1fYLODpJduc2mRjA_v6E205SvkfVSOgvr98xLeyDCHY4OPAaSFMK1SHYOfJ4TksHSX1-';
    public $secret = 'EDoy_PVrFyobWt9DzAMRMikJwWCXenkWSx9CGFz0MxHt3a8fs6v-LnORMilIbftb2GwBKxOoTVZNBHNR';

    /** 访问令牌*/
    public $accessToken;

    public function __construct()
    {
        // 初始化时做一些准备工作
        $redis = Redis::connection();
        $access_token = $redis->get('paypal:access_token');
        if ($access_token){
            $this->accessToken = $access_token;
        }else{
            $client = new Client([
                'headers'=>[
                    'Content-Type' => 'application/x-www-form-urlencoded',
                    'Accept'=>'application/json',
                ]
            ]);

            $response = $client->post($this->authUrl,[
                'form_params'=>['grant_type' => 'client_credentials'],
                'auth' => [$this->clientId, $this->secret],
            ]);
            $body = $response->getBody();
            $content = json_decode($body->getContents(),true);
            $this->accessToken = $content['access_token'];

            $redis->setex('paypal:access_token',$content['expires_in'],$content['access_token']);
        }
    }

    public function prepare(Order $order)
    {
        // 在PayPal上创建一个订单,它会返回一个订单对象,它有一个订单id


        return $this->accessToken;
    }
}