PayPal REST API - 结算协议不会返回令牌

时间:2017-02-17 07:36:01

标签: paypal-rest-sdk paypal-subscriptions paypal

我尝试使用REST API创建PayPal定期订阅(信用卡):

制定结算方案 - https://developer.paypal.com/docs/api/quickstart/create-billing-plan/

制定帐单协议 - https://developer.paypal.com/docs/api/quickstart/create-billing-agreement/

我正在测试和使用API​​,所以我创建了两个文件plan.php和agreement.php。

plan.php 是我生成计划ID并在 agreement.php 中静态传递的地方。

plan.php

<?php

require 'vendor/autoload.php';

$apiContext = new \PayPal\Rest\ApiContext(
  new \PayPal\Auth\OAuthTokenCredential(
    'Application-ID',    
    'Secret-ID'  
  )
);

use PayPal\Api\ChargeModel;
use PayPal\Api\Currency;
use PayPal\Api\MerchantPreferences;
use PayPal\Api\PaymentDefinition;
use PayPal\Api\Plan;
use PayPal\Api\Patch;
use PayPal\Api\PatchRequest;
use PayPal\Common\PayPalModel;

use PayPal\Api\Agreement;
use PayPal\Api\Payer;
use PayPal\Api\ShippingAddress;
use PayPal\Api\CreditCard;
use PayPal\Api\FundingInstrument;

    $plan = new Plan();
    $plan->setName('T-Shirt of the Month Club Plan')
      ->setDescription('Template creation.')
      ->setType('fixed');

    // Set billing plan definitions
    $paymentDefinition = new PaymentDefinition();
    $paymentDefinition->setName('Regular Payments')
      ->setType('REGULAR')
      ->setFrequency('Month')
      ->setFrequencyInterval('2')
      ->setCycles('12')
      ->setAmount(new Currency(array('value' => 100, 'currency' => 'USD')));

// Set charge models
$chargeModel = new ChargeModel();
$chargeModel->setType('SHIPPING')
  ->setAmount(new Currency(array('value' => 10, 'currency' => 'USD')));
$paymentDefinition->setChargeModels(array($chargeModel));

// Set merchant preferences
$merchantPreferences = new MerchantPreferences();
$merchantPreferences->setReturnUrl('http://localhost:3000/processagreement')
  ->setCancelUrl('http://localhost:3000/cancel')
  ->setAutoBillAmount('yes')
  ->setInitialFailAmountAction('CONTINUE')
  ->setMaxFailAttempts('0')
  ->setSetupFee(new Currency(array('value' => 1, 'currency' => 'USD')));

$plan->setPaymentDefinitions(array($paymentDefinition));
$plan->setMerchantPreferences($merchantPreferences);




//create plan
try {
  $createdPlan = $plan->create($apiContext);

  try {
    $patch = new Patch();
    $value = new PayPalModel('{"state":"ACTIVE"}');
    $patch->setOp('replace')
      ->setPath('/')
      ->setValue($value);
    $patchRequest = new PatchRequest();
    $patchRequest->addPatch($patch);
    $createdPlan->update($patchRequest, $apiContext);
    $plan = Plan::get($createdPlan->getId(), $apiContext);

    // Output plan id
    echo $plan->getId();
  } catch (PayPal\Exception\PayPalConnectionException $ex) {
    echo $ex->getCode();
    echo $ex->getData();
    die($ex);
  } catch (Exception $ex) {
    die($ex);
  }
} catch (PayPal\Exception\PayPalConnectionException $ex) {
  echo $ex->getCode();
  echo $ex->getData();
  die($ex);
} catch (Exception $ex) {
  die($ex);
}

