quantumca/laravel-coinpayments

Laravel 的 Coinpayments 支付

安装: 12

依赖: 0

建议者: 0

安全: 0

星级: 0

关注者: 0

分支: 32

类型:扩展

v1.1.5 2021-09-18 15:21 UTC

This package is auto-updated.

Last update: 2024-09-18 21:55:43 UTC


README

实现了大部分的 CoinPayments 功能。

Coinpayments Website

API 示例

需求

composer require quantumca/laravel-coinpayments

1. 安装服务提供者(如果 Laravel < 5.5)

// add directly from the app 
$app->register(\Kevupton\LaravelCoinpayments\Providers\LaravelCoinpaymentsServiceProvider::class);

或者

所有服务提供者都已在 config/app.php 配置文件中注册。

'providers' => [
    // Other Service Providers

    \Kevupton\LaravelCoinpayments\Providers\LaravelCoinpaymentsServiceProvider::class,
],

2. 配置

.env 配置

COINPAYMENTS_DB_PREFIX=cp_
COINPAYMENTS_MERCHANT_ID=your_unique_merchant_id
COINPAYMENTS_PUBLIC_KEY=generated_public_key
COINPAYMENTS_PRIVATE_KEY=generated_private_key
COINPAYMENTS_IPN_SECRET=your_custom_ipn_secret
COINPAYMENTS_IPN_URL=your_ipn_url
COINPAYMENTS_API_FORMAT=json
COINPAYMENTS_IPN_ROUTE_ENABLED=true
COINPAYMENTS_IPN_ROUTE_PATH=/api/ipn

执行 php artisan vendor:publish 以获取完整的配置文件。

配置:coinpayments.php

return array(

    // prefix to each of the tables in the database
    'database_prefix' => env('COINPAYMENTS_DB_PREFIX', 'cp_'),

    'merchant_id' => env('COINPAYMENTS_MERCHANT_ID'),

    // Your API public key associated with your coinpayments account
    'public_key' => env('COINPAYMENTS_PUBLIC_KEY'),

    // Your API private key associated with your coinpayments account
    'private_key' => env('COINPAYMENTS_PRIVATE_KEY'),

    // This is used to verify that an IPN is from us, use a good random string nobody can guess.
    'ipn_secret' => env('COINPAYMENTS_IPN_SECRET'),

    // URL for your IPN callbacks. If not set it will use the IPN URL in your Edit Settings page if you have one set.
    'ipn_url' => env('COINPAYMENTS_IPN_URL'),

    // The format of response to return, json or xml. (default: json)
    'format' => env('COINPAYMENTS_API_FORMAT', 'json'),

    // ALL logs all requests, ERROR logs only errors, and NONE never
    'log_level' => Log::LEVEL_ERROR,
    
    // Whether or not to have coinpayments automatically parse IPN's for you. If so please specify a PATH
    'route'           => [
        'enabled' => env('COINPAYMENTS_IPN_ROUTE_ENABLED', false),
        'path'    => env('COINPAYMENTS_IPN_ROUTE_PATH', '/api/ipn'),
    ],
);

3. 设置数据库

运行迁移以安装数据库表

php artisan migrate

4. 使用方法

简单交易

$transaction = \Coinpayments::createTransactionSimple($cost, $currency_base, $currency_received, $extra_details);

回调地址

$callbackAddress = \Coinpayments::getCallbackAddress($currency);

提款

$withdrawal = \Coinpayments::createWithdrawal($amount, $currency, $address, true);

批量提款 - 使用相同的提款值,但为数组形式

$mass_withdrawal = \Coinpayments::createMassWithdrawal([
    [
        'amount' => $amount1,
        'address' => $address1,
        'currency' => $currency1,
    ],
    [
        'amount' => $amount2,
        'address' => $address2,
        'currency' => $currency2,
    ],
]);

转换币种

$conversion = \Coinpayments::convertCoins($amount, $from, $to, $address = null);

提款信息

$info = \Coinpayments::getWithdrawalInfo($id);

转换信息

$info = \Coinpayments::getConversionInfo($id);

IPN 验证

Laravel Coinpayments 可以自动为您处理 IPN:只需指定路径,并通过环境变量启用。

