PHP code example of smlv / sdk

1. Go to this page and download the library: Download smlv/sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

smlv / sdk example snippets


use Smlv\Sdk\SmlvClient;

$smlv = new SmlvClient([
    'api_url'       => 'https://api.smlvcoin.com',
    'api_key'       => 'your-api-key',
    'api_secret'    => 'your-api-secret',
    'widget_secret' => 'your-widget-secret',
]);

use Smlv\Sdk\SmlvWidgetGenerator;

$widget = new SmlvWidgetGenerator($smlv);

// $subscriber->id — the subscriber ID in your system.
// One user may have multiple subscribers — pass the subscriber ID, not the user ID!
//
// email — optional, used only to pre-fill the account creation form on first visit.
// Recommended order: 1) main contact email of the subscriber, 2) current user's email.
// If email is unknown — pass an empty string.

echo $widget->generateDepositWidget(
    externalSubscriberId: (string) $subscriber->id,
    email:                $subscriber->contactEmail ?? $currentUser->email ?? '',
    returnUrl:            'https://your-app.com/billing'
);

// Deposit funds
echo $widget->generateDepositWidget($subscriber->id, $email, $returnUrl, $options);

// Balance overview + sync
echo $widget->generateBalanceWidget($subscriber->id, $email, $options);

// Mini inline bar — balance + ⊕ deposit button (ideal for navbars)
echo $widget->generateMiniWidget($subscriber->id, $email, $options);

// Paginated transaction history
echo $widget->generateTransactionsWidget($subscriber->id, $email, $options);

// Full account management (overview / edit / danger zone)
echo $widget->generateManagementWidget($subscriber->id, $email, $options);

// Unified widget: "Create account" OR 4-tab dashboard (Balance | Transactions | Overview | Danger Zone)
echo $widget->generateAccountWidget($subscriber->id, $email, $options);

// Account
$account = $smlv->createAccount($email, ['first_name' => 'John', 'external_id' => '42']);
$account = $smlv->getAccount($accountReference);
$smlv->updateAccount($accountReference, ['last_name' => 'Doe']);
$smlv->closeAccount($accountReference);
$smlv->reactivateAccount($accountReference);

// Balance
$balance = $smlv->getBalance($accountReference);
$smlv->syncBalance($accountReference);

// Transactions
$smlv->createTransaction($accountReference, ['amount' => 50, 'currency' => 'USD']);
$txns = $smlv->getTransactions($accountReference, ['page' => 1, 'per_page' => 20]);

// Lookup
$account = $smlv->findAccountByEmail($email);

use Smlv\Sdk\SmlvWebhookHandler;

$handler = new SmlvWebhookHandler($smlv);

try {
    $event = $handler->handle($_POST, $_SERVER['HTTP_X_SMLV_SIGNATURE'] ?? '');

    match ($event['type']) {
        'balance.updated'       => syncUserBalance($event),
        'transaction.completed' => logTransaction($event),
        default                 => null,
    };

    http_response_code(200);
} catch (\Exception $e) {
    http_response_code(400);
    echo $e->getMessage();
}

// config/services.php
'smlv' => [
    'api_url'       => env('SMLV_API_URL', 'https://api.smlvcoin.com'),
    'api_key'       => env('SMLV_API_KEY'),
    'api_secret'    => env('SMLV_API_SECRET'),
    'widget_secret' => env('SMLV_WIDGET_SECRET'),
],

// AppServiceProvider::register()
$this->app->singleton(SmlvClient::class, fn() => new SmlvClient(
    config('services.smlv.api_key'),
    config('services.smlv.api_secret'),
    config('services.smlv.api_url'),
    config('services.smlv.widget_secret'),
));

// common/config/main-local.php  ← already in .gitignore
'components' => [
    'smlv' => [
        'class'        => \Smlv\Sdk\Yii2\SmlvComponent::class,
        'apiUrl'       => 'https://api.smlvcoin.com',
        'apiKey'       => 'pk_live_xxxxxxxxxxxx',
        'apiSecret'    => 'sk_live_xxxxxxxxxxxx',
        'widgetSecret' => 'ws_live_xxxxxxxxxxxx',
        'widgetUrl'    => 'https://cdn.smlvcoin.com',   // CDN base URL
        'appUrl'       => 'https://smlvcoin.com',       // used by generateDepositUrl()
        // 'widgetScriptVersion' => 'v2.2',             // override CDN version (optional)
    ],
],

