baklysystems/laravel-shop-extended

此软件包设置为向Laravel提供商店或电子商务功能(例如购物车、订单、交易和项目),以便进行可定制的构建。

2.20 2018-02-06 11:11 UTC

This package is auto-updated.

Last update: 2024-09-09 20:58:09 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

Laravel Shop 是一种灵活的方式,可以将商店功能添加到 Laravel 5.1。旨在成为工匠的电子商务解决方案。

Laravel商店将购物车、订单和支付添加到您的新项目或现有项目中;让您可以将任何模型转换为可购买的商品。

支持

PayPal Omnipay

内容

范围

当前版本包括

  • 商店商品(将现有模型转换为可添加到购物车和订单的可购买商品)
  • 购物车
  • 订单
  • 交易
  • 支付网关支持
  • PayPal
  • 事件

即将推出

  • 访客用户购物车
  • 发货订单
  • 优惠券
  • 产品和变体解决方案
  • 后台仪表板
  • 前端模板

安装

使用composer

composer require baklysystems/laravel-shop-extended

或者添加

"baklysystems/laravel-shop-extended": "2.19"

到您的composer.json中。然后运行 composer installcomposer update

然后在您的 config/app.php 中添加

BaklySystems\LaravelShop\LaravelShopProvider::class,

providers 数组中。

然后添加

'Shop'      => BaklySystems\LaravelShop\LaravelShopFacade::class,

aliases 数组中。

配置

config/auth.php 文件中设置配置值。此软件包将使用它们来引用用户表和模型。

发布此软件包的配置以进一步自定义表名、模型命名空间、货币和其他值。运行以下命令

php artisan vendor:publish

将在您的 app/config 目录中创建一个 shop.php 文件。

数据库设置

生成软件包迁移文件

php artisan laravel-shop:migration

以下命令将生成一个新的迁移文件,其中包含创建购物车和项目表的数据库命令。该文件将位于 database/migrations。根据您的软件需求添加额外的字段。

该命令还将创建一个数据库填充器以填充商店目录的状态和类型。

在数据库中创建模式

php artisan migrate

将填充器添加到 database/seeds/DatabaseSeeder.php

class DatabaseSeeder extends Seeder
{

  public function run()
  {
    Model::unguard();

    $this->call('LaravelShopSeeder');

    Model::reguard();
  }

}

