简体   繁体   English

将Paypal与php(DoDirectMethod)集成

[英]Integrating Paypal with php(DoDirectMethod)

i was following this guide to integrate paypal. 我正在按照指南整合Paypal。 I dont want user to redirect to paypal for making payment. 我不希望用户重定向到Paypal进行付款。 So i need to follow Direct Payment method. 所以我需要遵循直接付款方式。

What i understood from that guide was that first i need to create two Sandbox accounts(buyer and merchant). 我从该指南中了解到,首先我需要创建两个Sandbox帐户(买方和商家)。 Then used details(USR, 'PWD', 'SIGNATURE') of merchant account in a class. 然后在一个类中使用商家帐户的详细信息(USR,“ PWD”,“签名”)。 So i created a class(paypal.php) and then process payment via that class. 所以我创建了一个类(paypal.php),然后通过该类处理付款。 i alds downloaded cacert.pem that the class needs. 我aldals下载了该类需要的cacert.pem

This is my class 这是我的课

<?php

class Paypal {


   /**
    * Last error message(s)
    * @var array
    */
   protected $_errors = array();

   /**
    * API Credentials
    * Use the correct credentials for the environment in use (Live / Sandbox)
    * @var array
    */
   protected $_credentials = array(
      'USER' => 'kanavk-facilitator_api1.ocodewire.com',
      'PWD' => '1404460510',
      'SIGNATURE' => 'A4sylwT.LsGOlR5e0Qos27RoSta5AKLvXCCjXXHcGN8Tor8.JxNZxIAs',
   );

   /**
    * API endpoint
    * Live - https://api-3t.paypal.com/nvp
    * Sandbox - https://api-3t.sandbox.paypal.com/nvp
    * @var string
    */
   protected $_endPoint = 'https://api-3t.sandbox.paypal.com/nvp';

   /**
    * API Version
    * @var string
    */
   protected $_version = '74.0';

   /**
    * Make API request
    *
    * @param string $method string API method to request
    * @param array $params Additional request parameters
    * @return array / boolean Response array / boolean false on failure
    */
   public function request($method,$params = array()) {
      $this -> _errors = array();
      if( empty($method) ) { //Check if API method is not empty
         $this -> _errors = array('API method is missing');
         return false;
      }

      //Our request parameters
      $requestParams = array(
         'METHOD' => $method,
         'VERSION' => $this -> _version
      ) + $this -> _credentials;

      //Building our NVP string
      $request = http_build_query($requestParams + $params);

      //cURL settings
      $curlOptions = array (
         CURLOPT_URL => $this -> _endPoint,
         CURLOPT_VERBOSE => 1,
         CURLOPT_SSL_VERIFYPEER => true,
         CURLOPT_SSL_VERIFYHOST => 2,
         CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem', //CA cert file
         CURLOPT_RETURNTRANSFER => 1,
         CURLOPT_POST => 1,
         CURLOPT_POSTFIELDS => $request
      );

      $ch = curl_init();
      curl_setopt_array($ch,$curlOptions);

      //Sending our request - $response will hold the API response
      $response = curl_exec($ch);

      //Checking for cURL errors
      if (curl_errno($ch)) {
         $this -> _errors = curl_error($ch);
         curl_close($ch);
         return false;
         //Handle errors
      } else  {
         curl_close($ch);
         $responseArray = array();
         parse_str($response,$responseArray); // Break the NVP string to an array
         return $responseArray;
      }
   }
}

?>

The i created a script for processing form. 我创建了一个脚本来处理表格。 Included that class and tried to process payment with dummy inputs. 包括该类,并尝试使用虚拟输入处理付款。 But nothing is happening when i'm executing the script. 但是当我执行脚本时什么也没发生。

this is my script that i'm using for processing form 这是我用来处理表格的脚本

<?php
    include("includes/config.php");
    include("includes/paypal.php");
    @session_start();
    include("steps.php");
    error_reporting(0);

$requestParams = array(
   'IPADDRESS' => $_SERVER['REMOTE_ADDR'],
   'PAYMENTACTION' => 'Sale'
);

$creditCardDetails = array(
   'CREDITCARDTYPE' => 'Visa',
   'ACCT' => '4929802607281663',
   'EXPDATE' => '062012',
   'CVV2' => '984'
);

$payerDetails = array(
   'FIRSTNAME' => 'John',
   'LASTNAME' => 'Doe',
   'COUNTRYCODE' => 'US',
   'STATE' => 'NY',
   'CITY' => 'New York',
   'STREET' => '14 Argyle Rd.',
   'ZIP' => '10010'
);

