Commit f45c307c by haojie

1

parent b05f894e
......@@ -116,5 +116,22 @@ public static function invalidJson(self $exception)
$exception->getHeaders());
}
public static function invalid($request, self $exception)
{
$data = [
'errors' => $exception->errors,
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'status_code' => $exception->getStatusCode(),
'data' => $exception->getData(),
];
if (app()->environment(['local'])) {
$data['trace'] = $exception->getTrace();
$data['time'] = microtime(true) - LARAVEL_START;
}
return response()->json($data, $exception->getStatusCode(),
$exception->getHeaders());
}
}
......@@ -4,6 +4,7 @@
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Throwable;
class Handler extends ExceptionHandler
......
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Service\TransferUserService;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function login(Request $request)
{
$data = $request->input();
$result = app(TransferUserService::class)->login($data);
return $this->success('success', $result);
}
}
......@@ -70,4 +70,19 @@ public function buy(Request $request)
return $this->success('success', $result);
}
// 本地打款获取redis任务
public function getRedisTask(Request $request)
{
$user = $request->user();
$result = app(TradeService::class)->getRedisTask($user);
return $this->success('success', $result);
}
// 打款回调
public function transferCallback(Request $request)
{
$data = $request->input();
$result = app(TradeService::class)->adminTransferCallback($data);
return $this->success('success', $result);
}
}
......@@ -3,19 +3,20 @@
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Log;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
// if (!$request->expectsJson()) {
// return route('login');
// }
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
class TransferUser extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable;
protected $table = 'transfer_user';
protected $guarded = [];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [
'role' => 'user'
];
}
}
......@@ -40,4 +40,18 @@ public function getTradeCheckCallbackUrl()
}
return $notify_url;
}
// 平台打款回调地址
public function getPlatformPayCallbackUrl()
{
$notify_url = '';
$api = '/api/inscription/local/task/callback';
// 判断是否本地环境
if (app()->environment('local')) {
$notify_url = 'http://192.168.1.5:8080' . $api;
} else {
$notify_url = config('app.url') . $api;
}
return $notify_url;
}
}
......@@ -2,6 +2,7 @@
namespace App\Service;
use App\Exceptions\UserException;
use App\Models\TransactionLog;
use Illuminate\Support\Facades\Log;
......@@ -11,32 +12,59 @@ class TransactionLogService
// 新增日志
public function create($params)
{
$model = TransactionLog::query();
$data = [];
$data['to'] = $params['to'];
$data['from'] = $params['from'];
$data['hash'] = $params['hash'];
$data['order_id'] = $params['order_id'];
// 状态
$data['status'] = TradeService::TRADE_STATUS_WAIT;
$data['type'] = $params['trade_type'];
$data['title'] = $params['title'];
// amount
// error_message
TransactionLog::query()->create($data);
// 判断金额字段是否存在
if (array_key_exists('amount', $params)) {
$data['amount'] = $params['amount'];
}
// hash是否存在
if (array_key_exists('hash', $params)) {
$data['hash'] = $params['hash'];
$res = $model->where('hash', $data['hash'])->first();
if ($res) {
throw new UserException(1, '支付hash已存在');
}
}
// error_message
$create = TransactionLog::query()->create($data);
if ($create) {
return $create->id;
}
throw new UserException(1, '日志创建失败');
}
public function update($data)
{
// callback status 1:失败 2:成功 3:支付成功,接收地址错误
$model = TransactionLog::query()->where('order_id', $data['id'])
$message = $data['message'] ?? '';
$model = TransactionLog::query()->where('id', $data['log_id'])
->where('type', $data['type'])
->where('to', $data['to'])
->where('from', $data['from'])
->where('hash', $data['hash']);
->where('from', $data['from']);
if ($data['type'] == TradeService::TRADE_TYPE_PAY) {
// 添加金额
$model->where('amount', $data['amount']);
}
$model->update(['status' => $data['status']]);
$update = ['status' => $data['status']];
if (array_key_exists('hash', $data)) {
$update['hash'] = $data['hash'];
}
// 判断message
$log = $model->first();
if ($log) {
if ($message) {
$error_message = $log->error_message ?? [];
$error_message[] = $message;
$update['error_message'] = $error_message;
}
$log->update($update);
}
}
}
<?php
namespace App\Service;
use App\Exceptions\UserException;
use App\Models\TransferUser;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
class TransferUserService
{
protected function respondWithToken($token)
{
return [
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60 * 24
];
}
public function login($data)
{
$credentials = Arr::only($data, ['username', 'password']);
$username = $credentials['username'] ?? '';
$password = $credentials['password'] ?? '';
$adminUsers = TransferUser::where('username', $username)->first();
if (blank($adminUsers)) {
throw new UserException(1, '账号不存在');
}
// if (!\Hash::check($password, $adminUsers->password)) {
// throw new UserException(1, '密码错误');
// }
if ($password !== $adminUsers->password) {
throw new UserException(1, '密码错误');
}
$token = auth('api')->login($adminUsers);
// 查询电脑管理
return $this->respondWithToken($token);
}
}
......@@ -11,7 +11,8 @@
"inertiajs/inertia-laravel": "^0.6.9",
"laravel/framework": "^9.19",
"laravel/sanctum": "^3.0",
"laravel/tinker": "^2.7"
"laravel/tinker": "^2.7",
"php-open-source-saver/jwt-auth": "^2.1"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
......
......@@ -14,7 +14,7 @@
*/
'defaults' => [
'guard' => 'web',
'guard' => 'api',
'passwords' => 'users',
],
......@@ -38,7 +38,11 @@
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
'provider' => 'transfer_user',
],
'api' => [
'driver' => 'jwt',
'provider' => 'transfer_user',
],
],
......@@ -65,10 +69,10 @@
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
'transfer_user' => [
'driver' => 'database',
'table' => 'transfer_user',
],
],
/*
......@@ -93,6 +97,12 @@
'expire' => 60,
'throttle' => 60,
],
'transfer_user' => [
'provider' => 'transfer_user',
'table' => 'transfer_user',
'expire' => 60,
'throttle' => 60,
],
],
/*
......
This diff is collapsed. Click to expand it.
......@@ -19,16 +19,18 @@ public function up()
$table->text('inscription')->comment('铭文数据');
// 原始金额--卖家输入的
$table->decimal('original_amount', 20, 8)->comment('原始金额');
// 后台收款账号
$table->string('admin_account')->comment('后台收款账号');
// 卖家卖出时的收款地址
$table->string('sell_admin_account')->comment('卖家卖出时的收款地址');
// 买家买入时的收款地址
$table->string('buy_admin_account')->nullable()->comment('买家买入时的收款地址');
// 卖出手续费比例
$table->integer('sell_fee')->default(0)->comment('卖出手续费比例');
// 卖出收取的实际手续费
$table->integer('sell_fee_amount')->default(0)->comment('卖出收取的实际手续费');
$table->decimal('sell_fee')->default(0)->comment('卖出手续费比例');
// 卖出转账时收取的实际费用
$table->decimal('sell_real_amount', 20, 8)->default(0)->comment('卖出收取的实际手续费');
// 买入手续费比例
$table->integer('buy_fee')->default(0)->comment('买入手续费比例');
// 买入收取的实际手续费
$table->integer('buy_fee_amount')->default(0)->comment('买入收取的实际手续费');
$table->decimal('buy_fee')->default(0)->comment('买入手续费比例');
// 买入收取的实际费用(买家应该支付的金额)
$table->decimal('buy_real_amount', 20, 8)->default(0)->comment('买入收取的实际手续费');
// 订单状态
$table->integer('status')->default(0)->comment('订单状态');
......@@ -47,6 +49,7 @@ public function up()
$table->string('buyer_pay_hash')->nullable()->comment('买家支付hash');
// 买家接收铭文hash
$table->string('buyer_receive_inscription_hash')->nullable()->comment('买家接收铭文hash');
// 卖家地址
$table->string('seller_address')->nullable()->comment('卖家地址');
// 买家地址
......
......@@ -21,7 +21,7 @@ public function up()
//from
$table->string('from')->comment('付款人地址');
// 交易hash
$table->string('hash')->comment('交易hash');
$table->string('hash')->nullable()->comment('交易hash');
// 状态
$table->unsignedTinyInteger('status')->default(0)->comment('交易状态');
// 交易类型(铭文,转账)
......
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('transfer_user', function (Blueprint $table) {
$table->id();
$table->string('username')->comment('用户名');
$table->string('password')->comment('密码');
$table->string('email')->nullable()->comment('邮箱');
$table->string('phone')->nullable()->comment('手机号');
$table->text('remark')->nullable()->comment('备注');
$table->text('user_info')->nullable()->comment('用户信息');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('transfer_user');
}
};
......@@ -25,13 +25,14 @@
<div class="service-fee-box">
<div class="service-fee-line">
<div class="label">总价格</div>
<div class="value">${{ realPrice }}</div>
<div class="value">${{ info.buy_real_amount }}</div>
</div>
</div>
</div>
</template>
<template #footer>
<div class="buy-dialog-footer">
<t-button @click="testSubmit">测试按钮</t-button>
<t-button class="buy-cancel-button" @click="visible = false"
>取消</t-button
>
......@@ -69,18 +70,7 @@ const app_info = inject(inertia_data);
const confirmPrice = ref("");
const userAddress = computed(() => store.getters["user/address"]);
// 根据输入的价格计算可获得usdt
const realPrice = computed(() => {
const { fee, info } = props;
if (info.original_amount && fee) {
return (
parseFloat(info.original_amount + "") +
info.original_amount * (parseFloat(fee + "") / 100)
);
}
});
//
// 0xdac17f958d2ee523a2206206994597c13d831ec7
const submitAdmin = async (
hash: string,
address: string,
......@@ -93,13 +83,20 @@ const submitAdmin = async (
id: id,
});
if (res.code == 0) {
showMessage("已提交,请等待");
showMessage("已提交,请等待", "success");
return;
}
} catch (e) {
console.log(e);
}
};
const testSubmit = () => {
submitAdmin(
"0x762acfc0e06bd403ba4acf772b799b4f9b514fb7d89c161ce23ba0307e562a2c",
"0x51eF357cf7204DB2a6e31750817F709a10c86f37",
"1"
);
};
// 立即购买
const onSubmit = async () => {
......@@ -114,7 +111,11 @@ const onSubmit = async () => {
showMessage("缺少必要的数据");
return;
}
const hash = await fox_EtherPay(receipt_account, realPrice.value);
const hash = await fox_EtherPay(
receipt_account,
address,
props.info.buy_real_amount
);
if (hash) {
// 提交到后台校验
submitAdmin(hash, address, id);
......
......@@ -6,30 +6,65 @@ import { ConvertToHexadecimal } from "@/utils/tool";
let eth: any = window;
// 发起交易--小狐狸-tp支付
export const fox_EtherPay = async (to: string, price: number) => {
export const fox_EtherPay = async (to: string, from: string, price: number) => {
try {
// 代币地址
const USDT = "0xc5a25e92e691635BDd6DF2e904633Dc3152360cD";
const provider = new ethers.providers.Web3Provider(eth.ethereum);
const signer = new ethers.providers.Web3Provider(
eth.ethereum
).getSigner();
const tokenContract = new ethers.Contract(USDT, ERC20ABI, provider);
// const tokenBalance = await tokenContract.balanceOf(
// eth.ethereum.selectedAddress
// );
// const tokenAmount = ethers.utils.parseUnits(
// ethers.utils.formatUnits(price),
// 18
// );
let tokenAmount = price * Math.pow(10, 18);
let big_num = BigInt(Math.floor(tokenAmount));
console.log(big_num);
const tokenSigner = tokenContract.connect(signer);
const transaction = await tokenSigner.transfer(to, big_num);
console.log(transaction);
console.log(transaction.hash);
return transaction.hash ? transaction.hash : "";
let is_local = true;
if (is_local) {
let eth: any = window;
// 转换后的收款地址
let MyNewAddress = to.substring(2).padStart(64, "0");
// 实际价格--props.price
// 测试价格
// let price = 0.01;
// 转换后的价格
let newPrice = (price * Math.pow(10, 6))
.toString(16)
.padStart(64, "0");
// 小狐狸支付
const result: any = await eth.ethereum.request({
method: "eth_sendTransaction",
params: [
{
// 用户钱包地址
from: from,
// 支付代币类型
to: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
// gas价格
// gasPrice: "0x12a05f200",
// gas: "0x16e360",
// 交易数据十六进制 交易0xa9059cbb 目标钱包地址(我们的钱包地址) 交易金额(十六转换)
data: "0xa9059cbb" + MyNewAddress + newPrice,
},
],
});
if (result) {
// hash
return result;
}
return "";
} else {
// old 0xc5a25e92e691635BDd6DF2e904633Dc3152360cD
// 代币地址
const USDT = "0xa1629DB8F5DE4Be28d21b157e42E0a6a46Fd68f4";
const provider = new ethers.providers.Web3Provider(eth.ethereum);
const signer = provider.getSigner();
const tokenContract = new ethers.Contract(USDT, ERC20ABI, provider);
// const tokenBalance = await tokenContract.balanceOf(
// eth.ethereum.selectedAddress
// );
// const tokenAmount = ethers.utils.parseUnits(
// ethers.utils.formatUnits(price),
// 18
// );
let tokenAmount = price * Math.pow(10, 18);
let big_num = BigInt(Math.floor(tokenAmount));
console.log(big_num);
const tokenSigner = tokenContract.connect(signer);
const transaction = await tokenSigner.transfer(to, big_num);
console.log(transaction);
console.log(transaction.hash);
return transaction.hash ? transaction.hash : "";
}
} catch (e: any) {
console.log(e);
if (e.code) {
......
......@@ -36,14 +36,20 @@
Route::get('/market', 'TradeController@inscriptionList');
// buy
Route::post('/buy', 'TradeController@buy');
// 本地转账登录
Route::post('/transfer/login', 'AuthController@login');
});
// // 需要登录
// Route::group([
// 'middleware' => 'auth:admin_api',
// ], function () {
// });
// 本地话接口--需要登录
Route::group([
'middleware' => 'auth:api',
'prefix' => '/local',
], function () {
// 获取转账任务
Route::get('/task', 'TradeController@getRedisTask');
// 转账任务回调
Route::post('/task/callback', 'TradeController@transferCallback');
});
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment