PayPal SDK错误"找不到默认用户的凭据"

时间:2015-08-19 15:23:11

标签: php api rest xampp paypal

我试图将PayPal SDK集成到我的网站中,但遇到了一个问题,我无法在文档中或通过Stackoverflow找到解决方案。

我使用标准设置:

start.php:

    <?php

    //require 'vendor/autoload.php';
    require __DIR__ . '/../vendor/autoload.php';

    use PayPal\Rest\ApiContext;
    use PayPal\Auth\OAuthTokenCredential;

    define('BASE_URL', 'http://localhost:80/paypaltut/');

    if(!defined("PP_CONFIG_PATH")){
            define('PP_CONFIG_PATH', '../vendor/paypal/rest-api-sdk-php/tests/');
            }
    $clientid = 'ARe54bHOzRcn13nRglDpIst46bWOp6pyBRYlP4nulwwTL2ivIuKlIJrUp5LdgZfuC0qPbqIuGdVFsmeK';
    $clientsecret = 'EJarieZ8B_6WEZ__gZl0uS-Dmc-ypa1RH1joF1u4_XlJje2IINBRCsARhNyZk-dJG7kBJS8ceQF5GNVr';

    $apiContext = new ApiContext(new OAuthTokenCredential($clientid, $clientsecret));    

的index.php:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!--Scripts-->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <script src="../scripts/modernizr.js"> </script> <!-- Modernizr -->
        <!--Stylesheets-->
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="../CSS/reset.css"> <!-- CSS reset -->
        <link rel="stylesheet" href="css/"> <!-- Resource style -->
        <link rel="stylesheet" href="css/ongakuStandard.css"> <!-- Resource style -->
        <link rel="stylesheet" href="../CSS/signupStyle.css" type="text/css"><!-- for sign up form and all of its partials-->
        <!--fonts-->
        <link href='http://fonts.googleapis.com/css?family=Titillium+Web:400,600,700' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Josefin+Sans:400,600,700' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Fira+Sans:400,500,700' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Grand+Hotel' rel='stylesheet' type='text/css'>  
    <title>Doc</title>
</head>
<body>

<div class="container-fluid centerDisp">
    <form class="blockDisp" name="productform" method="post" action="checkout.php">
        <div class="blockDisp">
            <div class="forminputdiv blockDisp">
                <label class="fw-120 label-1">Product name</label>
                <input class="medInput" type="text" name="product">
            </div>
            <div class="forminputdiv blockDisp">
                <label class="label-1 fw-120">Quantity</label>
                <input class="medInput" type="number" step="any" min="0" max="15" name="quantity">
<!--                <input class="medInput" type="string" name="quantity">-->
            </div>
            <div class="forminputdiv blockDisp">
                <label class="label-1 fw-120">price</label>
                <select class="medInput" type="number" name="price">
                    <option value="5.00">5.00</option>
                    <option value="8.00">8.00</option>
                    <option value="12.00">12.00</option>
                    <option value="18.00">18.00</option>
                    <option value="25.00">25.00</option>
                    <option value="60.00">60.00</option>
                </select>
            </div>
            <br>
            <div class="forminputdiv flex-middle">
                <button class="submission fw-200" value="submit">Submit</button>
            </div>
        </div>
        <input type="hidden" name="{{ csrf_key }}" value="{{ csrf_token }}" >
    </form>
</div>
<script>

    $('input[name="quantity"]').on('change', function(){
        var thisval = $(this).val();
        $(this).val(thisval + '.00');        
    });

</script>

</body>
</html>

checkout.php:

<?php
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;

require 'app/start.php';

if(!isset($_POST['product'], $_POST['price'], $_POST['quantity'])) {
    echo "post variables not set!!";
    die();
}  

$product = $_POST['product'];
$price = (float) $_POST['price'];
$quant = (float) $_POST['quantity'];
$shipping = (float) 2.55;
$tax = (float) 1.45;
$subtotal = $price * $quant;
$total = $subtotal + $shipping + $tax;

//more api variable definition
$payer = new Payer();
    $payer->setPaymentMethod('paypal');

$item = new Item();
    $item->setName($product);
    $item->setCurrency('GBP');
    $item->setQuantity($quant);
    $item->setPrice($price);

$itemList = new ItemList();
    $itemList->setItems([$item]);

$details = new Details();
    $details->setTax($tax);
    $details->setShipping($shipping);
    $details->setSubtotal($price * $quant);

$amount = new Amount();
    $amount->setCurrency('GBP');
    $amount->setTotal($total);
    $amount->setDetails($details);

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

$redirectUrls = new RedirectUrls();
    $redirectUrls->setReturnUrl(BASE_URL . 'pay.php?success=true');
    $redirectUrls->setCancelUrl(BASE_URL . 'pay.php?success=false');