$orderParams = array(
   'AMT' => '500',
   'ITEMAMT' => '496',
   'SHIPPINGAMT' => '4',
   'CURRENCYCODE' => 'GBP'
);

$item = array(
   'L_NAME0' => 'iPhone',
   'L_DESC0' => 'White iPhone, 16GB',
   'L_AMT0' => '496',
   'L_QTY0' => '1'
);

$paypal = new Paypal();



$response = $paypal -> request('DoDirectPayment',
   $requestParams + $creditCardDetails + $payerDetails + $orderParams + $item
);



if( is_array($response) && $response['ACK'] == 'Success') { // Payment successful
   // We'll fetch the transaction ID for internal bookkeeping
   $transactionId = $response['TRANSACTIONID'];

}else echo "failed";

?>

I'm scratching my head from the last four hours, following various guides and tutorials but don't know whats's wrong. 在过去的四个小时里,我一直在挠头,遵循各种指南和教程,但不知道出了什么问题。 Is there any other step/files i need to follow/download? 我还需要遵循/下载其他步骤/文件吗?

PS I'm trying paypal integration for the first time. PS我第一次尝试贝宝集成。

You can do it easily with PayPal SDK 您可以使用PayPal SDK轻松完成此操作
Just integrate it in your code and Use this class 只需将其集成到您的代码中并使用此类

 /* Created By RAJA */

 require realpath(dirname(__FILE__) . '/' . 'paymentconfig.php');
 require realpath(dirname(__FILE__) . '/' . '/PayPalSDK/vendor/autoload.php');

 use PayPal\Auth\OAuthTokenCredential;
 use PayPal\Rest\ApiContext;
 use PayPal\Api\Amount;
 use PayPal\Api\Details;
 use PayPal\Api\Item;
 use PayPal\Api\ItemList;
 use PayPal\Api\CreditCard;
 use PayPal\Api\Payer;
 use PayPal\Api\Payment;
 use PayPal\Api\FundingInstrument;
 use PayPal\Api\Transaction;
 use PayPal\Exception\PPConnectionException;

 class PaymentProcessor {

public static function proceedCreditCardTransaction($cardNumber, $cardType, $cardExpMonth, $cardExpYear, $firstName, $lastName, $amountToPay, $description, $currency = CURRENCY) {

    if (!isset($cardNumber) || strlen($cardNumber) <= 10) {
        throw new Exception("Invalid CardNumber : " . $cardNumber);
    }if (!isset($cardType) || strlen($cardType) <= 0) {
        throw new Exception("Invalid CardType : " . $cardType);
    }if (!isset($cardExpMonth) || intval($cardExpMonth) <= 0 || intval($cardExpMonth) > 12) {
        throw new Exception("Invalid Card Expire Month : " . $cardExpMonth);
    }if (!isset($cardExpYear) || strlen($cardExpYear) <= 2) {
        throw new Exception("Invalid Card Expire Year : " . $cardExpYear);
    }if (!isset($firstName) || strlen($firstName) <= 0) {
        throw new Exception("Invalid First Name : " . $firstName);
    }if (!isset($lastName)) {
        throw new Exception("Invalid Last Name : " . $lastName);
    }if (!isset($amountToPay) || strlen($amountToPay) <= 0 || intval($amountToPay) <= 0) {
        throw new Exception("Invalid Amount : " . $amountToPay);
    }if (!isset($currency) || strlen($currency) <= 0) {
        throw new Exception("Invalid Currency : " . $currency);
    }if (!isset($description) || strlen($description) <= 0) {
        throw new Exception("Invalid Description : " . $description);
    }

    $sdkConfig = array(
        "mode" => "sandbox"
    );

    $cred = new OAuthTokenCredential(CLIENT_ID, SECRET, $sdkConfig);

    $apiContext = new ApiContext($cred, 'Request' . time());
    $apiContext->setConfig($sdkConfig);

    $card = new CreditCard();
    $card->setType($cardType);
    $card->setNumber($cardNumber);
    $card->setExpire_month($cardExpMonth);
    $card->setExpire_year($cardExpYear);
    $card->setFirst_name($firstName);
    $card->setLast_name($lastName);

    $fundingInstrument = new FundingInstrument();
    $fundingInstrument->setCredit_card($card);

    $payer = new Payer();
    $payer->setPayment_method("credit_card");
    $payer->setFunding_instruments(array($fundingInstrument));

    $amount = new Amount();
    $amount->setCurrency($currency);
    $amount->setTotal($amountToPay);

    $transaction = new Transaction();
    $transaction->setAmount($amount);
    $transaction->setDescription($description);

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

    try {
        $payment->create($apiContext);
        return new PaymentParser($payment->toArray());
    } catch (PPConnectionException $ex) {
        throw new Exception($ex->getData());
    }
    //echo json_encode($payment->toArray());        
}

public static function proceedPaypalTransaction($amountToPay, $itemName, $description, $currency = CURRENCY) {

    $sdkConfig = array(
        "mode" => "sandbox"
    );

    $cred = new OAuthTokenCredential(CLIENT_ID, SECRET, $sdkConfig);
    $apiContext = new ApiContext($cred, 'Request' . time());
    $apiContext->setConfig($sdkConfig);

    $payer = new Payer();
    $payer->setPaymentMethod("paypal");

    $item1 = new Item();
    $item1->setName($itemName)
            ->setCurrency($currency)
            ->setQuantity(1)
            ->setPrice($amountToPay);

    $itemList = new ItemList();
    $itemList->setItems(array($item1));

    $amount = new Amount();
    $amount->setCurrency($currency)
            ->setTotal($amountToPay);

    $transaction = new Transaction();
    $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription($description);

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

    try {
        $payment->create($apiContext);
    } catch (PayPal\Exception\PPConnectionException $ex) {
        echo "Exception: " . $ex->getMessage() . PHP_EOL;
        var_dump($ex->getData());
        exit(1);
    }
}

 }

