Illuminate \ Routing \ Redirect类的对象,或者无法将其转换为字符串

时间:2019-02-13 06:44:26

标签: php laravel

当我单击贝宝(PayPal)集成按钮时,它会显示此错误,该错误也在我的幼虫5.7标题中写了

下面是我的控制器代码

class PayPalController extends Controller
{
    /**
     * @var ExpressCheckout
     */
    protected $provider;
    protected $mail = false;

    protected $products = [ 
        '1' => [
            'name' => 'Product 1', 'price' => 97, 'qty' => 1, 'mail' => false
        ],
        '2' => [
            'name' => 'Product 2', 'price' => 147, 'qty' => 1, 'mail' => false
        ],
        '3' => [
            'name' => 'Product 3', 'price' => 1300, 'qty' => 1, 'mail' => false
        ],
        '4' => [
            'name' => 'Product 4', 'price' => 2000, 'qty' => 1, 'mail' => false
        ],
        '5' => [
            'name' => 'Product 5', 'price' => 997, 'qty' => 1, 'mail' => true
        ],
        '6' => [
            'name' => 'Product 6', 'price' => 147, 'qty' => 1, 'mail' => true
        ]
    ];

    public function __construct()
    {
        $this->provider = new ExpressCheckout();
    }

    public function getIndex(Request $request)
    {
        $response = [];
        if (session()->has('code')) {
            $response['code'] = session()->get('code');
            session()->forget('code');
        }

        if (session()->has('message')) {
            $response['message'] = session()->get('message');
            session()->forget('message');
        }
        $response['headerClass'] = 'tnit-inner-header';
        print_r($response); die;
        return view('payment-details', $response);
    }


    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getExpressCheckout($type)
    {

        $recurring = false;
        $cart = $this->getCheckoutData($type);

        try {
            $response = $this->provider->setExpressCheckout($cart, $recurring);
            if($this->mail){
                session()->put(['mail'=> Request::post()]);
            }
            return redirect($response['paypal_link']);
        } catch (\Exception $e) {
            $invoice = $this->createInvoice($cart, 'Invalid');
            session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);

        }
    }

    /**
     * Process payment on PayPal.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getExpressCheckoutSuccess($type, Request $request)
    {
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $token = $request->get('token');
        $PayerID = $request->get('PayerID');

        $cart = $this->getCheckoutData($type);

        // Verify Express Checkout Token
        $response = $this->provider->getExpressCheckoutDetails($token);

        if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
            if ($recurring === true) {
                $response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
                if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
                    $status = 'Processed';
                } else {
                    $status = 'Invalid';
                }
            } else {
                // Perform transaction on PayPal
                $payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
                $status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
            }

            $invoice = $this->createInvoice($cart, $status);

            if ($invoice->paid) {

                if($this->mail){
                    $data = [];
                    if (session()->has('mail')) {
                        $data = session()->get('mail');
                        session()->forget('mail');
                    }
                    $data['to'] = ['nayab2010@gmail.com', 'choyo@gomex.com'];
                    Mail::send('email.payment_details', $data,function ($message) use ($data) {
                        $message->from('info@choyogomex.com', 'Choyogomex');
                        $message->to($data['to']);
                        $message->subject('Payment Details');
                    });   
                }

                session()->put(['code' => 'success', 'message' => "Order $invoice->id has been paid successfully!"]);
            } else {
                session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
            }
            return redirect('/payment-details');
        }
    }

    /**
     * Parse PayPal IPN.
     *
     * @param \Illuminate\Http\Request $request
     */
    public function notify(Request $request)
    {
        if (!($this->provider instanceof ExpressCheckout)) {
            $this->provider = new ExpressCheckout();
        }

        $post = [
            'cmd' => '_notify-validate'
        ];
        $data = $request->all();
        foreach ($data as $key => $value) {
            $post[$key] = $value;
        }

        $response = (string) $this->provider->verifyIPN($post);

        $ipn = new IPNStatus();
        $ipn->payload = json_encode($post);
        $ipn->status = $response;

        $ipn->save();            
    }

    /**
     * Set cart data for processing payment on PayPal.
     *
     * @param bool $recurring
     *
     * @return array
     */
    protected function getCheckoutData($type)
    {
        $data = [];

        $order_id = Invoice::all()->count() + 1;
        $data['items'] = [];
        array_push($data['items'],$this->products[$type]);
        $data['return_url'] = url('/payment-process/'.$type);

        //$data['subscription_desc'] = 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id;
        $data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
        $data['invoice_description'] = "Order #$order_id Invoice";
        $data['cancel_url'] = url('/');

        $total = 0;
        foreach ($data['items'] as $item) {
            $total += $item['price'] * $item['qty'];
            if( $item['mail'] ){
                $this->mail = true;
            }
        }

        $data['total'] = $total;

        return $data;
    }

    /**
     * Create invoice.
     *
     * @param array  $cart
     * @param string $status
     *
     * @return \App\Invoice
     */
    protected function createInvoice($cart, $status)
    {
        $invoice = new Invoice();
        $invoice->title = $cart['invoice_description'];
        $invoice->price = $cart['total'];
        if (!strcasecmp($status, 'Completed') || !strcasecmp($status, 'Processed')) {
            $invoice->paid = 1;
        } else {
            $invoice->paid = 0;
        }
        $invoice->save();

        collect($cart['items'])->each(function ($product) use ($invoice) {
            $item = new Item();
            $item->invoice_id = $invoice->id;
            $item->item_name = $product['name'];
            $item->item_price = $product['price'];
            $item->item_qty = $product['qty'];

            $item->save();
        });

        return $invoice;
    }
}

