Php 贝宝API:如何通过贝宝获得销售ID和退款?

Php 贝宝API:如何通过贝宝获得销售ID和退款?,php,rest,paypal,Php,Rest,Paypal,我正在使用PHP中的PayPal API创建交易,包括信用卡和PayPal本身。此外,我需要能够退还这些交易。我使用的代码大部分直接来自PayPalAPI示例,对于信用卡交易来说效果很好,但对于PayPal交易来说却失败了。具体地说,我正试图向下钻取支付对象并提取该销售的ID。通过信用卡生成的支付对象包含一个RelatedResources对象,该对象又包含带有ID的Sale对象,但通过PayPal生成的支付对象似乎不包含它们。所以,我的问题是,如何从通过PayPal支付的款项中检索销售ID 以

我正在使用PHP中的PayPal API创建交易,包括信用卡和PayPal本身。此外,我需要能够退还这些交易。我使用的代码大部分直接来自PayPalAPI示例,对于信用卡交易来说效果很好,但对于PayPal交易来说却失败了。具体地说,我正试图向下钻取支付对象并提取该销售的ID。通过信用卡生成的支付对象包含一个RelatedResources对象,该对象又包含带有ID的Sale对象,但通过PayPal生成的支付对象似乎不包含它们。所以,我的问题是,如何从通过PayPal支付的款项中检索销售ID

以下是我如何使用存储的信用卡创建付款:

    $creditCardToken = new CreditCardToken();
$creditCardToken->setCreditCardId('CARD-2WG5320481993380UKI5FSFI');

// ### FundingInstrument
// A resource representing a Payer's funding instrument.
// For stored credit card payments, set the CreditCardToken
// field on this object.
$fi = new FundingInstrument();
$fi->setCreditCardToken($creditCardToken);

// ### Payer
// A resource representing a Payer that funds a payment
// For stored credit card payments, set payment method
// to 'credit_card'.
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
    ->setFundingInstruments(array($fi));

// ### Amount
// Lets you specify a payment amount.
// You can also specify additional details
// such as shipping, tax.
$amount = new Amount();
$amount->setCurrency("USD")
    ->setTotal('1.00');

// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. 
$transaction = new Transaction();
$transaction->setAmount($amount)
    ->setDescription("Payment description");

// ### Payment
// A Payment Resource; create one using
// the above types and intent set to 'sale'
$payment = new Payment();
$payment->setIntent("sale")
    ->setPayer($payer)
    ->setTransactions(array($transaction));

// ###Create Payment
// Create a payment by calling the 'create' method
// passing it a valid apiContext.
// (See bootstrap.php for more on `ApiContext`)
// The return object contains the state.
try {
    $payment->create($apiContext);
} catch (PayPal\Exception\PPConnectionException $ex) {
    error_log($ex->getMessage());
    error_log(print_r($ex->getData(), true));
}
相比之下,以下是我如何进行贝宝支付。这是一个两步的过程。首先,用户被定向到PayPal的网站,然后,当他们返回我的网站时,付款被处理

第1部分:

$payer = new Payer();
$payer->setPaymentMethod("paypal");

$amount = new Amount();
$amount->setCurrency("USD")
    ->setTotal($userInfo['amount']);

$transaction = new Transaction();
$transaction->setAmount($amount)
    ->setDescription("Payment description");

// ### Redirect urls
// Set the urls that the buyer must be redirected to after 
// payment approval/ cancellation.
$baseUrl = 'http://example.com';
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/?success=true")
    ->setCancelUrl("$baseUrl/?success=false");

$payment = new Payment();
$payment->setIntent("sale")
    ->setPayer($payer)
    ->setRedirectUrls($redirectUrls)
    ->setTransactions(array($transaction));

try {
    $payment->create($apiContext);
} catch (PayPal\Exception\PPConnectionException $ex) {
    error_log($ex->getMessage());
    error_log(print_r($ex->getData(), true));
    return;
}

// ### Get redirect url
// The API response provides the url that you must redirect
// the buyer to. Retrieve the url from the $payment->getLinks()
// method
foreach($payment->getLinks() as $link) {
    if($link->getRel() == 'approval_url') {
        $redirectUrl = $link->getHref();
        break;
    }
}

// ### Redirect buyer to PayPal website
// Save payment id so that you can 'complete' the payment
// once the buyer approves the payment and is redirected
// bacl to your website.
//
// It is not really a great idea to store the payment id
// in the session. In a real world app, you may want to 
// store the payment id in a database.
$_SESSION['paymentId'] = $payment->getId();