<?php require 'vendor/autoload.php'; $apiContext = new \PayPal\Rest\ApiContext( new \PayPal\Auth\OAuthTokenCredential( 'Application-ID', 'Secret-ID' ) ); use PayPal\Api\ChargeModel; use PayPal\Api\Currency; use PayPal\Api\MerchantPreferences; use PayPal\Api\PaymentDefinition; use PayPal\Api\Plan; use PayPal\Api\Patch; use PayPal\Api\PatchRequest; use PayPal\Common\PayPalModel; use PayPal\Api\Agreement; use PayPal\Api\Payer; use PayPal\Api\ShippingAddress; use PayPal\Api\CreditCard; use PayPal\Api\FundingInstrument; $plan = new Plan(); $plan->setName('T-Shirt of the Month Club Plan') ->setDescription('Template creation.') ->setType('fixed'); // Set billing plan definitions $paymentDefinition = new PaymentDefinition(); $paymentDefinition->setName('Regular Payments') ->setType('REGULAR') ->setFrequency('Month') ->setFrequencyInterval('2') ->setCycles('12') ->setAmount(new Currency(array('value' => 100, 'currency' => 'USD'))); // Set charge models $chargeModel = new ChargeModel(); $chargeModel->setType('SHIPPING') ->setAmount(new Currency(array('value' => 10, 'currency' => 'USD'))); $paymentDefinition->setChargeModels(array($chargeModel)); // Set merchant preferences $merchantPreferences = new MerchantPreferences(); $merchantPreferences->setReturnUrl('http://localhost:3000/processagreement') ->setCancelUrl('http://localhost:3000/cancel') ->setAutoBillAmount('yes') ->setInitialFailAmountAction('CONTINUE') ->setMaxFailAttempts('0') ->setSetupFee(new Currency(array('value' => 1, 'currency' => 'USD'))); $plan->setPaymentDefinitions(array($paymentDefinition)); $plan->setMerchantPreferences($merchantPreferences); //create plan try { $createdPlan = $plan->create($apiContext); try { $patch = new Patch(); $value = new PayPalModel('{"state":"ACTIVE"}'); $patch->setOp('replace') ->setPath('/') ->setValue($value); $patchRequest = new PatchRequest(); $patchRequest->addPatch($patch); $createdPlan->update($patchRequest, $apiContext); $plan = Plan::get($createdPlan->getId(), $apiContext); // Output plan id echo $plan->getId(); } catch (PayPal\Exception\PayPalConnectionException $ex) { echo $ex->getCode(); echo $ex->getData(); die($ex); } catch (Exception $ex) { die($ex); } } catch (PayPal\Exception\PayPalConnectionException $ex) { echo $ex->getCode(); echo $ex->getData(); die($ex); } catch (Exception $ex) { die($ex); }

agreement.php


    

// Autoload SDK package for composer based installations require 'vendor/autoload.php'; $apiContext = new \PayPal\Rest\ApiContext( new \PayPal\Auth\OAuthTokenCredential( 'Application-ID', 'Secret-ID' ) ); use PayPal\Api\ChargeModel; use PayPal\Api\Currency; use PayPal\Api\MerchantPreferences; use PayPal\Api\PaymentDefinition; use PayPal\Api\Plan; use PayPal\Api\Patch; use PayPal\Api\PatchRequest; use PayPal\Common\PayPalModel; use PayPal\Api\Agreement; use PayPal\Api\Payer; use PayPal\Api\ShippingAddress; use PayPal\Api\CreditCard; use PayPal\Api\FundingInstrument; // Create new agreement // $agreement = new Agreement(); // $agreement->setName('Base Agreement') // ->setDescription('Basic Agreement') // ->setStartDate('2017-02-17T9:45:04Z'); // // Set plan id // $plan = new Plan(); // $plan->setId('P-1CD306827C2019339JKC6JDY'); // $agreement->setPlan($plan); // // Add payer type // $payer = new Payer(); // $payer->setPaymentMethod('paypal'); // $agreement->setPayer($payer); // // Adding shipping details // $shippingAddress = new ShippingAddress(); // $shippingAddress->setLine1('111 First Street') // ->setCity('Saratoga') // ->setState('CA') // ->setPostalCode('95070') // ->setCountryCode('US'); // $agreement->setShippingAddress($shippingAddress); //create new agreement $agreement = new Agreement(); $agreement->setName('Base Agreement') ->setDescription('Basic Agreement') ->setStartDate('2017-02-17T9:45:04Z'); // Set plan id $plan = new Plan(); $plan->setId('P-1CD306827C2019339JKC6JDY'); $agreement->setPlan($plan); // Create credit card object and set funding instrument $card = new CreditCard(); $card->setType("visa") ->setNumber("4250448816997456") ->setExpireMonth("06") ->setExpireYear("2018") ->setCvv2("012") ->setFirstName("Joe") ->setLastName("Shopper"); $fi = new FundingInstrument(); $fi->setCreditCard($card); // Set payer to process credit card $payer = new Payer(); $payer->setPaymentMethod("credit_card") ->setFundingInstruments(array($fi)); $agreement->setPayer($payer); // Adding shipping details $shippingAddress = new ShippingAddress(); $shippingAddress->setLine1('111 First Street') ->setCity('Saratoga') ->setState('CA') ->setPostalCode('95070') ->setCountryCode('US'); $agreement->setShippingAddress($shippingAddress); $agreement = $agreement->create($apiContext); // print_r($agreement); exit(); if (isset($_GET['success']) && $_GET['success'] == 'true') { $token = $_GET['token']; $agreement = new \PayPal\Api\Agreement(); try { // Execute agreement $agreement->execute($token, $apiContext); } catch (PayPal\Exception\PayPalConnectionException $ex) { echo $ex->getCode(); echo $ex->getData(); die($ex); } catch (Exception $ex) { die($ex); } } else { echo "user canceled agreement"; }

