<?php
namespace App\Classes\Api;
use GuzzleHttp\Client;
class BitunixFuturesApi{
public string $base_url = "https://fapi.bitunix.com/";
public string $klineE = "api/v1/futures/market/kline";
public string $marginModeE = "api/v1/futures/account/change_margin_mode";
public string $apiKey = "random";
public string $secretKey = "random";
public function set_margin_mode($symbol="BTCUSDT", $marginMode = "ISOLATED", $marginCoin = "USDT"):array{
try{
$client = new Client();
$params = [
"marginMode" => $marginMode,
"symbol" => $symbol,
"marginCoin" => $marginCoin
];
$apiKey = $this->apiKey;
$secretKey = $this->secretKey;
$nonce = bin2hex(random_bytes(16));
$queryParamsString = '';
ksort($params);
foreach ($params as $key => $value) {
$queryParamsString .= $key . $value;
}
$body = json_encode($params);
$timestamp = (int)(microtime(true)*1000);
$digest = hash('sha256' , $nonce.$timestamp.$apiKey.$queryParamsString.$body);
$sign = hash('sha256', $digest.$secretKey);
$response = $client->post($this->base_url.$this->marginModeE,[
'headers'=>[
'api-key' => $apiKey,
'sign' =>$sign,
'timestamp' => $timestamp,
'nonce'=>$nonce,
'Content-Type'=> 'application/json'
],
'json'=>$params
]);
$response = json_decode($response->getBody()->getContents(),false,512,JSON_THROW_ON_ERROR);
if($response->code ==0){
return ['success'=>true, 'message'=>"Margin mode changed successfully", 'data' => $response->data];
}
return ['success'=>false, 'message'=>"Error changing margin mode", 'data' => $response->msg, 'code'=>$response->code];
}catch(\Exception $e){
return ['success'=>false, 'message'=>$e->getMessage(),'line'=>$e->getLine(),'file'=>$e->getFile(), 'data' => ''];
}
}
}
there是我的代码的片段以供控制器参考:
<?php
namespace App\Http\Controllers\Dashboard;
use App\Classes\Api\BitunixFuturesApi;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class TradeController extends Controller
{
public function __construct(){
$this->middleware('auth');
}
public function index(){
$bit = new BitunixFuturesApi();
$data = $bit->set_margin_mode("BTCUSDT", "CROSS");
return view('dashboard.trade')->with('data',$data);
}
}
我不知道您是否有工作。经过大量测试,看来代码中唯一的问题是时间戳。使用日期('ymdhisz')看起来像$ nonce这样的外观可以是任何随机字符串。长度似乎并不重要。我使用了具有各种随机长度的简单随机alpha-numeric String生成器。所有人都起作用