这是我在控制器中使用的代码,其中的重定向代码使我无法理解

这是我的路线,我在这段代码中出错的地方找不到错误

Route::get('/payment/{type}','PayPalController@getExpressCheckout');
Route::post('/payment/{type}','PayPalController@getExpressCheckout');
Route::get('/payment-process/{type}','PayPalController@getExpressCheckoutSuccess');
Route::get('/payment-details','PayPalController@getIndex');

2 个答案:

答案 0 :(得分:0)

首先,我将向您展示如何使用自定义php集成贝宝。

  

1)这是Paypal的html表单。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Paypal Integration Test</title>
</head>
<body>

    <form class="paypal" action="payments.php" method="post" id="paypal_form">
        <input type="hidden" name="cmd" value="_xclick" />
        <input type="hidden" name="no_note" value="1" />
        <input type="hidden" name="lc" value="UK" />
        <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
        <input type="hidden" name="first_name" value="Customer's First Name" />
        <input type="hidden" name="last_name" value="Customer's Last Name" />
        <input type="hidden" name="payer_email" value="customer@example.com" />
        <input type="hidden" name="item_number" value="123456" / >
        <input type="submit" name="submit" value="Submit Payment"/>
    </form>

</body>

  

2)请求(操作页面)

payment.php页面将用于处理对PayPal的传出请求,以及处理付款后的传入响应。

// For test payments we want to enable the sandbox mode. If you want to put live
// payments through then this setting needs changing to `false`.
$enableSandbox = true;

// Database settings. Change these for your database configuration.
$dbConfig = [
    'host' => 'localhost',
    'username' => 'user',
    'password' => 'secret',
    'name' => 'example_database'
];

// PayPal settings. Change these to your account details and the relevant URLs
// for your site.
$paypalConfig = [
    'email' => 'user@example.com',
    'return_url' => 'http://example.com/payment-successful.html',
    'cancel_url' => 'http://example.com/payment-cancelled.html',
    'notify_url' => 'http://example.com/payments.php'
];

$paypalUrl = $enableSandbox ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr';

// Product being purchased.
$itemName = 'Test Item';
$itemAmount = 5.00;

// Include Functions
require 'functions.php';

// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])) {

    // Grab the post data so that we can set up the query string for PayPal.
    // Ideally we'd use a whitelist here to check nothing is being injected into
    // our post data.
    $data = [];
    foreach ($_POST as $key => $value) {
        $data[$key] = stripslashes($value);
    }

    // Set the PayPal account.
    $data['business'] = $paypalConfig['email'];

    // Set the PayPal return addresses.
    $data['return'] = stripslashes($paypalConfig['return_url']);
    $data['cancel_return'] = stripslashes($paypalConfig['cancel_url']);
    $data['notify_url'] = stripslashes($paypalConfig['notify_url']);

    // Set the details about the product being purchased, including the amount
    // and currency so that these aren't overridden by the form data.
    $data['item_name'] = $itemName;
    $data['amount'] = $itemAmount;
    $data['currency_code'] = 'GBP';

    // Add any custom fields for the query string.
    //$data['custom'] = USERID;

    // Build the query string from the data.
    $queryString = http_build_query($data);

    // Redirect to paypal IPN
    header('location:' . $paypalUrl . '?' . $queryString);
    exit();

} else {
    // Handle the PayPal response.
}

此外,这是本教程的完整linkLaravel支付集成教程。如果您有任何疑问,请随时在下面评论。

答案 1 :(得分:-1)

错误消息非常清楚,check the documentation on redirects。调用重定向方法时,您将收到一个RedirectResponse实例。检查您的代码并查找对redirectback的调用,并根据错误消息跟踪您对返回的数据的处理方式,我可以从错误消息中猜测您是显式的还是隐式的(调用具有string类型的提示参数)对该值执行string转换,正如您可以从错误中看到的那样,该转换不能自动完成。

这就是我看不到您的代码的全部内容。