如何实现循环扣款
分四个步骤:
-
创建升级计划,并激活;
创建订阅(创建Agreement),然后将跳转到Paypal的网站等待用户同意;
用户同意后,执行订阅
获取扣款帐单
1.创建升级计划
升级计划对应Plan这个类。这一步有几个注意点:
升级计划创建后,处于CREATED状态,必须将状态修改为ACTIVE才能正常使用。 Plan有PaymentDefinition和MerchantPreferences两个对象,这两个对象都不能为空; 如果想创建TRIAL类型的计划,该计划还必须有配套的REGULAR的支付定义,否则会报错; 看代码有调用一个setSetupFee(非常,非常,非常重要)方法,该方法设置了完成订阅后首次扣款的费用,而Agreement对象的循环扣款方法设置的是第2次开始时的费用。以创建一个Standard的计划为例,其参数如下:
$param = [ "name" => "standard_monthly", "display_name" => "Standard Plan", "desc" => "standard Plan for one month", "type" => "REGULAR", "frequency" => "MONTH", "frequency_interval" => 1, "cycles" => 0, "amount" => 20, "currency" => "USD" ];
创建并激活计划代码如下:
//上面的$param例子是个数组,我的实际应用传入的实际是个对象,用户理解下就好。
public function createPlan($param)
{
$apiContext = $this->getApiContext();
$plan = new Plan();
// # Basic Information
// Fill up the basic information that is required for the plan
$plan->setName($param->name)
->setDescription($param->desc)
->setType('INFINITE');//例子总是设置为无限循环
// # Payment definitions for this billing plan.
$paymentDefinition = new PaymentDefinition();
// The possible values for such setters are mentioned in the setter method documentation.
// Just open the class file. e.g. lib/PayPal/Api/PaymentDefinition.php and look for setFrequency method.
// You should be able to see the acceptable values in the comments.
$paymentDefinition->setName($param->name)
->setType($param->type)
->setFrequency($param->frequency)
->setFrequencyInterval((string)$param->frequency_interval)
->setCycles((string)$param->cycles)
->setAmount(new Currency(array('value' => $param->amount, 'currency' => $param->currency)));
// Charge Models
$chargeModel = new ChargeModel();
$chargeModel->setType('TAX')
->setAmount(new Currency(array('value' => 0, 'currency' => $param->currency)));
$returnUrl = config('payment.returnurl');
$merchantPreferences = new MerchantPreferences();
$merchantPreferences->setReturnUrl("$returnUrl?success=true")
->setCancelUrl("$returnUrl?success=false")
->setAutoBillAmount("yes")
->setInitialFailAmountAction("CONTINUE")
->setMaxFailAttempts("0")
->setSetupFee(new Currency(array('value' => $param->amount, 'currency' => 'USD')));
$plan->setPaymentDefinitions(array($paymentDefinition));
$plan->setMerchantPreferences($merchantPreferences);
// For Sample Purposes Only.
$request = clone $plan;
// ### Create Plan
try {
$output = $plan->create($apiContext);
} catch (Exception $ex) {
return false;
}
$patch = new Patch();
$value = new PayPalModel('{"state":"ACTIVE"}');
$patch->setOp('replace')
->setPath('/')
->setValue($value);
$patchRequest = new PatchRequest();
$patchRequest->addPatch($patch);
$output->update($patchRequest, $apiContext);
return $output;
}







