簡體   English   中英

將Paypal與php(DoDirectMethod)集成

[英]Integrating Paypal with php(DoDirectMethod)

我正在按照指南整合Paypal。 我不希望用戶重定向到Paypal進行付款。 所以我需要遵循直接付款方式。

我從該指南中了解到,首先我需要創建兩個Sandbox帳戶(買方和商家)。 然后在一個類中使用商家帳戶的詳細信息(USR,“ PWD”,“簽名”)。 所以我創建了一個類(paypal.php),然后通過該類處理付款。 我aldals下載了該類需要的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";

?>

在過去的四個小時里,我一直在撓頭,遵循各種指南和教程,但不知道出了什么問題。 我還需要遵循/下載其他步驟/文件嗎?

PS我第一次嘗試貝寶集成。

您可以使用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);
    }
}

 }

付款配置文件

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

首先,您在流程表單中輸入了錯誤的$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 Standard(而不是PayPal Payments Pro),然后點擊提交以保存所做的任何更改。

如果您不接受PayPal Payments Pro ,則不能使用直接方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM