我在一个OctoberCMS组件中工作,在工作时遇到了一些问题。看看这个代码:
class Payment extends ComponentBase
{
/**
* This hold the amount with PayPal fee and discount applied and pass back to template
* @var float
*/
public $amountToReload;
public function onAmountChange()
{
$amount = post('amount');
if (empty($amount)) {
throw new 'Exception(sprintf('Por favor introduzca un valor.'));
}
$this->amountToReload = round($amount - ($amount * (float) Settings::get('ppal_fee') - (float) Settings::get('ppal_discount')), 2);
return ['#amountToReload' => $this->amountToReload];
}
public function onRun()
{
$step = $this->param('step');
$sandboxMode = Settings::get('sandbox_enabled');
switch ($step) {
case "step2":
echo $this->amountToReload;
$params = [
'username' => $sandboxMode ? Settings::get('ppal_api_username_sandbox') : Settings::get('ppal_api_username'),
'password' => $sandboxMode ? Settings::get('ppal_api_password_sandbox') : Settings::get('ppal_api_password'),
'signature' => $sandboxMode ? Settings::get('ppal_api_signature_sandbox') : Settings::get('ppal_api_signature'),
'testMode' => $sandboxMode,
'amount' => $this->amountToReload,
'cancelUrl' => 'www.xyz.com/returnUrl', // should point to returnUrl method on this class
'returnUrl' => 'www.xyz.com/cancelUrl', // should point to cancelUrl method on this class
'currency' => 'USD'
];
$response = Omnipay::purchase($params)->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response);
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
return $response->getRedirectResponse();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
break;
default:
break;
}
$this->page['step'] = $step;
}
public function cancelPayment()
{
// handle payment cancel
}
}
如果我在类的顶部有$amountToReload
作为公共声明的var,并在onAmountChange()
方法中为其设置值?那么在onRun()
方法中,这个var不应该保持它的设置值吗?为什么它到达NULL或没有值?我是来自Symfony的Laravel的新手。保持var值的最佳方法是什么,这样我就可以在整个类中使用它而不会出现问题?
作为这篇文章的第二部分,我需要为cancelPayment()
方法生成一个有效的路由,这将在以下行中进行:
'returnUrl' => 'www.xyz.com/cancelUrl', // should point to cancelUrl method on this class
如何在Laravel中创建一个可能带有参数的有效URL?使用URL帮助程序?使用路线?哪一个?
您的方法很好,因为amountToReload
被声明为类属性(尽管您可能希望将该属性设为protected
,除非您明确希望将其公开)。唯一的问题是需要在onRun()
之前调用方法onAmountChange()
,以便设置amountToReload
的值。
至于生成URL,最简单的方法是使用url()
:
url('foo/bar', $parameters = array(), $secure = null);
有关更多信息,请查看Laravel Helpers文档。