当前位置: 首页 > 知识库问答 >
问题:

使用paypal/rest api sdk php时出现laravel PayPals集成错误

耿锦
2023-03-14

在我点击我的Web应用程序中的付款按钮时收到的错误下面,这可能是我的问题的解决方案,我已经查看了类似的问题,而不是似乎可以解决我的解决方案。访问 https://api.sandbox.paypal.com/v1/payments/payment 时获得 Http 响应代码 400。PayPal\核心\贝帕尔连接: 错误: 访问 https://api.sandbox.paypal.com/v1/payments/payment 时收到 Http 响应代码 400。{“名称”:“MALFORMED_REQUEST”,“消息”:“传入的 JSON 请求不映射到 API 请求”,“information_link”:“https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST”,“debug_id”:“7abde5aa538aa”}

下面是我的控制器PaypalController.php

<?php

namespace App\Http\Controllers;

use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Item;
use PayPal\Api\WebProfile;
use PayPal\Api\ItemList;
use PayPal\Api\InputFields;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;
use Redirect;
use Session;
use URL;
use App\Invoice;
use App\Project;
use App\Suborder;
use Str;
//Use Request;
use Auth;
use Config;
use DB;

class PaypalController extends Controller
{
    private $apiContext;

    public function __construct()
    {
        # Main configuration in constructor
        $paypalConfig = Config::get('paypal');

        $this->apiContext = new ApiContext(new OAuthTokenCredential(
                $paypalConfig['client_id'],
                $paypalConfig['secret'])
        );

        $this->apiContext->setConfig($paypalConfig['settings']);
    }

    public function pay_amount(Request $request, $id)
    {
       $id =DB::table('projects')->where('id', $id)->get();
        return view('projects.pay')
        ->with('id', $id);
    }

    public function payWithpaypal(Request $request, $id)
    {
        # We initialize the payer object and set the payment method to PayPal
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        # We insert a new order in the order table with the 'initialised' status
        // $project = new Project();
        // $project->user_name = Auth::user()->name;
        // $project->invoice_id = null;
        // $project->status = 'initialised';
        // $project->save();

        $project = Project::findOrFail($request->id);
        //$project = new Project();
        $project->update(['user_name' => (Auth::user()->name)]);
        $project->update(['invoice_id' => (null)]);
        $project->update(['status' => ('initialised')]);
        $project->save();

        # We need to update the order if the payment is complete, so we save it to the session
        Session::put('projectId', $project->getKey());

        # We get all the items from the cart and parse the array into the Item object

        //dd($project->project_id);

        $item = new Item();
        $items[] = (new Item())
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($project->amount);
            //->setName($project->project_id)
            //->setName($item->name)
            //->setQuantity($item->qty)
            //->setPrice($item->price);
            //->setPrice($project->total_amount);

            //->setPrice($request->get('amount')); 

        # We create a new item list and assign the items to it

        $itemList = new ItemList();
        $itemList->setItems(array($items));

        # Disable all irrelevant PayPal aspects in payment
        // $inputFields = new InputFields();
        // $inputFields->setAllowNote(true)
        //     ->setNoShipping(1)
        //     ->setAddressOverride(0);

        // $webProfile = new WebProfile();
        // $webProfile->setName(uniqid())
        //     ->setInputFields($inputFields)
        //     ->setTemporary(true);

        // $createProfile = $webProfile->create($this->apiContext);

        # We get the total price of the cart

        $amount = new Amount();
        $amount->setCurrency('USD')
                ->setTotal($project->amount);
            //->setTotal(Cart::subtotal());


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

        $redirectURLs = new RedirectUrls();
        $redirectURLs->setReturnUrl(URL::to('status'))
            ->setCancelUrl(URL::to('status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
        //$payment->setIntent('authorize')
            ->setPayer($payer)
            ->setRedirectUrls($redirectURLs)
            ->setTransactions(array($transaction));

        //$payment->setExperienceProfileId($createProfile->getId());
        //$payment->create($this->apiContext);


        try {

            $payment->create($this->apiContext);
            $execution = new PaymentExecution(); $result = $payment->execute($execution, $apiContext);


        } catch (\PayPal\Exception\PPConnectionException $ex) {

            if (\Config::get('app.debug')) {

                \Session::put('error', 'Connection timeout');
                return Redirect::to('/');

            } else {

                \Session::put('error', 'Some error occur, sorry for inconvenient');
                return Redirect::to('/');

            }

        }

        foreach ($payment->getLinks() as $link) {

            if ($link->getRel() == 'approval_url') {

                $redirect_url = $link->getHref();
                break;

            }

        }

        # We store the payment ID into the session
        Session::put('paypalPaymentId', $payment->getId());

        if (isset($redirectURL)) {
            return Redirect::away($redirectURL);
        }

        Session::put('error', 'There was a problem processing your payment. Please contact support.');

        return Redirect::to('/client/projects');
    }


    public function getPaymentStatus()
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');

        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {

            \Session::put('error', 'Payment failed');
            return Redirect::to('/');

        }

        $payment = Payment::get($payment_id, $this->_api_context);
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));

        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);

        if ($result->getState() == 'approved') {

            \Session::put('success', 'Payment success');
            return Redirect::to('/');

        }

        \Session::put('error', 'Payment failed');
        return Redirect::to('/');

    }

 
}```

共有1个答案

严烨
2023-03-14

PayPal-PHP-SDK和v1/支付API已弃用。

相反,请使用用于v2/Checkout/orders API的Checkout PHP SDK,如下所示:https://developer.paypal.com/docs/business/checkout/server-side-api-calls/#server-副api调用

您应该创建两条路线,一条用于“创建订单”,另一条为“捕获订单”。这些路由应仅返回/输出JSON数据(无HTML或文本)

将这两条路线与以下审批流配对:https://developer.paypal.com/demo/checkout/#/pattern/server

 类似资料:
  • 遇到未捕获的异常类型:PayPal \ Exception \ PayPalConnectionException 消息:访问https://API . sandbox . paypal . com/v1/payments/payment/PAYID-l 6 lqrca 096350664 r 714145g时得到Http响应代码401。 文件名:/home/mastai 9/public _ h

  • 我已经将我的android应用程序与Paypal集成在一起,并用Paypal沙箱凭据对其进行了测试。Ti测试与其他凭据,我创建了另一个帐户,当我测试这个,我得到错误说.... 请给我宝贵的建议和帮助我

  • 登录后,它生成了一个哈希值,但仍然给出错误“Some problem currened!try tain”。

  • 我正在尝试整合Paypal express checkout(场外)和payflow(场内)到我们的支付页面。 我已经成功地集成了paypal express结账按钮使用NVP和SOAP API和一切工作良好。 我还开始了payflow(旧XML API)的集成,并将其作为一个选项。 我的问题是我如何允许客户有2个选项在订单表单去同一个商户帐户?当前它是一个选项卡(移动到单选按钮)来显示支付选项。

  • 对于迁移管理,我决定使用Prisma Migrate,而不是节点pg Migrate(PostgreSQL)。我按照此链接中的说明操作,一切正常。然而,主要的挑战是,我的集成测试在尝试在测试数据库(而不是开发数据库)上运行迁移时失败。如何覆盖测试数据库的配置? 在节点pg migrate中,我可以在运行集成测试之前简单地提供配置:

  • 基本上我是按照这个指示做的:http://thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/ 但结果是: 尚未找到任何服务器 请求方法:获取请求URL:http://52.25.226.143/admin/ Django版本:1.5.11异常类型:ServerSelectionTimeoutError异常