跨 Laravel 个控制器传递 Braintree 网关
Pass Braintree gateway across Laravel controllers
我正在为一个网站设置支付方式,我想通过我的整个 Laravel 5 应用程序传递一个默认的 Braintree 网关。我的 AppServiceProvider.php
中有以下内容,但不确定它是否应该放在那里。
public function boot() {
Schema::defaultStringLength(191);
$gateway = new Braintree_Gateway([
'environment' => env('BRAINTREE_ENVIRONMENT'),
'merchantId' => env('BRAINTREE_MERCHANT_ID'),
'publicKey' => env('BRAINTREE_PUBLIC_KEY'),
'privateKey' => env('BRAINTREE_PRIVATE_KEY')
]);
}
它应该放在那个文件中吗?或者我应该只在 BaseViewController 中设置它?
这是 Laravel service container 的完美用例。
在服务提供商中(您可以创建一个新的或使用默认的 AppServiceProvider
),您可以将通用的 PaymentGateway 绑定到您的 Braintree 支付网关的特定实例:
$this->app->bind('PaymentGateway', function ($app) {
return new Braintree_Gateway([...]);
});
然后,在您的应用程序中需要使用该网关的任何地方(例如,在您的控制器之一的 store() 方法中),您可以这样做:
public function store(PaymentGateway $gateway)
{
// Do whatever you need with the gateway
$gateway->doSomething();
}
这是一种很好的方法,因为您不需要每次都创建一个新实例并手动添加凭据。您可以在需要的地方输入提示,Laravel 会自动为您解决。
我正在为一个网站设置支付方式,我想通过我的整个 Laravel 5 应用程序传递一个默认的 Braintree 网关。我的 AppServiceProvider.php
中有以下内容,但不确定它是否应该放在那里。
public function boot() {
Schema::defaultStringLength(191);
$gateway = new Braintree_Gateway([
'environment' => env('BRAINTREE_ENVIRONMENT'),
'merchantId' => env('BRAINTREE_MERCHANT_ID'),
'publicKey' => env('BRAINTREE_PUBLIC_KEY'),
'privateKey' => env('BRAINTREE_PRIVATE_KEY')
]);
}
它应该放在那个文件中吗?或者我应该只在 BaseViewController 中设置它?
这是 Laravel service container 的完美用例。
在服务提供商中(您可以创建一个新的或使用默认的 AppServiceProvider
),您可以将通用的 PaymentGateway 绑定到您的 Braintree 支付网关的特定实例:
$this->app->bind('PaymentGateway', function ($app) {
return new Braintree_Gateway([...]);
});
然后,在您的应用程序中需要使用该网关的任何地方(例如,在您的控制器之一的 store() 方法中),您可以这样做:
public function store(PaymentGateway $gateway)
{
// Do whatever you need with the gateway
$gateway->doSomething();
}
这是一种很好的方法,因为您不需要每次都创建一个新实例并手动添加凭据。您可以在需要的地方输入提示,Laravel 会自动为您解决。