Files
dpl/app/Services/PaymentHealth/HttpsTransport.php
T

31 lines
1.8 KiB
PHP

<?php
namespace App\Services\PaymentHealth;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class HttpsTransport
{
public function request(string $method,string $url,array $fields=[]): array
{
$parts=parse_url($url);$host=strtolower($parts['host']??'');
if (($parts['scheme']??'')!=='https'||!$host||isset($parts['user'])||isset($parts['pass'])||isset($parts['fragment'])||($parts['port']??443)!==443) throw new RuntimeException('unsafe_url');
if(!in_array($host,config('payment_health.allowed_hosts',[]),true)) throw new RuntimeException('unapproved_host');
$ip=$this->publicAddress($host);
$client=Http::withoutRedirecting()->connectTimeout(10)->timeout(25)->withUserAgent('XB-PaymentHealth/1.0')
->withOptions(['verify'=>true,'curl'=>[CURLOPT_RESOLVE=>[$host.':443:'.(str_contains($ip,':')?'['.$ip.']':$ip)]]]);
$response=$method==='POST'?$client->asForm()->post($url,$fields):$client->get($url);
$body=$response->body();if(strlen($body)>2097152)throw new RuntimeException('oversized_cashier_response');
return ['status'=>$response->status(),'body'=>$body,'location'=>$response->header('Location'),'host'=>$host,'sha256'=>hash('sha256',$body)];
}
protected function publicAddress(string $host): string
{
if(filter_var($host,FILTER_VALIDATE_IP)) throw new RuntimeException('ip_literal_not_allowed');
$records=dns_get_record($host,DNS_A|DNS_AAAA);$ips=[];
foreach($records?:[] as $r){$ip=$r['ip']??$r['ipv6']??null;if(!$ip)continue;
if(!filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_NO_PRIV_RANGE|FILTER_FLAG_NO_RES_RANGE))throw new RuntimeException('nonpublic_dns');$ips[]=$ip;}
if(!$ips)throw new RuntimeException('dns_unavailable');
return $ips[0];
}
}