Php 如何使用yii2的PayPal扩展在yii2中集成支付网关

Php 如何使用yii2的PayPal扩展在yii2中集成支付网关,php,paypal,yii2,yii-extensions,Php,Paypal,Yii2,Yii Extensions,如何在yii2中使用paypal扩展。我正在使用此链接 我安装了扩展名并在配置文件中添加了代码 但没有更多的信息表明下一步该怎么做。所以请帮帮我 谢谢这是我的解决方案,它与Yi2 advanced tempalte合作 我把这个类marciocamello/yii2 paypal/paypal.php从vendor文件夹移动到common/component/paypal.php 您必须在“组件”部分的frontend\config\main.php中“包括”common\components\

如何在yii2中使用paypal扩展。我正在使用此链接
我安装了扩展名并在配置文件中添加了代码

但没有更多的信息表明下一步该怎么做。所以请帮帮我


谢谢

这是我的解决方案,它与Yi2 advanced tempalte合作

我把这个类marciocamello/yii2 paypal/paypal.php从vendor文件夹移动到common/component/paypal.php

您必须在“组件”部分的frontend\config\main.php中“包括”common\components\paypal:

 'components' => [
    'paypal'=> [
        'class'        => 'common\components\Paypal',
        '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',
        'isProduction' => false,
         // This is config file for the PayPal system
         'config'       => [
             'http.ConnectionTimeOut' => 30,
             'http.Retry'             => 1,
             'mode'                   => \common\components\Paypal::MODE_SANDBOX, 
             'log.LogEnabled'         => YII_DEBUG ? 1 : 0,
             'log.FileName'           => '@runtime/logs/paypal.log',
             'log.LogLevel'           => \common\components\Paypal::LOG_LEVEL_INFO,
        ]
    ],
],

在第11行的PPHttpConfig.php中,我更改了以下行

    //CURLOPT_SSLVERSION => 3,
    CURLOPT_SSLVERSION => 'CURL_SSLVERSION_TLSv1',
在第48-52行的PPLoggingManager.php中,i'v硬编码了日志路径

if($this->isLoggingEnabled) {
        $this->loggerFile = $_SERVER['DOCUMENT_ROOT'].'/domain/frontend/runtime/logs/paypal.log';//($config['log.FileName']) ? $config['log.FileName'] : ini_get('error_log');
        $loggingLevel = strtoupper($config['log.LogLevel']);
        $this->loggingLevel = (isset($loggingLevel) && defined(__NAMESPACE__."\\PPLoggingLevel::$loggingLevel")) ? constant(__NAMESPACE__."\\PPLoggingLevel::$loggingLevel") : PPLoggingManager::DEFAULT_LOGGING_LEVEL;
    }
在站点控制器i'v中调用组件函数

      echo '<pre/>';
  print_r(Yii::$app->paypal->payDemo());  
  exit();
我总是有400个错误,因为我有价格格式的问题,我用number\u格式函数修复了它

    $amount = 16;    
$formattedAmount = number_format($amount,2);
        $payer = new Payer();
        $payer->setPayment_method("paypal");
        $item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
    ->setCurrency('USD')
    ->setQuantity(1)
    ->setPrice($formattedAmount);
$item2 = new Item();
$item2->setName('Granola bars')
    ->setCurrency('USD')
    ->setQuantity(1)
    ->setPrice($formattedAmount);
$itemList = new ItemList();

$itemList->setItems(array($item1, $item2));
        //  $amountDetails = new Details();
        // $amountDetails->setSubtotal('7');
        // $amountDetails->setTax('0.00');
        // $amountDetails->setShipping('0.00');

         $amount = new Amount();
        $amount->setCurrency('USD');
        $amount->setTotal(number_format((2*$formattedAmount),2));
      //  $amount->setDetails($amountDetails);

        $transaction = new Transaction();
        $transaction->setDescription("creating a payment");
        $transaction->setItemList($itemList);
        $transaction->setAmount($amount);

        //$baseUrl = getBaseUrl();
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturn_url("https://devtools-paypal.com/guide/pay_paypal/php?success=true");
        $redirectUrls->setCancel_url("https://devtools-paypal.com/guide/pay_paypal/php?cancel=true");

        $payment = new Payment();
        $payment->setIntent("sale");
        $payment->setPayer($payer);
        $payment->setRedirect_urls($redirectUrls);
        $payment->setTransactions(array($transaction));


        return $payment->create($this->_apiContext);
