【问题标题】:Integrating Paypal with php(DoDirectMethod)将 Paypal 与 php 集成(DoDirectMethod)
【发布时间】:2014-07-04 10:39:54
【问题描述】:

我正在关注this 指南以集成贝宝。我不希望用户重定向到贝宝进行付款。所以我需要遵循直接付款方式。

我从该指南中了解到,首先我需要创建两个沙盒帐户(买家和商家)。然后使用类中商家帐户的详细信息(USR,'PWD','SIGNATURE')。所以我创建了一个类(paypal.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";

?>

在过去的四个小时里,我一直在摸索,遵循各种指南和教程,但不知道出了什么问题。我需要遵循/下载任何其他步骤/文件吗?

附:我第一次尝试贝宝集成。

【问题讨论】:

    标签: php paypal


    【解决方案1】:

    您可以使用PayPal SDK轻松做到这一点
    只需将其集成到您的代码中并使用此类

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

    【讨论】:

      【解决方案2】:

      首先你在处理表单中输入了错误的到期日期$creditCardDetails,(输入'EXPDATE'=>'062020')

      并在流程形式上进行以下更改,

      来自

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

      之后你会得到以下错误,

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

      为解决此错误,在您获得 PayPal 的 PayPal Payments Pro 批准后,您已在您的 PayPal 帐户中接受了“PayPal Payments Pro”协议。如果您已接受他们的协议但仍然收到此错误,则 PayPal 有时也会确认该协议并激活虚拟终端,但不知何故错过了激活 PayPal Payments Pro 本身;如果您的 PayPal“开始”摘要屏幕仅显示虚拟终端,而没有任何关于 PayPal Payments Pro 的信息,请联系 PayPal 支持以激活您的 PayPal Payments Pro 服务。

      如果您仅通过普通的 PayPal 个人、企业或高级账户使用 PayPal Payments Standard(即,如果您尚未升级到 PayPal Payments Pro),请转到卖家管理 > 付款首选项并确保您有 PayPal Payments选中标准(而不是 PayPal Payments Pro)并单击提交以保存您所做的任何更改。

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

      【讨论】:

      • 我将有效期更改为 062014,但仍然没有显示任何错误。在我创建了 Paypal 类的实例并显示值Paypal Object ( [_errors:protected] =&gt; Array ( ) [_credentials:protected] =&gt; Array ( [USER] =&gt; kanavk-facilitator_api1.ocodewire.com [PWD] =&gt; 1404460510 [SIGNATURE] =&gt; A4sylwT.LsGOlR5e0Qos27RoSta5AKLvXCCjXXHcGN8Tor8.JxNZxIAs ) [_endPoint:protected] =&gt; https://api-3t.sandbox.paypal.com/nvp [_version:protected] =&gt; 74.0 ) 之后,我尝试了 print_r($paypal)。但是没有错误。页面为空白。我需要包含任何 sdk 或任何其他文件吗?
      • 我编辑了我的评论,再次检查并按照建议替换代码,之后您将收到实际的错误消息。
      • 我正在通过浏览器直接打开脚本(带有卡片详细信息的脚本)。不涉及形式。我需要遵循 POST 方法吗?
      • 在第二个 php 文件中找到 $creditCardDetails 并将 'EXPDATE' =&gt; '062012', 替换为 'EXPDATE' =&gt; '062020', 。然后检查答案帖子中提到的替换代码。
      • 你最后打印echo "&lt;pre&gt;";print_r($response);了吗?
      猜你喜欢
      • 2013-06-01
      • 2017-02-08
      • 2017-06-19
      • 2020-07-10
      • 2013-02-25
      • 2011-09-23
      • 2022-10-08
      • 2012-10-22
      • 2015-02-27
      相关资源
      最近更新 更多