PAYMENTCONFIG.PHP 付款配置文件

define("CURRENCY","USD");

if (!file_exists(__DIR__ . '/PayPalSDK/vendor/autoload.php')) {
    echo "The 'vendor' folder is missing. You must run 'composer update' to resolve     application dependencies.\nPlease see the README for more information.\n";
exit(1);
}
define('PP_CONFIG_PATH', realpath(dirname(__FILE__) . '/' . '/PayPalSDK/sdk_config.ini'));
define('CLIENT_ID', 'CLIENT_ID');
define('SECRET', 'SECRET');

First of all you have enter wrong Expire Date of $creditCardDetails in process form,(put 'EXPDATE'=>'062020') 首先,您在流程表单中输入了错误的$creditCardDetails到期日期,(输入'EXPDATE'=>'062020')

and do following change in process form, 并按照流程形式进行更改,

From

if( is_array($response) && $response['ACK'] == 'Success') { // Payment successful
   // We'll fetch the transaction ID for internal bookkeeping
   $transactionId = $response['TRANSACTIONID'];

}else echo "Failed";

to

if( is_array($response) && $response['ACK'] == 'Success') { // Payment successful
    // We'll fetch the transaction ID for internal bookkeeping
    $transactionId = $response['TRANSACTIONID'];    
}else{
    echo "<pre>";
    print_r($response);
}

after this you will get following error, 之后,您将得到以下错误,

ERROR: 10501 Invalid Configuration. 错误:10501无效的配置。 This transaction cannot be processed due to an invalid merchant configuration. 由于商家配置无效,因此无法处理此交易。

To solve this error you have accepted the " PayPal Payments Pro " agreement in your PayPal account after you have been approved by PayPal for PayPal Payments Pro. 为解决此错误,在您被PayPal批准使用PayPal Payments Pro后,您已经在您的PayPal帐户中接受了“ PayPal Payments Pro ”协议。 If you have accepted their agreement but are still getting this error, PayPal also occasionally acknowledges the agreement and activates Virtual Terminal but somehow misses activating PayPal Payments Pro itself; 如果您已接受他们的协议,但仍然出现此错误,则PayPal有时也会确认该协议并激活虚拟终端,但不知何故未激活PayPal Payments Pro本身; if your PayPal "Get Started" summary screen only shows Virtual Terminal and nothing about PayPal Payments Pro, please contact PayPal support to get your PayPal Payments Pro service activated. 如果您的PayPal“入门”摘要屏幕仅显示“虚拟终端”,而不显示任何有关PayPal Payments Pro的信息,请联系PayPal支持以激活您的PayPal Payments Pro服务。

If you are only using PayPal Payments Standard with a regular PayPal personal, Business or Premier account (ie, if you have not upgraded to PayPal Payments Pro), please go to Seller Admin > Payment Preferences and make sure you have PayPal Payments Standard checked (rather than PayPal Payments Pro) and click Submit to save any changes you make. 如果您仅通过常规的PayPal个人,企业或贵宾帐户使用PayPal Payments Standard(即,如果您尚未升级到PayPal Payments Pro),请转到卖方管理>付款首选项,并确保已选中PayPal Payments Standard(而不是PayPal Payments Pro),然后点击提交以保存所做的任何更改。

Without accepting of PayPal Payments Pro you cant use Do Direct Method. 如果您不接受PayPal Payments Pro ,则不能使用直接方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM