PayPal SDK错误“找不到默认用户的凭据"; [英] PayPal SDK error "Credential not found for default user"

查看:112
本文介绍了PayPal SDK错误“找不到默认用户的凭据";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to integrate the PayPal SDK into my site but have run into a problem which I cannot find a solution for in the documentation or via Stackoverflow.

我使用标准设置:

start.php:

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:

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:

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:

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

当我尝试使用我的应用程序的贝宝沙盒版本处理付款时,出现错误消息:

When I attempt to process the payment using the paypal sandbox version of my app, I get the error:

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

I have gone through the process of creating the app through the paypal developer's dashboard, I've tried adding a new ApiContext to teh pay (return url ) file and still get the same error. anybody know how to fix this one?

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

oh an I'm using the v1.5.0 sdk and php 5.6.1

推荐答案

找到了根本原因.

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

You forgot to pass $apiContext object to execute call in your pay.php code.

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

将其更改为此,它应该可以工作:

Change it to this, and it should work:

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

这篇关于PayPal SDK错误“找不到默认用户的凭据";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