运行填充器(先执行 composer dump-autoload

php artisan db:seed

模型

以下模型必须创建以使商店功能正常工作,这些模型可以根据您的需要进行自定义。

商品

创建一个Item模型

php artisan make:model Item

这将创建模型文件 app/Item.php,编辑它并使其看起来像(考虑您的应用命名空间)

<?php

namespace App;

use BaklySystems\LaravelShop\Models\ShopItemModel;

class Item extends ShopItemModel
{
}

Item 模型具有以下主要属性

  • id — 商品id。
  • sku — 库存单位,也称为您的商店中产品的唯一标识。
  • price — 商品价格。
  • tax — 商品税费。默认为0。
  • shipping — 商品运输费。默认为0。
  • currency — 当前版本默认使用美元。
  • quantity — 商品数量。
  • class — 作为可购买项使用的模型的类引用。当使用数组数据时为可选。
  • reference_id — 作为可购买项使用的模型的ID引用。当使用数组数据时为可选。
  • user_id — 所有者。
  • displayPrice — 适用于商店显示的价格值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayTax — 适用于商店显示的税值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayShipping — 适用于商店显示的运费值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayName — 基于模型的商品名称属性。
  • shopUrl — 基于模型的商品路由属性。
  • wasPurchased — 标志表示商品是否已购买。这基于配置文件中设置的状态。
  • created_at — 商品记录在数据库中创建的时间。
  • updated_at — 商品最后更新时间。

业务定义:用作 购物车项订单项 的商品。

购物车

创建一个购物车模型

php artisan make:model Cart

这将创建模型文件 app/Cart.php,编辑它并使其看起来像(考虑您的应用程序命名空间)

<?php

namespace App;

use BaklySystems\LaravelShop\Models\ShopCartModel;

class Cart extends ShopCartModel 
{
}

Item 模型具有以下主要属性

  • id — 购物车ID。
  • user_id — 所有者。
  • items — 购物车中的商品。
  • count — 购物车中商品的总数。
  • totalPrice — 购物车中所有商品的总价。
  • totalTax — 购物车中所有商品的总税,加上配置中设置的全球税。
  • totalShipping — 购物车中所有商品的运费。
  • total — 应收总额,包括总价、总税和总运费。
  • displayTotalPrice — 适用于商店显示的总价值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayTotalTax — 适用于商店显示的总税值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayTotalShipping — 适用于商店显示的总运费值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayTotal — 适用于商店显示的总金额值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • created_at — 购物车记录在数据库中创建的时间。
  • updated_at — 购物车最后更新时间。

订单

创建一个订单模型

php artisan make:model Order

这将创建模型文件 app/Order.php,编辑它并使其看起来像(考虑您的应用程序命名空间)

<?php

namespace App;

use BaklySystems\LaravelShop\Models\ShopOrderModel;

class Order extends ShopOrderModel 
{
}

Order 模型有以下主要属性

  • id — 订单ID或订单编号。
  • user_id — 所有者。
  • items — 订单中的商品。
  • transactions — 订单上进行的交易。
  • statusCode — 状态代码。
  • count — 订单中商品的总数。
  • totalPrice — 订单中所有商品的总价。
  • totalTax — 订单中所有商品的总税,加上配置中设置的全球税。
  • totalShipping — 订单中所有商品的运费。
  • total — 应收总额,包括总价、总税和总运费。
  • displayTotalPrice — 适用于商店显示的总价值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayTotalTax — 适用于商店显示的总税值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayTotalShipping — 适用于商店显示的总运费值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • displayTotal — 适用于商店显示的总金额值格式化。例如,“$9.99”而不是仅仅“9.99”。
  • created_at — 订单记录在数据库中创建的时间。
  • updated_at — 订单最后更新时间。

交易

创建一个交易模型

php artisan make:model Transaction

这将创建模型文件 app/Transaction.php,编辑它并使其看起来像(考虑您的应用程序命名空间)

<?php

namespace App;

use BaklySystems\LaravelShop\Models\ShopTransactionModel;

class Transaction extends ShopTransactionModel 
{
}

Order 模型有以下主要属性

  • id — 订单ID或订单编号。
  • order — 订单中的商品。
  • gateway — 使用的网关。
  • transaction_id — 网关返回的交易ID。
  • detail — 网关返回的详细信息。
  • token — 网关回调的令牌。
  • created_at — 订单记录在数据库中创建的时间。
  • updated_at — 订单最后更新时间。

用户

在您的现有 User 模型中使用 ShopUserTrait 特性。通过添加 use BaklySystems\LaravelShop\Traits\ShopUserTraituse ShopUserTrait,如下例所示

<?php

use BaklySystems\LaravelShop\Traits\ShopUserTrait;

class User extends Model {

	use Authenticatable, CanResetPassword, ShopUserTrait;

}

这将启用与 Cart 和商店所需的方法和属性的关联。

  • cart — 用户的购物车。
  • items — 商品(订单或购物车中的商品)。
  • orders — 用户的订单。

现有模型转换

Laravel Shop 包允许您将任何现有的 Eloquent 模型转换为可购买的物品,在商店中使用而不会牺牲任何现有功能。此功能将允许将模型添加到购物车或订单。这需要两个小步骤

在您的现有模型中使用 ShopItemTrait。通过添加 use BaklySystems\LaravelShop\Traits\ShopItemTraituse ShopItemTrait,如下例所示

<?php

use BaklySystems\LaravelShop\Traits\ShopItemTrait;

class MyCustomProduct extends Model {

	use ShopItemTrait;

	// MY METHODS AND MODEL DEFINITIONS........

}

sku(字符串)和 price(小数,20,2)字段添加到您的模型表的字段中。您还可以包括 name(字符串)、tax(小数,20,2)和 shipping(小数,20,2),尽管这些都是可选的。您可以通过创建一个新的迁移来做到这一点

php artisan make:migration alter_my_table

定义迁移如下例所示

<?php

class AlterMyTable extends Migration {

	public function up()
	{
		Schema::table('MyCustomProduct', function($table)
		{
			$table->string('sku')->after('id');
			$table->decimal('price', 20, 2)->after('sku');
			$table->index('sku');
			$table->index('price');
		});
	}

	public function down()
	{
		// Restore type field
		Schema::table('MyCustomProduct', function($table)
		{
			$table->dropColumn('sku');
			$table->dropColumn('price');
		});
	}

}

运行迁移

php artisan migrate
物品名称

默认情况下,Laravel Shop 将查找 name 属性来定义物品的名称。如果您的现有模型已将不同的属性分配给名称,请简单地在该模型的属性中定义它

<?php

use BaklySystems\LaravelShop\Traits\ShopItemTrait;

class MyCustomProduct extends Model {

	use ShopItemTrait;

	/**
	 * Custom field name to define the item's name.
	 * @var string
	 */
	protected $itemName = 'product_name';

	// MY METHODS AND MODEL DEFINITIONS........

}
物品 URL

您可以通过设置 itemRouteNameitemRouteParams 类属性来定义物品的 URL 属性。在以下示例中,定义的 URL 为显示产品配置文件的 product/{slug},必须对模型进行以下更改

<?php

use BaklySystems\LaravelShop\Traits\ShopItemTrait;

class MyCustomProduct extends Model {

	use ShopItemTrait;

    /**
     * Name of the route to generate the item url.
     *
     * @var string
     */
    protected $itemRouteName = 'product';

    /**
     * Name of the attributes to be included in the route params.
     *
     * @var string
     */
    protected $itemRouteParams = ['slug'];

	// MY METHODS AND MODEL DEFINITIONS........

}

自动加载转储

导出 composer 自动加载

composer dump-autoload

支付网关

可以在 shop.php 配置文件中的 gateways 数组中配置和添加已安装的支付网关,如下所示

'gateways' => [
    'paypal'            =>  BaklySystems\LaravelShopGatewayPaypal\GatewayPayPal::class,
    'paypalExpress'     =>  BaklySystems\LaravelShopGatewayPaypal\GatewayPayPalExpress::class,
],

PayPal

Laravel Shop 默认支持 PayPal。您可以使用 PayPal 的 直接借记卡PayPal 快速支付

要配置 PayPal 并了解如何使用网关,请访问 PayPal 网关包页面

Omnipay

安装 Omnipay 网关 以启用其他支付服务,如 2Checkout、Authorize.net、Stripe 等。

您可能需要了解 Omnipay 的工作方式。

使用

商店

考虑使用的商店方法

将价格或其他值格式化为配置中指定的价格格式

$formatted = Shop::format(9.99);
// i.e. this will return $9.99 or the format set in the config file.

购买流程

使用 Laravel Shop,您可以自定义事物以适应您的需求,尽管我们建议您将购买或结账流程标准化如下(以下将解释如何使用商店方法)

Purchase Flow

  • (步骤 1)- 用户查看他的购物车。
  • (步骤 2)- 继续选择要使用的网关。
  • (步骤 3)- 继续向选定的网关提供所需信息。
  • (步骤 4)- 在下订单前检查购物车并查看购物车。
  • (步骤 5)- 下订单。

支付网关

在调用任何商店方法之前,必须设置支付网关

// Select the gateway to use
Shop::setGateway('paypal');

echo Shop::getGateway(); // echos: paypal

您还可以访问网关类对象

$gateway = Shop::gateway();

echo $gateway; // echos: [{"id":"paypal"}] 

结账

一旦选择了支付网关,您可以通过以下方式调用购物车结账

// Checkout current users' cart
$success = Shop::checkout();

// Checkout q specific cart
$success = Shop::checkout($cart);

这将调用支付网关中的 onCheckout 函数并执行验证。此方法将返回一个布尔标志,指示操作是否成功。

订单放置

一旦选择了支付网关并且用户已结账,您可以调用订单放置如下

// Places order based on current users' cart
$order = Shop::placeOrder();

// Places order based on a specific cart
$order = Shop::placeOrder($cart);

注意: placeOrder() 将创建订单,将购物车中的所有项目与订单相关联,并清空购物车。Order 模型不包含添加或删除项目的功能,任何对购物车的修改都必须在下订单之前完成。在设计您的结账流程时请注意这一点。

这将调用支付网关中的 onCharge 函数并收取订单总金额。 placeOrder() 将返回一个 Order 模型,您可以使用它来验证状态并检索网关生成的交易。

支付

支付由网关处理,此包默认包含 PayPal。

您可以使用PayPal的直接信用卡PayPal Express支付方式。

要配置PayPal并了解如何使用其网关,请访问PayPal网关包页面。

异常

如果结账或placeOrder出现错误,您可以调用并查看相关异常

// On checkout
if (!Shop::checkout()) {
  $exception = Shop::exception();
  echo $exception->getMessage(); // echos: error
}

// Placing order
$order = Shop::placeOrder();

if ($order->hasFailed) {
  $exception = Shop::exception();
  echo $exception->getMessage(); // echos: error
}

关键异常存储在Laravel的日志中。

购物车

购物车是在数据库中为每个用户创建的,这意味着用户在登出时或切换到不同设备时可以保存其购物车。

让我们先调用或创建当前用户的购物车

// From cart
$cart = Cart::current();
// Once a cart has been created, it can be accessed from user
$user->cart;

注意:Laravel Shop目前不支持访客。

获取其他用户的购物车

$userId = 1;

$cart = Cart::findByUser($userId);

添加商品

让我们添加一个我们的测试和现有模型MyCustomProduct的一个项目

$cart = Cart::current()->add(MyCustomProduct::find(1));

默认情况下,添加方法将设置数量为1。

而不是添加3个MyCustomProduct

$cart = Cart::current();

$cart->add(MyCustomProduct::find(1), 3);

购物车中每个sku只能创建一个项目。如果添加了相同sku的项目,则只会保留一个项目,但其数量会增加

$product = MyCustomProduct::find(1);

// Adds 1
$cart->add($product);

// Adds 3
$cart->add($product, 3);

// Adds 2
$cart->add($product, 2);

echo $cart->count; // echos: 6

$second_product = MyCustomProduct::findBySKU('TEST');

// Adds 2 of product 'TEST'
$cart->add($second_product, 2);

// Count based on quantity
echo $cart->count; // echos: 8

// Count based on products
echo $cart->items->count(); // echos: 2

我们可以将一个项目的数量重置为给定的值

// Add 3
$cart->add($product, 3);

echo $cart->count; // echos: 3

// Reset quantity to 4
$cart->add($product, 4, $forceReset = true);

echo $cart->count; // echos: 4

添加不存在的模型项目

您可以通过将它们作为数组插入来添加不存在的项目,每个数组必须包含skuprice

// Adds unexistent item model PROD0001
$cart->add(['sku' => 'PROD0001', 'price' => 9.99]);

// Add 4 items of SKU PROD0002
$cart->add(['sku' => 'PROD0002', 'price' => 29.99], 4);

移除商品

让我们从购物车中移除我们的测试和现有模型MyCustomProduct

$product = MyCustomProduct::find(1);

// Remove the product from cart
$cart = Cart::current()->remove($product);

下面的示例将完全删除项目,但也可以只从购物车中删除一定数量的项目

// Removes only 2 from quantity
// If the quantity is greater than 2, then 1 item will remain in cart
$cart->remove($product, 2);

可以使用数组删除不存在的模型项目

// Removes by sku
$cart->remove(['sku' => 'PROD0001']);

清空购物车

$cart->clear();

这些方法可以串联使用

$cart->add($product, 5)
    ->add($product2)
    ->remove($product3)
    ->clear();

购物车方法

// Checks if cart has item with SKU "PROD0001"
$success = $cart->hasItem('PROD0001');

下单

您可以直接从购物车下订单,而不调用Shop类,尽管这只会创建数据库中的订单记录,不会处理支付。与使用Shop相同,在下订单后购物车将会清空。

// This will create the order and set it to the status in configuration
$order = $cart->placeOrder();

创建时可以强制设置状态

$order = $cart->placeOrder('completed');

显示

以下是如何在blade模板中显示购物车的示例

购物车中的项目数量

<span>Items in cart: {{ $cart->count }}</span>

购物车中的项目

<table>
	@foreach ($cart->items as $item) {
		<tr>
			<td>{{ $item->sku }}</td>
			<td><a href="{{ $item->shopUrl }}">{{ $item->displayName }}</a></td>
			<td>{{ $item->price }}</td>
			<td>{{ $item->displayPrice }}</td>
			<td>{{ $item->tax }}</td>
			<td>{{ $item->quantity }}</td>
			<td>{{ $item->shipping }}</td>
		</tr>
	@endforeach
</table>

购物车金额计算

<table>

	<tbody>
		<tr>
			<td>Subtotal:</td>
			<td>{{ $cart->displayTotalPrice }}</td>
            <td>{{ $cart->totalPrice }}</td>
		</tr>
		<tr>
			<td>Shipping:</td>
			<td>{{ $cart->displayTotalShipping }}</td>
		</tr>
		<tr>
			<td>Tax:</td>
			<td>{{ $cart->displayTotalTax }}</td>
		</tr>
	</tbody>

	<tfoot>
		<tr>
			<th>Total:</th>
			<th>{{ $cart->displayTotal }}</th>
            <th>{{ $cart->total }}</th>
		</tr>
	</tfoot>

</table>

商品

插入到购物车或订单中的模型或数组将被转换为SHOP项目,模型Item在商店内部使用。

可以从SHOP项目检索模型对象

// Lets assume that the first Cart item is MyCustomProduct.
$item = $cart->items[0];

// Check if item has model
if ($item->hasObject) {
	$myproduct = $item->object;
}

$item->object是已经加载的MyCustomProduct模型,我们可以直接访问其属性和方法,如下所示:

// Assuming MyCustomProduct has a types relationship.
$item->object->types;

// Assuming MyCustomProduct has myAttribute attribute.
$item->object->myAttribute;

以下商店方法适用于模型Item或使用ShopItemTrait的现有模型

$item = Item::findBySKU('PROD0001');

$item = MyCustomProduct::findBySKU('PROD0002');

// Quering
$item = Item::whereSKU('PROD0001')->where('price', '>', 0)->get();

订单

查找特定订单编号

$order = Order::find(1);

查找用户的订单

// Get orders from specific user ID.
$orders = Order::findByUser($userId);
// Get orders from specific user ID and status.
$canceled_orders = Order::findByUser($userId, 'canceled');

执行交易

您可以直接从订单中执行交易,而不调用Shop类,尽管这只会创建数据库中的交易记录,不会处理支付。

// This will create the order and set it to the status in configuration
$transaction = $order->placeTransaction(
		$gateway 				= 'my_gateway',
		$transactionId 	= 55555,
		$detail 				= 'Custom transaction 55555'
);

订单方法

$completed = $order->isCompleted
// Checks if order is in a specific status.
$success = $order->is('completed');

// Quering
// Get orders from specific user ID.
$orders = Order::whereUser($userId)->get();
// Get orders from specific user ID and status.
$completed_orders = Order::whereUser($userId)
		->whereStatus('completed')
		->get();

订单状态代码

默认状态代码

  • in_creation — 创建中的订单状态。或使用$order->isInCreation
  • pending — 等待支付。或使用$order->isPending
  • in_process — 处理中的发货。处理中的修订。或使用$order->isInProcess
  • completed — 当支付已完成并将项目交付给客户时。或使用$order->isCompleted
  • failed — 当支付失败时。或使用$order->hasFailed
  • canceled — 当订单被用户取消时。或使用$order->isCanceled

您可以使用自己的自定义状态代码。只需手动将其添加到order_status数据库表或创建一个类似于这样的自定义种子器:

class MyCustomStatusSeeder extends Seeder
{

  public function run()
  {

    DB::table('order_status')->insert([
		    [
		    		'code' 				=> 'my_status',
		    		'name' 				=> 'My Status',
		    		'description' => 'Custom status used in my shop.',
		    ],
		]);

  }
}

然后使用它如下:

$myStatusCode = 'my_status';

if ($order->is($myStatusCode)) {
	echo 'My custom status work!';
}

事件

Laravel Shop遵循Laravel 5指南来触发事件,创建您的处理程序和监听器,就像您通常使用它们一样。

以下是事件参考

事件处理程序示例

如何在处理程序中使用事件的示例

<?php

namespace App\Handlers\Events;

use App\Order;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

use BaklySystems\LaravelShop\Events\OrderCompleted;

class NotifyPurchase implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Handle the event.
     *
     * @param  OrderPurchased $event
     * @return void
     */
    public function handle(OrderCompleted $event)
    {
        // The order ID
        echo $event->id;

        // Get order model object
        $order = Order::find($event->id);

        // My code here...
    }
}

请记住,在事件提供程序中注册您的处理程序和监听器

        'BaklySystems\LaravelShop\Events\OrderCompleted' => [
            'App\Handlers\Events\NotifyPurchase',
        ],

支付网关开发

基于定制化的考虑,Laravel Shop 已被开发出来。允许社区扩展其功能。

缺失的支付网关可以轻松地作为外部包开发,然后在配置文件中进行配置。

将此项目作为您的包或 Laravel 设置的必需依赖项,并简单地从 Laravel Shop 核心类扩展,这里有一个 PayPal 示例

<?php

namespace Vendor\Package;

use BaklySystems\LaravelShop\Core\PaymentGateway;
use BaklySystems\LaravelShop\Exceptions\CheckoutException;
use BaklySystems\LaravelShop\Exceptions\GatewayException;

class GatewayPayPal extends PaymentGateway
{
    /**
     * Called on cart checkout.
     * THIS METHOD IS OPTIONAL, DONE FOR GATEWAY VALIDATIONS BEFORE PLACING AN ORDER
     *
     * @param Order $order Order.
     */
    public function onCheckout($cart)
    {
        throw new CheckoutException('Checkout failed.');
    }

    /**
     * Called by shop to charge order's amount.
     *
     * @param Order $order Order.
     *
     * @return bool
     */
    public function onCharge($order)
    {
        throw new GatewayException('Payment failed.');
        return false;
    }
}

网关至少需要 onCharge 方法。您可以根据需要添加更多。

创建后,您可以将它添加到 shop.php 配置文件中,如下所示

'gateways' => [
    'paypal'              =>  Vendor\Package\GatewayPaypal::class,
],

然后使用它,如下所示

Shop::setGateway('paypal');

交易

为了正确生成交易,您必须在 onCharge 设置时考虑 3 个属性

public function onCharge($order)
{
    // The transaction id generated by the provider i.e.
    $this->transactionId = $paypal->transactionId;

    // Custom detail of 1024 chars.
    $this->detail = 'Paypal: success';

    // Order status after method call.
    $this->statusCode = 'in_process';

    return true;
}
  • transactionId —— 供应商的交易 ID,将帮助识别交易。
  • detail —— 交易的自定义描述。
  • statusCode —— 在 onCharge 执行后,使用该订单状态代码更新订单。默认为 'completed'。

回调

Laravel Shop 支持需要回调的网关。为此,您需要为您的网关添加 2 个额外函数

<?php

namespace Vendor\Package;

use BaklySystems\LaravelShop\Core\PaymentGateway;
use BaklySystems\LaravelShop\Exceptions\CheckoutException;
use BaklySystems\LaravelShop\Exceptions\GatewayException;

class GatewayWithCallbacks extends PaymentGateway
{
    /**
     * Called by shop to charge order's amount.
     *
     * @param Order $order Order.
     *
     * @return bool
     */
    public function onCharge($order)
    {

        // Set the order to pending.
        $this->statusCode = 'pending';

        // Sets provider with the callback for successful transactions.
        $provider->setSuccessCallback( $this->callbackSuccess );

        // Sets provider with the callback for failed transactions.
        $provider->setFailCallback( $this->callbackFail );

        return true;
    }

    /**
     * Called on callback.
     *
     * @param Order $order Order.
     * @param mixed $data  Request input from callback.
     *
     * @return bool
     */
    public function onCallbackSuccess($order, $data = null)
    {
        $this->statusCode     = 'completed';

        $this->detail         = 'successful callback';

        $this->transactionId  = $data->transactionId;

        // My code...
    }

    /**
     * Called on callback.
     *
     * @param Order $order Order.
     * @param mixed $data  Request input from callback.
     *
     * @return bool
     */
    public function onCallbackFail($order, $data = null)
    {
        $this->detail       = 'failed callback';

        // My code...
    }
}

在上面的示例中,onCharge 不是创建完成的交易,而是创建一个挂起的交易,并指示供应商需要调用哪些 URL 来回调支付结果。

onCallbackSuccessonCallbackFail 方法由 Shop 在供应商回调其响应时调用,根据供应商使用的回调 URL 调用适当的函数。

onCallbackSuccess 方法将为结束的订单创建一个新的交易。

  • callbackSuccess —— 成功回调 URL,由供应商使用。
  • callbackFail —— 即失败回调 URL,由供应商使用。
  • token —— 即验证令牌。

异常

Laravel Shop 提供了您可以使用来报告错误的几个异常。

对于 onCheckout

  • CheckoutException
  • GatewayException
  • StoreException —— 此异常将在 Laravel 中记录,因此仅用于致命错误。

对于 onChangeonCallbackSuccessonCallbackFail

  • GatewayException
  • StoreException —— 此异常将在 Laravel 中记录,因此仅用于致命错误。

注意:Laravel Shop 不会捕获任何其他异常。如果抛出正常的 Exception 或任何其他异常,它将像通常一样中断方法,这将影响您的结账流程,例如在示例中,您想要从 placeOrder() 获取订单时。

示例

您可以看到我们制作的 PayPal 网关 作为示例。

许可证

Laravel Shop 是免费软件,根据 MIT 许可证条款分发。

更多信息

此包的架构和设计受到了 Zizaco/entrust 包的启发,我们想感谢他们的贡献者们的出色工作。

变更日志