$payment = new Payment();
    $payment->setIntent('sale');
    $payment->setPayer($payer);
    $payment->setRedirectUrls($redirectUrls);
    $payment->setTransactions([$transaction]);

    try{    
$payment->create($apiContext);
    }
 catch (PayPal\Exception\PayPalConnectionException $ex) {
    echo $ex->getCode(); 
    echo $ex->getData(); 
} catch (Exception $ex) {
    die($ex);
}
$approvalUrl = $payment->getApprovalLink();
header("Location: {$approvalUrl}");
exit(1);

pay.php:

<?php

require 'app/start.php';

use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;

    if(!isset($_GET['success'], $_GET['paymentId'], $_GET['PayerID'])){
        die();
    }

    if((bool)$_GET['success']=== 'false'){

        echo 'Transaction cancelled!';
        die();
    }

    $paymentID = $_GET['paymentId'];
    $payerId = $_GET['PayerID'];

    $payment = Payment::get($paymentID, $apiContext);

    $execute = new PaymentExecution();
    $execute->setPayerId($payerId);

    try{
        $result = $payment->execute($execute);
    }catch(Exception $e){
        die($e);
    }
    echo 'Payment made, Thanks!';

congif.ini:

;Account credentials from developer portal
[Account]
acct1.ClientId = AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS
acct1.ClientSecret = EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL

acct2.ClientId = TestClientId
acct2.ClientSecret = TestClientSecret

;Connection Information
[Http]
http.ConnectionTimeOut = 60
http.Retry = 1
;http.Proxy=http://[username:password]@hostname[:port][/path]

mode=sandbox

;Service Configuration
[Service]
service.EndPoint="https://api.sandbox.paypal.com"
; Uncomment this line for integrating with the live endpoint 
; service.EndPoint="https://api.paypal.com"


;Logging Information
[Log]
log.LogEnabled=true

; When using a relative path, the log file is created
; relative to the .php file that is the entry point
; for this request. You can also provide an absolute
; path here
log.FileName=PayPal.log

; Logging level can be one of FINE, INFO, WARN or ERROR
; Logging is most verbose in the 'FINE' level and
; decreases as you proceed towards ERROR
log.LogLevel=DEBUG

;Validation Configuration
[validation]
; If validation is set to strict, the PayPalModel would make sure that
; there are proper accessors (Getters and Setters) for each model
; objects. Accepted value is
; 'log'     : logs the error message to logger only (default)
; 'strict'  : throws a php notice message
; 'disable' : disable the validation
validation.level=strict

当我尝试使用我的应用的paypal沙盒版本处理付款时,我收到错误:

 exception 'PayPal\Exception\PayPalInvalidCredentialException' with message 'Credential not found for default user. Please make sure your configuration/APIContext has credential information' in D:\WebDev\htdocs\paypaltut\vendor\paypal\rest-api-sdk-php\lib\PayPal\Core\PayPalCredentialManager.php:154 Stack trace: 
Stack trace:
 #0 D:\WebDev\htdocs\paypaltut\vendor\paypal\rest-api-sdk-php\lib\PayPal\Rest\ApiContext.php(56): PayPal\Core\PayPalCredentialManager->getCredentialObject()

 #1 D:\WebDev\htdocs\paypaltut\vendor\paypal\rest-api-sdk-php\lib\PayPal\Handler\RestHandler.php(51): PayPal\Rest\ApiContext->getCredential()

 #2 D:\WebDev\htdocs\paypaltut\vendor\paypal\rest-api-sdk-php\lib\PayPal\Transport\PayPalRestCall.php(71): PayPal\Handler\RestHandler->handle(Object(PayPal\Core\PayPalHttpConfig), '{"payer_id":"6H...', Array)

 #3 D:\WebDev\htdocs\paypaltut\vendor\paypal\rest-api-sdk-php\lib\PayPal\Common\PayPalResourceModel.php(103): PayPal\Transport\PayPalRestCall->execute(Array, '/v1/payments/pa...', 'POST', '{"payer_id":"6H...', NULL)

 #4 D:\WebDev\htdocs\paypaltut\vendor\paypal\rest-api-sdk-php\lib\PayPal\Api\Payment.php(498): PayPal\Common\PayPalResourceModel::executeCall('/v1/payments/pa...', 'POST', '{"payer_id":"6H...', NULL, NULL, NULL)

 #5 D:\WebDev\htdocs\paypaltut\pay.php(36): PayPal\Api\Payment->execute(Object(PayPal\Api\PaymentExecution))
 #6 {main}

我已经完成了通过paypal开发人员的信息中心创建应用程序的过程,我尝试添加新的ApiContext到付费(返回网址)文件并仍然得到相同的错误。有谁知道如何解决这个问题?

哦,我正在使用v1.5.0 sdk和php 5.6.1

1 个答案:

答案 0 :(得分:9)

找到根本原因。

您忘记传递$ apiContext对象以执行try { $result = $payment->execute($execute); } catch(Exception $e) { die($e); } 代码中的调用。

try {
    $result = $payment->execute($execute, $apiContext);
}
catch(Exception $e){
    die($e);
}

将其更改为此,它应该有效:

static