我修改了payDemo()函数

    $amount = 16;    
$formattedAmount = number_format($amount,2);
        $payer = new Payer();
        $payer->setPayment_method("paypal");
        $item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
    ->setCurrency('USD')
    ->setQuantity(1)
    ->setPrice($formattedAmount);
$item2 = new Item();
$item2->setName('Granola bars')
    ->setCurrency('USD')
    ->setQuantity(1)
    ->setPrice($formattedAmount);
$itemList = new ItemList();

$itemList->setItems(array($item1, $item2));
        //  $amountDetails = new Details();
        // $amountDetails->setSubtotal('7');
        // $amountDetails->setTax('0.00');
        // $amountDetails->setShipping('0.00');

         $amount = new Amount();
        $amount->setCurrency('USD');
        $amount->setTotal(number_format((2*$formattedAmount),2));
      //  $amount->setDetails($amountDetails);

        $transaction = new Transaction();
        $transaction->setDescription("creating a payment");
        $transaction->setItemList($itemList);
        $transaction->setAmount($amount);

        //$baseUrl = getBaseUrl();
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturn_url("https://devtools-paypal.com/guide/pay_paypal/php?success=true");
        $redirectUrls->setCancel_url("https://devtools-paypal.com/guide/pay_paypal/php?cancel=true");

        $payment = new Payment();
        $payment->setIntent("sale");
        $payment->setPayer($payer);
        $payment->setRedirect_urls($redirectUrls);
        $payment->setTransactions(array($transaction));


        return $payment->create($this->_apiContext);
如果仍然出现400或40倍的错误,您可以在第107行的PPHttpConnection.php中打印整个PayPal响应,并显示错误消息等

    $ex->setData($result);
        // echo '<pre>';
        // print_r($ex);exit;
        throw $ex;
$ex->setData($result);
//回声';
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;
  }
}
//印刷品(港币);;出口 抛出$ex;
。通过此扩展,您可以设置/安装paypal库,该库可在此链接上访问-
这个PapypalPHPSDK包含不同方法的示例


我已在YII2中安装/设置了此库,并使用了付款方式。

无需为此使用扩展。您只需安装软件包并执行以下步骤

1.创建一个组件将Paypal粘合到Yii2 在
@app
目录中创建
组件
文件夹。如果您使用的是基本模板,则此文件夹与
webroot
文件夹相同;在高级模板中,此文件夹位于要启用付款的应用程序中

创建一个包含以下内容的PHP类文件(
CashMoney

'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
    'client_id' => 'YOUR-CLIENT-ID-FROM-PAYPAL',
    'client_secret' => 'YOUR-CLIENT-SECRET-FROM-PAYPAL',
    // You may choose to include other configuration options from PayPal
    // as they have specified in the documentation
  ],
  ...
]
这就足够开始了。以后您可以选择添加特定于PayPal的其他配置

2.向Yii2注册胶水组件 在
app/config/main.php
(或
app/config/main local.php
)中,包含以下内容以注册
现金组件

use Yii;
...
use PayPal\Api\CreditCard;
use PayPal\Exception\PaypalConnectionException;

class PaymentsController { // or whatever yours is called
  ...
  public function 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;
    }
    ...
  }

  ...

}
现在我们的支付组件注册为
现金
,我们可以使用
Yii::$app->cm
访问它。酷吧

3.进行API调用 到Yii2

打开要在其中处理付款的控制器操作,并包括以下内容

