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

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

问题描述

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

我使用标准设置:

start.php:

 

index.php:

 <html lang="zh-cn"><头><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><!--脚本--><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"><!-- Modernizr --><!--样式表--><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 重置--><link rel="stylesheet" href="css/"><!-- 资源样式--><link rel="stylesheet" href="css/ongakuStandard.css"><!-- 资源样式--><link rel="stylesheet" href="../CSS/signupStyle.css" type="text/css"><!-- 用于注册表单及其所有部分--><!--字体--><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>文档</title><身体><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">产品名称</label><input class="medInput" type="text" name="product">

<div class="forminputdiv blockDisp"><label class="label-1 fw-120">数量</label><input class="medInput" type="number" step="any" min="0" max="15" name="quantity"><!-- <input class="medInput" type="string" name="quantity">-->

<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></选择>

<br><div class="forminputdiv flex-middle"><button class="submission fw-200" value="submit">Submit</button>

<input type="hidden" name="{{ csrf_key }}" value="{{ csrf_token }}" ></表单>

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

checkout.php:

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]);尝试{$payment->create($apiContext);}捕获 (PayPal\Exception\PayPalConnectionException $ex) {echo $ex->getCode();echo $ex->getData();} catch (Exception $ex) {死($ex);}$approvalUrl = $payment->getApprovalLink();header("位置:{$approvalUrl}");退出(1);

pay.php:

setPayerId($payerId);尝试{$result = $payment->execute($execute);}catch(异常$e){死($ e);}echo '已付款,谢谢!';

配置文件.ini:

;来自开发者门户的账户凭证[帐户]acct1.ClientId = AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRSacct1.ClientSecret = EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbLacct2.ClientId = TestClientIdacct2.ClientSecret = TestClientSecret;连接信息[http]http.ConnectionTimeOut = 60http.Retry = 1;http.Proxy=http://[用户名:密码]@主机名[:端口][/路径]模式=沙箱;服务配置[服务]service.EndPoint="https://api.sandbox.paypal.com";取消注释此行以与实时端点集成;service.EndPoint="https://api.paypal.com";记录信息[日志]log.LogEnabled=true;使用相对路径时,会创建日志文件;相对于作为入口点的 .php 文件;对于这个请求.您也可以提供绝对;这里的路径log.FileName=PayPal.log;日志级别可以是 FINE、INFO、WARN 或 ERROR 之一;日志记录在FINE"级别是最详细的,并且;当你朝着 ERROR 前进时减少log.LogLevel=调试;验证配置[验证];如果验证设置为严格,PayPalModel 将确保;每个模型都有适当的访问器(Getter 和 Setter);对象.接受的值为;'log' :仅将错误消息记录到记录器(默认);'strict' : 抛出一个 php 通知消息;'disable' : 禁用验证验证.级别=严格

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

 异常PayPal\Exception\PayPalInvalidCredentialException",消息未找到默认用户的凭据".请确保您的配置/APIContext 在 D:\WebDev\htdocs\paypaltut\vendor\paypal\rest-api-sdk-php\lib\PayPal\Core\PayPalCredentialManager.php:154 堆栈跟踪中具有凭据信息:堆栈跟踪:#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 {主要}

我已经通过 paypal 开发人员的仪表板完成了创建应用程序的过程,我尝试将新的 ApiContext 添加到支付(返回 url)文件中,但仍然出现相同的错误.有人知道如何解决这个问题吗?

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

解决方案

找到根本原因.

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

尝试{$result = $payment->execute($execute);}捕获(异常 $e){死($ e);}

把它改成这样,它应该可以工作了:

尝试{$result = $payment->execute($execute, $apiContext);}捕获(异常 $e){死($ e);}

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.

I use a standard set-up:

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

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}

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?

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

解决方案

Found the root cause.

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天全站免登陆