// Autoload SDK package for composer based installations require 'vendor/autoload.php'; $apiContext = new \PayPal\Rest\ApiContext( new \PayPal\Auth\OAuthTokenCredential( 'Application-ID', 'Secret-ID' ) ); use PayPal\Api\ChargeModel; use PayPal\Api\Currency; use PayPal\Api\MerchantPreferences; use PayPal\Api\PaymentDefinition; use PayPal\Api\Plan; use PayPal\Api\Patch; use PayPal\Api\PatchRequest; use PayPal\Common\PayPalModel; use PayPal\Api\Agreement; use PayPal\Api\Payer; use PayPal\Api\ShippingAddress; use PayPal\Api\CreditCard; use PayPal\Api\FundingInstrument; // Create new agreement // $agreement = new Agreement(); // $agreement->setName('Base Agreement') // ->setDescription('Basic Agreement') // ->setStartDate('2017-02-17T9:45:04Z'); // // Set plan id // $plan = new Plan(); // $plan->setId('P-1CD306827C2019339JKC6JDY'); // $agreement->setPlan($plan); // // Add payer type // $payer = new Payer(); // $payer->setPaymentMethod('paypal'); // $agreement->setPayer($payer); // // Adding shipping details // $shippingAddress = new ShippingAddress(); // $shippingAddress->setLine1('111 First Street') // ->setCity('Saratoga') // ->setState('CA') // ->setPostalCode('95070') // ->setCountryCode('US'); // $agreement->setShippingAddress($shippingAddress); //create new agreement $agreement = new Agreement(); $agreement->setName('Base Agreement') ->setDescription('Basic Agreement') ->setStartDate('2017-02-17T9:45:04Z'); // Set plan id $plan = new Plan(); $plan->setId('P-1CD306827C2019339JKC6JDY'); $agreement->setPlan($plan); // Create credit card object and set funding instrument $card = new CreditCard(); $card->setType("visa") ->setNumber("4250448816997456") ->setExpireMonth("06") ->setExpireYear("2018") ->setCvv2("012") ->setFirstName("Joe") ->setLastName("Shopper"); $fi = new FundingInstrument(); $fi->setCreditCard($card); // Set payer to process credit card $payer = new Payer(); $payer->setPaymentMethod("credit_card") ->setFundingInstruments(array($fi)); $agreement->setPayer($payer); // Adding shipping details $shippingAddress = new ShippingAddress(); $shippingAddress->setLine1('111 First Street') ->setCity('Saratoga') ->setState('CA') ->setPostalCode('95070') ->setCountryCode('US'); $agreement->setShippingAddress($shippingAddress); $agreement = $agreement->create($apiContext); // print_r($agreement); exit(); if (isset($_GET['success']) && $_GET['success'] == 'true') { $token = $_GET['token']; $agreement = new \PayPal\Api\Agreement(); try { // Execute agreement $agreement->execute($token, $apiContext); } catch (PayPal\Exception\PayPalConnectionException $ex) { echo $ex->getCode(); echo $ex->getData(); die($ex); } catch (Exception $ex) { die($ex); } } else { echo "user canceled agreement"; }

然而,它没有返回令牌,并且未设置成功变量。我打印了 $ agreement 变量,下面是回复:

为什么我无法获得令牌?

提前致谢。

1 个答案:

答案 0 :(得分:0)

这是您的解决方案

1)创建计划时,您需要将返回网址设为Execute.php。

2)您将该计划ID传递给了结算协议

3)您的agreement.php print_r($ agreement-&gt; toArray());

4)买方批准协议时,它会重定向到Execute.php,即创建计划时返回的Url集。

5)在execute.php中,您将获得令牌并成功为真。

您正在添加执行协议的代码 协议创造。这就是你没有获得成功的原因, 您可以在买方批准后按ID执行结算协议。 检查以下链接。

https://developer.paypal.com/docs/api/payments.billing-agreements

所以现在你应该从agreement.php中删除执行代码并添加execute.php 用这个

<?php

// #Execute Agreement
// This is the second part of CreateAgreement Sample.
// Use this call to execute an agreement after the buyer approves it
require __DIR__ . '/../bootstrap.php';

// ## Approval Status
// Determine if the user accepted or denied the request
if (isset($_GET['success']) && $_GET['success'] == 'true') {
    $token = $_GET['token'];
    $agreement = new \PayPal\Api\Agreement();
    try {
        // ## Execute Agreement
        // Execute the agreement by passing in the token
        $agreement->execute($token, $apiContext);
    } catch (Exception $ex) {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printError("Executed an Agreement", "Agreement", $agreement->getId(), $_GET['token'], $ex);
        exit(1);
    }

    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printResult("Executed an Agreement", "Agreement", $agreement->getId(), $_GET['token'], $agreement);

    // ## Get Agreement
    // Make a get call to retrieve the executed agreement details
    try {
        $agreement = \PayPal\Api\Agreement::get($agreement->getId(), $apiContext);
    } catch (Exception $ex) {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
        ResultPrinter::printError("Get Agreement", "Agreement", null, null, $ex);
        exit(1);
    }

    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printResult("Get Agreement", "Agreement", $agreement->getId(), null, $agreement);
} else {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printResult("User Cancelled the Approval", null);
}