paypal.Button.render({
    env: 'sandbox', // Specify 'sandbox' for the test environment
    client: {
        sandbox: 'CLIENT-ID of your APP in step1'           
    },
    payment: function (resolve, reject) {

        /* URL which would create payment */
        var CREATE_PAYMENT_URL = '/transactions/create-paypal';

        paypal.request.post(CREATE_PAYMENT_URL)
            .then(function (data) {
                resolve(data.paymentID);
            })
            .catch(function (err) {
                reject(err);
            });
    },

    onAuthorize: function (data, actions) {

        // Execute the payment here, when the buyer authorize and approves the transaction
        var EXECUTE_PAYMENT_URL = '/transactions/execute-paypal';
        paypal.request.post(EXECUTE_PAYMENT_URL,
            {paymentID: data.paymentID, payerID: data.payerID, token: data.paymentToken,serviceId:serviceId})

            .then(function (data) {
                console.log(data);
                if(data.http_code == '200') {
                    /* payment done .. do something here */
                    handleCreateService(url);
                }else {
                    /* something didn't went right with payment */
                }
            })
            .catch(function (err) {
                /* catch any exceptions */
                console.log(err);
            });
    }

}, '#paypal-button');
使用Yii;
...
使用PayPal\Api\信用卡;
使用PayPal\Exception\PaypalConnectionException;
类PaymentsController{//或您的任何名称
...
公共函数actionMakePayments{//或任何你的函数的调用
...
$card=新的PayPalCredit卡;
$card->setType('visa')
->集合编号('4111111111')
->setExpireMonth('06')
->setExpireYear(2018年)
->setCvv2('782')
->setFirstName('Richie')
->setLastName('Richardson');
试一试{
$card->create(Yii::$app->cm->getContext());
//…并用于调试目的
回声';
var_dump(“成功场景”);
回音$卡;
}捕获(PayPalConnectionException){
回声';
var_转储(“故障场景”);
echo$e;
}
...
}
...
}
预期输出与PayPal文档中的输出类似


一旦连接开始,您应该能够执行其他任务

我在我的网站上使用基于RESTAPI的paypal express结账。无需任何第三方扩展。该解决方案一般可应用于任何网站,不限于Yii框架。阅读基本概念

