php - Paypal SDK错误 "Credential not found for default user"

标签 php api rest xampp paypal

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

我使用标准设置:

开始.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));    

索引.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>

结帐.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);

支付.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!';

配置文件:

;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 添加到支付(返回 url)文件中,但仍然遇到相同的错误。有人知道如何解决这个问题吗?

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

最佳答案

找到根本原因。

您忘记传递 $apiContext 对象以在您的 pay.php 代码中执行调用。

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

改成这样,应该可以了:

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

关于php - Paypal SDK错误 "Credential not found for default user",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32099649/

相关文章:

azure - 如何在 Azure API 管理中打印 HTTP 请求 header 元素?

java - 如何查询预定进程(定时器事件)?

database - 从 JWT token 中隐藏内部用户 ID

php - 基于 Ajax PHP 的简单论坛

php - 从邻接表生成 megamenu

javascript - 脚本代码与宽度缩小的图像冲突

rest - 如何保护 RESTful API

php - PHP中的函数重载

php - cPanel JSON API2 editzone记录问题

javascript - Angular POST 到 API 不传递数据