将Paypal与php集成(DoDirectMethod)

将Paypal与php集成(DoDirectMethod),php,paypal,Php,Paypal,我是按照指南整合贝宝的。我不希望用户重定向到贝宝付款。所以我需要遵循直接付款方式 我从该指南中了解到,首先我需要创建两个沙箱帐户Buyer和merchant。然后在一个类中使用detailsUSR、'PWD、'SIGNATURE'商户账户。因此,我创建了一个classpaypal.php,然后通过该类处理付款。我下载了班级需要的cacert.pem 这是我的课 <?php class Paypal { /** * Last error message(s) *

我是按照指南整合贝宝的。我不希望用户重定向到贝宝付款。所以我需要遵循直接付款方式

我从该指南中了解到,首先我需要创建两个沙箱帐户Buyer和merchant。然后在一个类中使用detailsUSR、'PWD、'SIGNATURE'商户账户。因此,我创建了一个classpaypal.php,然后通过该类处理付款。我下载了班级需要的cacert.pem

这是我的课

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

?>
我创建了一个用于处理表单的脚本。包括该类并尝试使用虚拟输入处理付款。但是当我执行脚本时,什么都没有发生

这是我用来处理表单的脚本

<?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";

?>
在过去的四个小时里,我一直在为各种各样的指南和教程挠头,但不知道到底出了什么问题。是否有其他步骤/文件需要遵循/下载

另外,我第一次尝试贝宝整合

您可以轻松地使用 只需将其集成到代码中并使用该类即可

 /* 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);
    }
}

 }

首先,您在流程表单中输入了错误的$creditCardDetails过期日期,请输入'EXPDATE'=>'062020'

并在流程形式上做如下更改

在此之后,将出现以下错误:

错误:10501配置无效。 由于商户配置无效,无法处理此交易

为了解决此错误,在PayPal批准您使用PayPal Payments Pro后,您已经在PayPal帐户中接受了PayPal Payments Pro协议。如果您已经接受了他们的协议,但仍然出现此错误,PayPal也会偶尔承认协议并激活虚拟终端,但不知何故未能激活PayPal Payments Pro本身;如果您的PayPal Get Started summary屏幕仅显示虚拟终端,而未显示有关PayPal Payments Pro的任何信息,请联系PayPal支持以激活您的PayPal Payments Pro服务

如果您仅在常规PayPal个人、企业或卓越理财账户中使用PayPal支付标准,即,如果您尚未升级到PayPal Payments Pro,请转到卖家管理>付款首选项,并确保已选中PayPal付款标准,而不是PayPal Payments Pro,然后单击提交保存所做的任何更改


如果不接受PayPal Payments Pro,您就不能使用Do Direct方法。

我将到期日更改为2014年6月6日,但仍然没有显示任何错误。在我创建paypal类的实例之后,我尝试打印$paypal,它显示的值是paypal对象[\u错误:受保护]=>Array[\u凭证:受保护]=>Array[USER]=>kanavk-faciliator\u api1.ocodewire.com[PWD]=>1404460510[SIGNATURE]=>A4sylwT.lsgol5e0qosta5klvxcjxxhcgn8tor8.jxnzzias[\u端点:受保护] => https://api-3t.sandbox.paypal.com/nvp [\u版本:受保护]=>74.0。但是没有错误。这一页是空白的。我需要包括任何sdk或任何其他文件吗?我编辑了我的评论,再次检查并按照建议替换代码,之后您将收到实际的错误消息。我正在通过浏览器直接打开包含卡详细信息的脚本。没有涉及任何形式。我需要遵循POST方法吗?在第二个php文件中找到$creditCardDetails并将'EXPDATE'=>'062012'替换为'EXPDATE'=>'062020'。然后检查回复帖子中提到的替换代码。您是否打印了echo;打印答复;最后?
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');
if( is_array($response) && $response['ACK'] == 'Success') { // Payment successful
   // We'll fetch the transaction ID for internal bookkeeping
   $transactionId = $response['TRANSACTIONID'];

}else echo "Failed";
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);
}