我的做法如下:

  • 在中创建REST API应用程序。一旦您创建了应用程序,您将获得客户端ID和密钥,以便稍后用于身份验证

  • 在要显示“签出”按钮的网页上,创建一个空div

  • 在您的资产中包含javascript

  • 4.使用以下Javascript代码呈现paypal按钮

  • 现在,您需要在controller中编写创建付款和执行付款方法的代码

  • 最后创建一个组件来进行身份验证/生成令牌和执行支付


  • 也许最好问问真正的开发者。您可以在Github上创建关于文档问题的问题。据我所见,文档非常糟糕,没有其他链接。另一个选择是,你可以通过查看源代码来理解它。主类(除了init和demo)和配置文件中只有一个方法。也许扩展正处于开发的初始阶段。这不是一个答案,但我想知道是否能有所帮助。我不是YII开发人员,因此不确定它是否需要特殊考虑。PayPal PHP SDK在composer中以
    PayPal/rest api SDK PHP
    的形式提供。您好,用户3387825,感谢您的回复,并对响应延迟表示抱歉。我按照你说的做了,但是我收到了错误(“设置未知属性:common\components\Paypal::config”)请帮助我谢谢Shello你能给我提供你的电子邮件地址吗,我有一个Yi2高级入门项目,这个Paypal模块工作得很好。我可以通过电子邮件发送给您。:)我刚发了一封电子邮件:)。如果您有任何问题,请不要犹豫,联系meThanks用户3387825以引起您的注意,但我没有收到您的电子邮件。你能再寄一次吗。我的电子邮件地址是gam.jatin。vaghasiya@gmail.com我在等你的答复。谢谢,请检查您的收件箱文件夹。我已经发送了一个链接,你可以在那里下载这个项目。祝你有美好的一天。扰流板:支持的最小值:PHP5.5
    $this->apiContext=newapicontext(newOAuthTokenCredential($this->client_id,$this->client_secret)应该是
    $this->apiContext=新的apiContext(
    
    /* Create Paypal function will pass token,
    paymentID back to JS in step 4. */
    
    public function actionCreatePaypal() {        
        $paypal = new Paypal();
        $paypal->getToken();
        $res = $paypal->createPayment();
        echo json_encode($res);
    }
    
    public function actionExecutePaypal() {
        $paymentID = $_POST['paymentID'];
        $payerID =  $_POST['payerID'];
        $access_token = $_POST['token'];
        $paypal = new Paypal(['paymentID'=>$paymentID,'payerID' =>$payerID,'access_token' =>$access_token]);
        $paypal->getToken();
        $res = $paypal->executePayment();
        echo json_encode($res);
    }    
    
    class Paypal {  
    
        public $url;
        public $env;
        public $clientId;
        public $clientSecret;
        public $access_token;
        public $paymentID;
        public $payerID;
        public $premiumService;
    
        public function __construct($params=0) {
            $this->access_token = '';
            /* for sandbox url is https://api.sandbox.paypal.com */
            $this->url = \Yii::$app->params['paypal_url'];
            $this->clientId = \Yii::$app->params['paypal_clientId'];
            $this->clientSecret = \Yii::$app->params['paypal_clientSecret'];
    
            if(isset($params['paymentID'])) {
                $this->paymentID = $params['paymentID'];
            }
    
            if(isset($params['payerID'])) {
                $this->payerID = $params['payerID'];
            }
    
            if(isset($params['access_token'])) {
                $this->access_token = $params['access_token'];
            }
    
            /* This is where you describe the product you are selling */    
            $this->premiumService = '{
            "intent":"sale",
            "redirect_urls":{
                 "cancel_url":"https://cancelurl.com",
                 "return_url":"https://returnurl.com"
            },
            "payer":{
                "payment_method":"paypal"
            },
            "transactions":[
            {
                "amount":{
                "currency":"USD",
                "total":"39.00"
                },
                "item_list":{
                    "items": [
                    {
                        "quantity": "1",
                        "name": "Premium Service",
                        "price": "39.00",
                        "currency": "USD",
                        "description": "Purchase allows one time use of this premium service"
                    }]
                },
                "description":"Premium Service"
    
            }]
            }';
    }
    public function getToken() {
        $curlUrl = $this->url."/v1/oauth2/token";
        $curlHeader = array(
            "Content-type" => "application/json",
            "Authorization: Basic ". base64_encode( $this->clientId .":". $this->clientSecret),
        );
        $postData = array(
            "grant_type" => "client_credentials"
        );
    
        $curlPostData = http_build_query($postData);
        $curlResponse = $this->curlCall($curlUrl, $curlHeader, $curlPostData);
        if($curlResponse['http_code'] == 200) {
            $this->access_token = $curlResponse['json']['access_token'];
        }
    }
    
    
    public function createPayment() {
        $curlUrl = $this->url."/v1/payments/payment";
        $curlHeader = array(
            "Content-Type:application/json",
            "Authorization:Bearer  ". $this->access_token,
        );
    
    
        $curlResponse = $this->curlCall($curlUrl, $curlHeader, $this->premiumService);
        $id = null;
        $approval_url = null;
        if($curlResponse['http_code'] == 201) {
            $id = $curlResponse['json']['id'];
            foreach ($curlResponse['json']['links'] as $link) {
                if($link['rel'] == 'approval_url'){
                    $approval_url = $link['href'];
                }
            }
        }
    
        $res = ['paymentID' =>$id,'approval_url'=>$approval_url];
        return $res;
    }
    
    public function executePayment() {
        $curlUrl = $this->url."/v1/payments/payment/".$this->paymentID."/execute";
    
        $curlHeader = array(
            "Content-Type:application/json",
            "Authorization:Bearer ".$this->access_token,
        );
        $postData = array(
            "payer_id" => $this->payerID
        );
    
        $curlPostData = json_encode($postData);
        $curlResponse = $this->curlCall($curlUrl, $curlHeader, $curlPostData);
    
        return $curlResponse;
    }
    
    function curlCall($curlServiceUrl, $curlHeader, $curlPostData) {
        // response container
        $resp = array(
            "http_code" => 0,
            "json"     => ""
        );
    
        //set the cURL parameters
        $ch = curl_init($curlServiceUrl);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
    
        //turning off the server and peer verification(TrustManager Concept).
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    
        curl_setopt($ch, CURLOPT_SSLVERSION , 'CURL_SSLVERSION_TLSv1_2');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        //curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeader);
    
        if(!is_null($curlPostData)) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPostData);
        }
        //getting response from server
        $response = curl_exec($ch);
    
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        curl_close($ch); // close cURL handler
    
        // some kind of an error happened
        if (empty($response)) {
            return $resp;
        }
    
        $resp["http_code"] = $http_code;
        $resp["json"] = json_decode($response, true);
    
        return $resp;
    
    }
    }