// Full account management widget (subscriber detail page)
echo Yii::$app->smlv->widgetGenerator->generateAccountWidget(
    (string) $subscriber->id,
    $subscriber->email,
    ['prefill' => ['account_type' => 'legal']]
);

// Minimal navbar widget (default widgetType = 'mini')
echo \Smlv\Sdk\Yii2\SmlvBalanceWidget::widget([
    'subscriberId' => (string) $abonent->id,
    'email'        => $abonent->email,
]);

// Full account widget for subscriber page
echo \Smlv\Sdk\Yii2\SmlvBalanceWidget::widget([
    'subscriberId' => (string) $abonent->id,
    'email'        => $abonent->email,
    'widgetType'   => 'account',
    'prefill'      => ['account_type' => 'legal'],
]);

$depositUrl = Yii::$app->smlv->generateDepositUrl(
    (string) $subscriber->id,      // account reference
    Yii::$app->request->absoluteUrl // return URL after deposit
);

// CDN <script> tag only (place in <head> or before </body>)
echo $widget->buildScriptTag();          // async
echo $widget->buildScriptTag(defer: true); // defer

// Inline init only (place after the <div>)
echo $widget->generateInitSnippet(
    externalSubscriberId: $subscriber->id,
    email:                $email,  // optional — see email sourcing note above
    type:                 'balance',
    options:              ['theme' => 'dark'],
    selector:             '#my-balance-widget'
);

// Signed JWT token only (for manual JS queue push)
$token = $widget->generateToken($subscriber->id, $email, 'deposit');

use Smlv\Sdk\Yii2\SmlvChargeBehavior;

class Order extends ActiveRecord
{
    public function behaviors(): array
    {
        return [
            'smlvCharge' => [
                'class'       => SmlvChargeBehavior::class,
                'email'       => fn() => $this->user->email,
                'amount'      => fn() => $this->subtotal * 0.02,   // e.g. 2% fee
                'description' => fn() => 'Order #' . $this->id,
                'metadata'    => fn() => [
                    'order_id' => $this->id,
                    'plan'     => $this->plan_name,
                ],
            ],
        ];
    }
}

// common/traits/smlv/SmlvChargeableTrait.php  (your SaaS code)
namespace common\traits\smlv;

use Smlv\Sdk\Yii2\SmlvChargeBehavior;

trait SmlvChargeableTrait
{
    protected function smlvBehaviorConfig(): array
    {
        return [
            'class'       => SmlvChargeBehavior::class,
            'email'       => fn() => $this->getChargeEmail(),
            'amount'      => fn() => $this->getChargeAmount(),
            'description' => fn() => $this->getChargeDescription(),
            'metadata'    => fn() => $this->getChargeMetadata(),
        ];
    }

    abstract protected function getSmlvActionType(): ?string;

    public function getChargeAmount(): ?float
    {
        // Opt-in guard: skip SMLV charge when the subscriber has no SMLV account
        // (returns null) — traditional bank billing will apply instead.
        $accountRef = Yii::$app->smlv->billing->resolveAccountByEmail($this->getChargeEmail());
        if ($accountRef === null) {
            return null;
        }

        $eurPrice = SmlvPricelist::getPriceFor($this->getSmlvActionType());
        $rate     = $this->fetchSmlvRate();

        return ($eurPrice && $rate > 0) ? round($eurPrice / $rate, 8) : null;
    }

    // ... getChargeEmail(), getChargeDescription(), getChargeMetadata(), fetchSmlvRate()
}

// common/models/bill/Bill.php
use common\traits\smlv\SmlvChargeableTrait;

class Bill extends BaseDoc
{
    use SmlvChargeableTrait;

    public function behaviors(): array
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'smlvCharge' => $this->smlvBehaviorConfig(),
        ]);
    }

    // The only method you must implement — everything else is handled by the trait
    protected function getSmlvActionType(): ?string
    {
        return $this->doc_type === 'job_request'
            ? SmlvPricelist::TYPE_ORDER
            : SmlvPricelist::TYPE_BILL;
    }
}
js
window._smlvQueue = window._smlvQueue || [];
window._smlvQueue.push({
  token:    '<?= $widget->generateToken($subscriber->id, $email, 'deposit')