web-dev-qa-db-fra.com

Paypal for the Yii2.

Comment utiliser l'extension Paypal dans yii2. J'utilise ce lien 
https://github.com/marciocamello/yii2-Paypal
J'ai installé l'extension et ajouté du code dans le fichier de configuration.

Mais il n'y a pas plus d'informations que faire. Alors aidez-moi s'il vous plaît.

Merci

12
jatin vaghasiya

Il n'est pas nécessaire d'utiliser une extension pour cela. Vous pouvez simplement installer le paquet Paypal/rest-api-sdk-php et effectuer les étapes suivantes.

1. Créer un composant pour coller Paypal à Yii2

Créez un dossier components dans votre répertoire @app. Si vous utilisez le modèle de base, il s'agit du même dossier que webroot; dans le modèle avancé, ce dossier se trouve dans l'application dans laquelle vous souhaitez activer les paiements.

Créez un fichier de classe PHP (CashMoney par exemple) avec le contenu suivant

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;
  }
}

C'est assez pour commencer. Vous pouvez choisir d'ajouter d'autres configurations spécifiques à Paypal ultérieurement.

2. Enregistrez votre composant de colle avec Yii2

Dans votre app/config/main.php (ou app/config/main-local.php), incluez les éléments suivants pour enregistrer le composant 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
  ],
  ...
]

Nous avons maintenant notre composant de paiement enregistré en tant que CashMoney. Nous pouvons y accéder en utilisant Yii::$app->cm. Cool hein?

3. Faire des appels d'API

To Faites votre premier appel API in Yii2,

Ouvrez l'action du contrôleur dans laquelle vous souhaitez gérer les paiements et incluez les éléments suivants:

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;
    }
    ...
  }

  ...

}

Le résultat attendu est similaire à celui de la documentation Paypal.

Une fois la connexion établie, vous devriez pouvoir effectuer d'autres tâches. 

16
iGbanam

C'est ma solution, ça marche avec yii2 advanced tempalte!

I'v a déplacé cette classe marciocamello/yii2-Paypal/PayPal.php du dossier du fournisseur vers common/composant/Paypal.php

Vous devez "inclure" common\components\Paypal dans frontend\config\main.php dans la section components:

 '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,
        ]
    ],

],

Dans PPHttpConfig.php à la ligne 11, j’ai modifié la ligne suivante

    //CURLOPT_SSLVERSION => 3,
    CURLOPT_SSLVERSION => 'CURL_SSLVERSION_TLSv1',

Dans PPLoggingManager.php à la ligne 48-52, le chemin du journal a été codé en dur

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;
    }

Dans le contrôleur de site, j'ai appelé la fonction composant

      echo '<pre/>';
  print_r(Yii::$app->Paypal->payDemo());  
  exit();

J'ai reçu une réponse avec URL de redirection, transactionId, etc.

--------------  400 ERROR Debuging ----------

J'ai toujours eu 400 erreur parce que j'avais un problème avec le format de prix, je l'ai corrigé en utilisant la fonction number_format.

J'ai peu modifié la fonction 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);

Si vous obtenez toujours une erreur 400 ou 40x, vous pouvez imprimer toute la réponse Paypal avec les messages d'erreur, etc. dans PPHttpConnection.php à la ligne 107. 

    $ex->setData($result);
        // echo '<pre>';
        // print_r($ex);exit;
        throw $ex;
2
Nagy Ervin

https://github.com/marciocamello/yii2-Paypal . Par cette extension, vous pouvez simplement installer/installer la bibliothèque Paypal disponible sur ce lien - https://github.com/Paypal/PayPal-PHP-SDK
Ce kit-SDK de type phypal contient des exemples de méthodes différentes. 

J'ai installé/installé cette bibliothèque dans YII2 et utilisé des méthodes de paiement.

1
Mohd Bashir

J'utilise Paypal Express Checkout basé sur Rest API sur mon site Web. Pas besoin d'une extension tierce. La solution peut être appliquée à n’importe quel site Web en général non limité au cadre Yii. Pour obtenir des concepts de base, lisez https://developer.Paypal.com/docs/integration/direct/express-checkout/integration-jsv4/

Voici mon approche:

  1. Créez une application REST API dans https://developer.Paypal.com . Une fois que vous avez créé votre application, vous obtenez un identifiant client et une clé secrète, qui seront utilisés ultérieurement pour l'authentification.

  2. Sur votre page Web, où vous souhaitez afficher le bouton de paiement, créez un div. Vide. <div id="Paypal-button"></div>

  3. Inclure https://www.paypalobjects.com/api/checkout.js javascript dans votre actif. 

4.Rendez le bouton Paypal avec le code Javascript suivant

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');
  1. Vous devez maintenant coder votre paiement créé et exécuter les méthodes de paiement dans le contrôleur. 

    /* 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);
    }    
    
  2. Enfin, créez un composant pour authentifier/générer un jeton et exécuter le paiement.

    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;
    
    }
    }
    
0
Vikalp Veer