COINPAYMENTS_IPN_ROUTE_ENABLED=true
COINPAYMENTS_IPN_ROUTE_PATH=/api/ipn

您可以通过监听以下事件来订阅模型事件

存款 - 当有人向回调地址存钱时
  • 存款创建 - 当存款被创建时
  • 存款更新 - 当存款被更新,但尚未完成时
  • 存款完成 - 当存款完成后(所有确认都已收到)
提款 - 当您从 API 提款时
  • 提款创建
  • 提款更新
  • 提款完成
交易 - 当您通过 API 进行交易时
  • 交易创建
  • 交易更新
  • 交易完成

然后只需通过向 App\Providers\EventServiceProvider 中添加监听器来订阅事件。

    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Kevupton\LarvelCoinpayments\Events\Deposit\DepositCompleted::class => [
            App\Listeners\DoSomethingOnDepositListener::class, // your own class listener for when a deposit is created
        ],
    ];

然后您可以对每个事件做同样的事情。

示例事件监听器

<?php

namespace App\Listeners;

use Kevupton\LaravelCoinpayments\Events\Deposit\DepositComplete;

class DoSomethingOnDepositListener
{

    /**
    * Handler for the DepositComplete event. 
    * Here we can do anything with the completed deposit object.
    */
    public function handle(DepositComplete $depositComplete)
    {
        var_dump($depositComplete->deposit->toArray());
    }

}

手动方法处理 IPNS

try {
    $ipn = \Coinpayments::validateIPNRequest($request);
    
    // do soemthing with the completed IPN
} catch (\Exception $e) {
    
    // transaction not completed.
}

4.1 示例控制器

CoinPayments 控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Kevupton\LaravelCoinpayments\Exceptions\IpnIncompleteException;
use Kevupton\LaravelCoinpayments\Models\Ipn;
use Kevupton\LaravelCoinpayments\Models\Transaction;

class CoinpaymentsController extends Controller
{
    const ITEM_CURRENCY = 'BTC';
    const ITEM_PRICE    = 0.01;

    /**
     * Purchase items using coinpayments payment processor
     *
     * @param Request $request
     * @return array
     */
    public function purchaseItems (Request $request)
    {
        // validate that the request has the appropriate values
        $this->validate($request, [
            'currency' => 'required|string',
            'amount'   => 'required|integer|min:1',
        ]);


        $amount   = $request->get('amount');
        $currency = $request->get('currency');

        /*
         * Calculate the price of the item (qty * ppu)
         */
        $cost = $amount * self::ITEM_PRICE;

        /** @var Transaction $transaction */
        $transaction = \Coinpayments::createTransactionSimple($cost, self::ITEM_CURRENCY, $currency);

        return ['transaction' => $transaction];
    }

    /**
     * Creates a donation transaction
     *
     * @param Request $request
     * @return array
     */
    public function donation (Request $request)
    {
        // validate that the request has the appropriate values
        $this->validate($request, [
            'currency' => 'required|string',
            'amount'   => 'required|integer|min:0.01',
        ]);

        $amount   = $request->get('amount');
        $currency = $request->get('currency');

        /*
         * Here we are donating the exact amount that they specify.
         * So we use the same currency in and out, with the same amount value.
         */
        $transaction = \Coinpayments::createTransactionSimple($amount, $currency, $currency);

        return ['transaction' => $transaction];
    }

    /**
     * Handled on callback of IPN
     *
     * @param Request $request
     */
    public function validateIpn (Request $request)
    {
        try {
            /** @var Ipn $ipn */
            $ipn = \Coinpayments::validateIPNRequest($request);

            // if the ipn came from the API side of coinpayments merchant
            if ($ipn->isApi()) {

                /*
                 * If it makes it into here then the payment is complete.
                 * So do whatever you want once the completed
                 */

                // do something here
                // Payment::find($ipn->txn_id);
            }
        }
        catch (IpnIncompleteException $e) {
            $ipn = $e->getIpn();
            /*
             * Can do something here with the IPN model if desired.
             */
        }
    }
}

5. 记录

通过在配置文件中选择 LEVEL_NONELEVEL_ERRORLEVEL_ALL 来调整记录。

日志将被保存在数据库中的 $prefix . 'log' 下。

贡献

请随时提交 pull request。任何帮助都受欢迎(Y)