coinwind/app/Tool/ThirdApi.php

118 lines
3.1 KiB
PHP

<?php
namespace App\Tool;
/**
* L3 Distribution
*/
class ThirdApi
{
const USER_AGENT = "Jose's Chrome/1.2";
const ID_BTC = 1;
const ID_ETH = 1027;
/**
* Send a Message to Tg.
*
* @param {string} msg: message
* @return {boolean}
*/
public static function sendToTg($msg): bool
{
// config
$groupid = -1001256080228;
$token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXRob3JpemVkIjp0cnVlLCJleHAiOjE2ODQ3NDM4ODYsInVzZXJuYW1lIjoic3VwZXJtYXN0ZXIifQ.1R-PvyUg_GXpJOk-7lQTBjBnw0cLRxajx5kNsvuY7OA';
$hc = new \GuzzleHttp\Client();
$resp = $hc->post(config('app.tg_url'), [
'headers' => [
'User-Agent' => self::USER_AGENT,
'Content-Type' => 'application/json',
'Token' => $token,
],
'json' => [
'groupid' => $groupid,
'msg' => $msg,
]
]);
// In fact, we dont care the result.
return true;
}
/**
* Price of Coin in USD.
*
* API Sample Return:
*
* {
* "data": {
* "symbol": "ETH",
* "id": "1027",
* "name": "Ethereum",
* "amount": 1,
* "last_updated": 1653295260000,
* "quote": [
* {
* "cryptoId": 2781,
* "symbol": "USD",
* "price": 2057.2269068671376,
* "lastUpdated": 1653295336000
* }
* ]
* },
* "status": {
* "timestamp": "2022-05-23T08:43:37.410Z",
* "error_code": "0",
* "error_message": "SUCCESS",
* "elapsed": "1",
* "credit_count": 0
* }
* }
*
* @param {integer} id: id of coin.(CoinMarketCap API)
* @return {float}
*/
public static function getPrice($id): float
{
$base_url = 'https://api.coinmarketcap.com/data-api/v3/tools/price-conversion';
$amount = 1;
$convert_id = 2781; // USD
$url = $base_url . "?amount=$amount&convert_id=$convert_id&id=$id";
$hc = new \GuzzleHttp\Client();
$resp = $hc->get($url, [
'headers' => [
'User-Agent' => self::USER_AGENT,
]
]);
if ($resp->getStatusCode() == 200 && $body = $resp->getBody()) {
$body->seek(0);
$data = $body->read(1024);
$d = json_decode($data, true);
if (
$d['status'] &&
$d['status']['error_code'] == 0 &&
$d['data'] &&
$d['data']['id'] == $id &&
$d['data']['quote']
) {
return $d['data']['quote'][0]['price'] ?? 0.0;
}
}
return 0.0;
}
/**
* Get Price of ETH in USD.
*/
public static function getETHPrice(): float
{
return self::getPrice(self::ID_ETH);
}
}