Braintree php支付(二)

本文档展示了如何在PHP中使用Braintree SDK进行支付处理。类`Braintree`包含了初始化配置、获取客户端令牌、创建交易、退款交易等核心功能。通过设置不同的环境、密钥和商户账号,该类能够处理不同货币的支付请求,并支持3D Secure验证。在交易过程中,捕获并处理可能出现的异常,确保支付流程的稳定性和安全性。
摘要由CSDN通过智能技术生成
<?php 

namespace base;
use app\service\UserService;

class Braintree
{
	protected $environment;
	protected $merchantId;
	protected $publicKey;
	protected $privateKey;
	protected $gateway;
	protected $merchantAccountId;
	protected $merchantAccountArr = [
	    'AUD' => 'AUD',
	    'CAD' => 'CAD',
	    'EUR' => 'EUR',
	    'GBP' => 'GBP',
	    'USD' => 'USD',
    ];

	public function __construct()
	{
		$this->environment = 'sandbox';
		$this->merchantId = 'xxxx';
		$this->publicKey = 'xxxx';
		$this->privateKey = 'xxxxxx';
		
		$this->gateway = new \Braintree\Gateway([
			'environment' => $this->environment,
			'merchantId' => $this->merchantId,
			'publicKey' => $this->publicKey,
			'privateKey' => $this->privateKey
		]);
//        $this->gateway->applePay()->registerDomain('xxx.xxxx.com');
	}

	public function getClientToken()
	{
		try {
			// pass $clientToken to your front-end
			$clientToken = $this->gateway->clientToken()->generate();

		} catch (\Exception $e) {
			return DataReturn(' Error:' . $e->getMessage(), -1);
		}

		return DataReturn('success', 0, $clientToken);
	}

	public function checkout($amount, $nonce, $deviceDataFromTheClient, $currency, $orderId, $threeDSecure = false)
	{
		if ($amount <= 0 || empty($nonce)) {
			return DataReturn('Incorrect payment parameters', -1);
		}
		$this->setMerchantAccountId($currency);

		try {

			if ($threeDSecure) {
				$result = $this->gateway->transaction()->sale([
				    'amount' => $amount,
                    'orderId' => $orderId,
				    'paymentMethodNonce' => $nonce,
				    'deviceData' => $deviceDataFromTheClient,
				    'merchantAccountId' => $this->merchantAccountId,
				    'options' => [
				        'submitForSettlement' => true,
						'threeDSecure' => [
							'required' => true
						],	        
				    ]
				]);
			} else {
				$result = $this->gateway->transaction()->sale([
				    'amount' => $amount,
                    'orderId' => $orderId,
				    'paymentMethodNonce' => $nonce,
				    'deviceData' => $deviceDataFromTheClient,
                    'merchantAccountId' => $this->merchantAccountId,
				    'options' => [
				        'submitForSettlement' => true
				    ]
				]);
			}

			if ($result->success && !is_null($result->transaction)) {
			    // $transaction = $result->transaction;

			    return DataReturn('success', 0, $result);

			} else {
			    $errorString = "";

			    foreach($result->errors->deepAll() as $error) {
			        $errorString .= 'Error: ' . $error->code . ": " . $error->message . "\n";
			    }

			    if (empty($errorString)) {
			    	$errorString = $result->message;
			    }

			    return DataReturn($errorString, -1, $result);
			}
		} catch (\Exception $e) {
			return DataReturn(' Error:' . $e->getMessage(), -1);
		}
	}

	public function transaction($id)
	{
        $transaction = $this->gateway->transaction()->find($id);

        $transactionSuccessStatuses = [
            \Braintree\Transaction::AUTHORIZED,
            \Braintree\Transaction::AUTHORIZING,
            \Braintree\Transaction::SETTLED,
            \Braintree\Transaction::SETTLING,
            \Braintree\Transaction::SETTLEMENT_CONFIRMED,
            \Braintree\Transaction::SETTLEMENT_PENDING,
            \Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT
        ];

        if (in_array($transaction->status, $transactionSuccessStatuses)) {
            $header = "Sweet Success!";
            $icon = "success";
            $message = "Your test transaction has been successfully processed. See the Braintree API response and try again.";
        } else {
            $header = "Transaction Failed";
            $icon = "fail";
            $message = "Your test transaction has a status of " . $transaction->status . ". See the Braintree API response and try again.";
        }
        return DataReturn($header, 0, $transaction);
	}

    public function refund($trade_no, $amount)
    {
        try {
            $transaction = $this->gateway->transaction()->find($trade_no);
            if($transaction->status == 'submitted_for_settlement'){
                //如果交易尚未结算 暂不让退款
                return DataReturn('braintree尚未结算,暂不能退款', -1);
            }
            $response = $this->gateway->transaction()->refund($trade_no, $amount);
            if($response->success) {
                return DataReturn('braintree_refund_success');
            }else{
                return DataReturn('braintree_refund_fail:'. $response->message, -1);
            }
        } catch (\Exception $e) {
            return DataReturn(' Error:' . $e->getMessage(), -1);
        }
	}

    public function setMerchantAccountId($currency)
    {
        $currency = strtoupper($currency);
        if (!isset($this->merchantAccountArr[$currency])) {
            throw new \Exception('Merchant account id error');
        }
        $this->merchantAccountId = $this->merchantAccountArr[$currency];
    }
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值