ServiceHelper.php 2.24 KB
<?php

namespace App\Helpers;

use Carbon\Carbon;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;

class ServiceHelper
{
    /**
     * @return string
     */
    public static function getServiceHost(): string
    {
        return config('services.provider.service_host', '');
    }

    /**
     * @return string
     */
    public static function getServiceSecret(): string
    {
        return config('services.provider.service_secret', '');
    }

    /**
     * 推送微信服务号
     * @param array<string,mixed> $data
     * @return \Illuminate\Http\Client\Response
     * @throws \JsonException
     */
    public static function sendWechatOfficial(array $data): Response
    {
        return self::send('WechatOfficialMessage', $data);
    }

    /**
     * 推送微信小程序
     * @param array<string,mixed> $data
     * @return \Illuminate\Http\Client\Response
     * @throws \JsonException
     */
    public static function sendWechatApp(array $data): Response
    {
        return self::send('WechatAppMessage', $data);
    }

    /**
     * 推送极光消息
     * @param array<string,mixed> $data
     * @return \Illuminate\Http\Client\Response
     * @throws \JsonException
     */
    public static function sendJPush(array $data): Response
    {
        return self::send('JPushMessage', $data);
    }

    /**
     * @param string              $channel
     * @param array<string,mixed> $data
     * @return \Illuminate\Http\Client\Response
     * @throws \JsonException
     */
    public static function send(string $channel, array $data): Response
    {
        $payload         = ['time' => Carbon::now()->timestamp, 'channel' => $channel, 'data' => $data];
        $payload['sign'] = self::getSign($payload);
        return Http::asJson()->post(self::getServiceHost() . '/api/provider', $payload);
    }

    /**
     * @param array<string,mixed> $payload
     * @return string
     * @throws \JsonException
     */
    private static function getSign(array $payload): string
    {
        $payload['data']   = json_encode($payload['data'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
        $payload['secret'] = self::getServiceSecret();
        ksort($payload);
        return md5(base64_encode(implode('&', $payload)));
    }
}