if(isset($redirectUrl)) {
    $response->redirectUrl = $redirectUrl;
}
return $response;
下面是第2部分,当用户重定向到我的站点时,会显示一条“成功”消息:

$payment = Payment::get($lineitem->paypal_payment_ID, $apiContext);

// PaymentExecution object includes information necessary 
// to execute a PayPal account payment. 
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayer_id($_GET['PayerID']);

//Execute the payment
// (See bootstrap.php for more on `ApiContext`)
$payment->execute($execution, $apiContext);
下面是我如何退款的交易。API中的示例没有讨论如何检索销售ID,因此我深入研究了对象。通过PayPal进行的支付没有RelatedResources对象,因此失败:

    try {
    $payment = Payment::get('PAY-8TB50937RV8840649KI6N33Y', $apiContext);
    $transactions = $payment->getTransactions();
    $resources = $transactions[0]->getRelatedResources();//This DOESN'T work for PayPal transactions.

    $sale = $resources[0]->getSale();
    $saleID = $sale->getId();

    // ### Refund amount
    // Includes both the refunded amount (to Payer) 
    // and refunded fee (to Payee). Use the $amt->details
    // field to mention fees refund details.
    $amt = new Amount();
    $amt->setCurrency('USD')
        ->setTotal($lineitem->cost);

    // ### Refund object
    $refund = new Refund();
    $refund->setAmount($amt);

    // ###Sale
    // A sale transaction.
    // Create a Sale object with the
    // given sale transaction id.
    $sale = new Sale();
    $sale->setId($saleID);
    try {   
        // Refund the sale
        // (See bootstrap.php for more on `ApiContext`)
        $sale->refund($refund, $apiContext);
    } catch (PayPal\Exception\PPConnectionException $ex) {
        error_log($ex->getMessage());
        error_log(print_r($ex->getData(), true));
        return;
    }
} catch (PayPal\Exception\PPConnectionException $ex) {
    error_log($ex->getMessage());
    error_log(print_r($ex->getData(), true));
    return;
}

关于如何检索销售ID有什么想法吗?谢谢

函数
Payment::get()
不会返回所有必需的信息。 您需要将
getTransactions()
getRelatedResources()
函数应用于
executePayment()
函数返回的对象

.....
$payment = executePayment( $execution, $apiContext );
$transactions = $payment->getTransactions();
$resources = $transactions[0]->getRelatedResources();
.....

我已成功退款交易,并没有找到一个简单的方法。所以,我用了另一种方式。请尝试以下代码:

$apiContext = new ApiContext(new OAuthTokenCredential(
            "<CLIENT_ID>", "<CLIENT_SECRET>")
    );
    $payments = Payment::get("PAY-44674747470TKNYKRLI", $apiContext);
    $payments->getTransactions();
    $obj = $payments->toJSON();//I wanted to look into the object
    $paypal_obj = json_decode($obj);//I wanted to look into the object
    $transaction_id = $paypal_obj->transactions[0]->related_resources[0]->sale->id;
    $this->refund($transaction_id);//Call your custom refund method
$apiContext=新的apiContext(新的OAuthTokenCredential)(
"", "")
);
$payments=Payment::get(“PAY-446747470tknykrli”,$apiContext);
$payments->getTransactions();
$obj=$payments->toJSON()//我想看看这个物体
$paypal_obj=json_decode($obj)//我想看看这个物体
$transaction\u id=$paypal\u obj->transactions[0]->相关资源[0]->sale->id;
$this->退款($transaction\u id)//请致电您的自定义退款方法

干杯

您确定付款(“PAY-8TB50937RV8840649KI6N33Y”)已执行吗?只有当付款达到“已完成”状态,并且只有在付款执行时,才会创建销售。对于PayPal支付,在此之前,支付要么处于“已创建”状态,要么处于“已批准”状态。PayPal的某人刚刚确认,使用PayPal支付的款项不可退款,因此无法退款。下面是一篇通过php api退款的文章。嗯,getRelatedResources给我造成了一个未定义的索引错误,我喜欢这个api:-)错误是未定义的索引:第14行的\paypal\paypal\sdk core php\lib\paypal\Common\PPModel.php中的相关资源$transaction\u ref是什么意思?是$transaction\u id吗@Jubayer ArefinYes,它是$transaction_id,实际上是唯一的销售id。更新的答案。