下载安装SDK包 install the paypal/rest-api-sdk-php package
然后按以下步骤操作
1. Create a component to glue Paypal to Yii2
Create a components
folder in your @app
directory. If you are using the basic template, this is the same folder as webroot
; in the advanced template, this folder is in the app you want to enable payments in.
Create a PHP class file (CashMoney
for example) with the following content
use yii\base\Component;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
class CashMoney extends Component {
public $client_id;
public $client_secret;
private $apiContext; // paypal's API context
// override Yii's object init()
function init() {
$this->apiContext = new ApiContext(
new OAuthTokenCredential($this->client_id, $this->client_secret);
);
}
public function getContext() {
return $this->apiContext();
}
}
This is enough to get started. You may choose to add other configurations specific to PayPal later on.
2. Register your glue component with Yii2
In your app/config/main.php
(or app/config/main-local.php
), include the following to register the CashMoney
component.
'components' => [ ... 'cm' => [ // bad abbreviation of "CashMoney"; not sustainable long-term 'class' => 'app/components/CashMoney', // note: this has to correspond with the newly created folder, else you'd get a ReflectionError // Next up, we set the public parameters of the class
// You may choose to include other configuration options from PayPal // as they have specified in the documentation ], ...]
'clientId' => 'your id you can find it over your paypal develpoer account. Ypu ah to create an application', 'clientSecret' => 'your id you can find it over your paypal develpoer account. Ypu ah to create an application',
Now we have our payment component registered as CashMoney
, we can access it using Yii::$app->cm
. Cool, huh?
3. Make API calls
To Make Your First API call in Yii2,
Open the controller action in which you want to handle payments, and include the following
use Yii;
...
use PayPal\Api\CreditCard;
use PayPal\Exception\PaypalConnectionException;
class PaymentsController { // or whatever yours is called
...
public actionMakePayments { // or whatever yours is called
...
$card = new PayPalCreditCard;
$card->setType('visa')
->setNumber('4111111111111111')
->setExpireMonth('06')
->setExpireYear('2018')
->setCvv2('782')
->setFirstName('Richie')
->setLastName('Richardson');
try {
$card->create(Yii::$app->cm->getContext());
// ...and for debugging purposes
echo '<pre>';
var_dump('Success scenario');
echo $card;
} catch (PayPalConnectionException) {
echo '<pre>';
var_dump('Failure scenario');
echo $e;
}
...
}
...
}