Skip to content

Commit

Permalink
GuzzleHttp 替换 Curl
Browse files Browse the repository at this point in the history
  • Loading branch information
ZBrettonYe committed Jul 22, 2020
1 parent 01ed70d commit 49d402c
Show file tree
Hide file tree
Showing 19 changed files with 461 additions and 255 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
SESSION_CONNECTION=session
SESSION_LIFETIME=120

# Redis 设置
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ yarn-error.log
.phpunit.result.cache
_ide_helper_models.php
_ide_helper.php
/tests
10 changes: 5 additions & 5 deletions app/Http/Controllers/AdminController.php
Original file line number Diff line number Diff line change
Expand Up @@ -1212,23 +1212,23 @@ public function setConfig(Request $request): JsonResponse {
public function sendTestNotification(): JsonResponse {
if(self::$systemConfig['is_notification']){
$result = PushNotification::send('这是测试的标题', 'ProxyPanel测试内容');
if($result == false){
if($result === false){
return Response::json(['status' => 'fail', 'message' => '发送失败,请重新尝试!']);
}
switch(self::$systemConfig['is_notification']){
case 'serverChan':
if(!$result->errno){
if(!$result['errno']){
return Response::json(['status' => 'success', 'message' => '发送成功,请查看手机是否收到推送消息']);
}

return Response::json(['status' => 'fail', 'message' => $result? $result->errmsg : '未知']);
return Response::json(['status' => 'fail', 'message' => $result? $result['errmsg'] : '未知']);
break;
case 'bark':
if($result->code == 200){
if($result['code'] == 200){
return Response::json(['status' => 'success', 'message' => '发送成功,请查看手机是否收到推送消息']);
}

return Response::json(['status' => 'fail', 'message' => $result->message]);
return Response::json(['status' => 'fail', 'message' => $result['message']]);
break;
default:
}
Expand Down
10 changes: 10 additions & 0 deletions app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@
class Controller extends BaseController {
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

// 生成随机密码
public function makePasswd() {
return makeRandStr();
}

// 生成UUID
public function makeUUID() {
return Str::uuid();
}

// 生成网站安全码
public function makeSecurityCode(): string {
return strtolower(makeRandStr(8));
Expand Down
60 changes: 22 additions & 38 deletions app/Http/Controllers/Gateway/BitpayX.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

use App\Models\Payment;
use Auth;
use GuzzleHttp\Client;
use Illuminate\Http\JsonResponse;
use Log;
use Response;

class BitpayX extends AbstractPayment {
private $bitpayGatewayUri = 'https://api.mugglepay.com/v1/';
private $bitpayGatewayUrl = 'https://api.mugglepay.com/v1/';

public function purchase($request): JsonResponse {
$payment = $this->creatNewPayment(Auth::id(), $request->input('oid'), $request->input('amount'));
Expand All @@ -29,14 +31,13 @@ public function purchase($request): JsonResponse {

$result = json_decode($this->mprequest($data), true);


if($result['status'] === 200 || $result['status'] === 201){
$result['payment_url'] .= '&lang=zh';
Payment::whereId($payment->id)->update(['url' => $result['payment_url']]);

return Response::json([
'status' => 'success',
'url' => $result['payment_url'] .= '&lang=zh',
'url' => $result['payment_url'],
'message' => '创建订单成功!'
]);
}
Expand All @@ -52,35 +53,27 @@ private function prepareSignId($tradeno) {
$data_sign = [
'merchant_order_id' => $tradeno,
'secret' => parent::$systemConfig['bitpay_secret'],
'type' => 'FIAT',
'type' => 'FIAT'
];
ksort($data_sign);

return http_build_query($data_sign);
return http_build_query(ksort($data_sign));
}

private function mprequest($data, $type = 'pay') {
$headers = ['content-type: application/json', 'token: '.parent::$systemConfig['bitpay_secret']];
$curl = curl_init();
if($type === 'pay'){
$this->bitpayGatewayUri .= 'orders';
curl_setopt($curl, CURLOPT_URL, $this->bitpayGatewayUri);
curl_setopt($curl, CURLOPT_POST, 1);
$data_string = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
}elseif($type === 'query'){
$this->bitpayGatewayUri .= 'orders/merchant_order_id/status?id='.$data['merchant_order_id'];
curl_setopt($curl, CURLOPT_URL, $this->bitpayGatewayUri);
curl_setopt($curl, CURLOPT_HTTPGET, 1);
$client = new Client(['base_uri' => $this->bitpayGatewayUrl, 'timeout' => 10]);

if($type === 'query'){
$request = $client->get('orders/merchant_order_id/status?id='.$data['merchant_order_id'],
['json' => ['token' => parent::$systemConfig['bitpay_secret']]]);
}else{// pay
$request = $client->post('orders',
['json' => ['token' => parent::$systemConfig['bitpay_secret']], 'body' => json_encode($data)]);
}
if($request->getStatusCode() != 200){
Log::debug('BitPayX请求支付错误:'.var_export($request, true));
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
$data = curl_exec($curl);
curl_close($curl);

return $data;

return $request->getBody();
}

public function notify($request): void {
Expand All @@ -100,23 +93,14 @@ public function notify($request): void {
}
// 准备待签名数据
$str_to_sign = $this->prepareSignId($inputJSON['merchant_order_id']);
$resultVerify = $this->verify($str_to_sign, $inputJSON['token']);
$isPaid = $data != null && $data['status'] != null && $data['status'] === 'PAID';

if($resultVerify && $isPaid){
if($this->sign($str_to_sign) === $inputJSON['token'] && $isPaid){
$this->postPayment($inputJSON['merchant_order_id'], 'BitPayX');
$return['status'] = 200;
echo json_encode($return);
echo json_encode(['status' => 200]);
}else{
$return['status'] = 400;
echo json_encode($return);
echo json_encode(['status' => 400]);
}
exit();
}

private function verify($data, $signature): bool {
$mySign = $this->sign($data);

return $mySign === $signature;
}
}
12 changes: 10 additions & 2 deletions app/Http/Controllers/Gateway/EPay.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

namespace App\Http\Controllers\Gateway;

use App\Components\Curl;
use App\Models\Payment;
use Auth;
use GuzzleHttp\Client;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Response;

class EPay extends AbstractPayment {
// Todo Debug测试
public function purchase(Request $request): JsonResponse {
$payment = $this->creatNewPayment(Auth::id(), $request->input('oid'), $request->input('amount'));

Expand Down Expand Up @@ -39,7 +40,14 @@ public function purchase(Request $request): JsonResponse {
];
$data['sign'] = $this->sign($this->prepareSign($data));

$result = json_decode(Curl::send(self::$systemConfig['epay_url'].'/submit.php', $data), true);
$client = new Client(['timeout' => 5]);
$request = $client->get(self::$systemConfig['epay_url'].'/submit.php');
$result = json_decode($request->getBody(), true);

if($request->getStatusCode() != 200){
return Response::json(['status' => 'fail', 'message' => '网关处理失败!']);
}

if(!$result){
return Response::json(['status' => 'fail', 'message' => '支付处理失败!']);
}
Expand Down
8 changes: 5 additions & 3 deletions app/Http/Controllers/Gateway/PayPal.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

namespace App\Http\Controllers\Gateway;

use App\Components\Curl;
use App\Models\Order;
use App\Models\Payment;
use Auth;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Log;
Expand Down Expand Up @@ -40,8 +40,10 @@ public function __construct() {
];
$this->provider->setApiCredentials($config);
$this->exChange = 7;
$exChangeRate = json_decode(Curl::send('http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4'),
true);
$client = new Client(['timeout' => 5]);
$exChangeRate = json_decode($client->get('http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4')
->getBody(), true);

if($exChangeRate && $exChangeRate['success']){
$this->exChange = $exChangeRate['result']['rate'];
}
Expand Down
15 changes: 9 additions & 6 deletions app/Http/Controllers/NodeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -453,12 +453,15 @@ public function pingNode(Request $request): ?JsonResponse {
$result = NetworkDetection::ping($node->is_ddns? $node->server : $node->ip);

if($result){
$data[0] = $result['China Telecom']['time']?: '';
$data[1] = $result['China Unicom']['time']?: '';
$data[2] = $result['China Mobile']['time']?: '';
$data[3] = $result['Hong Kong']['time']?: '';

return Response::json(['status' => 'success', 'message' => $data]);
return Response::json([
'status' => 'success',
'message' => [
$result['telecom']['time']?: '',//电信
$result['Unicom']['time']?: '',// 联通
$result['move']['time']?: '',// 移动
$result['HongKong']['time']?: ''// 香港
]
]);
}

return Response::json(['status' => 'fail', 'message' => 'Ping访问失败']);
Expand Down
49 changes: 9 additions & 40 deletions app/helpers.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

use App\Components\Curl;
use GuzzleHttp\Client;

define('KB', 1024);
define('MB', 1048576);
Expand Down Expand Up @@ -163,48 +163,17 @@ function getClientIP() {

// 获取IPv6信息
if(!function_exists('getIPv6')){
/*
* {
* "longitude": 105,
* "latitude": 35,
* "area_code": "0",
* "dma_code": "0",
* "organization": "AS23910 China Next Generation Internet CERNET2",
* "country": "China",
* "ip": "2001:da8:202:10::36",
* "country_code3": "CHN",
* "continent_code": "AS",
* "country_code": "CN"
* }
*
* {
* "longitude": 105,
* "latitude": 35,
* "area_code": "0",
* "dma_code": "0",
* "organization": "AS9808 Guangdong Mobile Communication Co.Ltd.",
* "country": "China",
* "ip": "2409:8a74:487:1f30:5178:e5a5:1f36:3525",
* "country_code3": "CHN",
* "continent_code": "AS",
* "country_code": "CN"
* }
*/
function getIPv6($ip) {
$url = 'https://api.ip.sb/geoip/'.$ip;
$client = new Client(['timeout' => 5]);
$request = $client->get('https://api.ip.sb/geoip/'.$ip);
$message = json_decode($request->getBody(), true);

try{
$result = json_decode(Curl::send($url), true);
if(!is_array($result) || isset($result['code'])){
throw new RuntimeException('解析IPv6异常:'.$ip);
}

return $result;
}catch(Exception $e){
Log::error($e->getMessage());

return [];
if($request->getStatusCode() == 200){
return $message;
}

Log::debug('解析IPv6异常:'.$ip.PHP_EOL.var_export($request, true));
return false;
}
}

Expand Down
Loading

0 comments on commit 49d402c

Please sign in to comment.