// +---------------------------------------------------------------------- namespace App\Services; /** * 生活充值接口管理-服务类 * @author laravel开发员 * @since 2020/11/11 * @package App\Services */ class DyrPayService extends BaseService { // 静态对象 protected static $instance = null; protected $apiUrl = 'http://1.huichikeji.cn/yrapi.php'; protected $apiKey = ''; protected $apiClientId = ''; protected $apiUrls = [ 'recharge' => '/index/recharge', 'query' => '/index/check', ]; public function __construct() { $apiUrl = ConfigService::make()->getConfigByCode('pay_api_url'); $this->apiUrl = $apiUrl ? $apiUrl : $this->apiUrl; $this->apiKey = ConfigService::make()->getConfigByCode('pay_api_key'); $this->apiClientId = ConfigService::make()->getConfigByCode('pay_ userid'); } /** * 静态入口 */ public static function make() { if (!self::$instance) { self::$instance = new static(); } return self::$instance; } /** * 充值 * @param $no 单号 * @param string $account // 充值账号 * @param string $productId 产品 ID * @param string $amount 充值面值 * @return bool */ public function recharge($no, $account, $productId, $amount) { if (empty($this->apiUrl) || empty($this->apiKey) || empty($this->apiClientId)) { $this->error = '接口参数未配置'; return false; } $cacheKey = "caches:dryPay:{$no}_{$productId}_{$account}"; if (RedisService::get($cacheKey . '_lock')) { $this->error = '充值处理中~'; return false; } $param = [ 'userid' => $this->apiClientId, // 商户ID 'product_id' => $productId, // 产品ID 'out_trade_num' => $no, // 单号 'amount' => $amount, // 金额 'mobile' => $account, // 手机号 'notify_url' => url('/api/notify/dyr/' . $productId), // 回调地址 ]; //请求参数 $param['sign'] = $this->makeSign($param); $url = $this->apiUrl.$this->apiUrls['recharge']; $result = httpRequest($url, $param, 'post', '', 5); $this->saveLog($cacheKey, ['url'=>$url,'param'=>$param,'result'=>$result]); return $result; } /** * 查询订单 * @param $nos 查询单号 * @return bool */ public function query($nos) { if (empty($this->apiUrl) || empty($this->apiKey) || empty($this->apiClientId)) { $this->error = '接口参数未配置'; return false; } $cacheKey = "caches:dryPay:queryOrder:".md5($nos); if (RedisService::get($cacheKey . '_lock')) { $this->error = '充值处理中~'; return false; } $param = [ 'userid' => $this->apiClientId, // 商户ID 'out_trade_nums' => $nos, // 单号 ]; //请求参数 $param['sign'] = $this->makeSign($param); $url = $this->apiUrl.$this->apiUrls['query']; $result = httpRequest($url, $param, 'post', '', 5); $this->saveLog($cacheKey, ['url'=>$url,'param'=>$param,'result'=>$result]); return $result; } /** * 日志 * @param $key * @param $data */ public function saveLog($key, $data) { if(env('APP_DEBUG')){ RedisService::set($key,$data, 7200); } } /** * 生成签名 * @param $param * @return string */ public function makeSign($param,$type=1) { // 字典排序 ksort($param); // 拼接签名串 $param = $type==2?urldecode(http_build_query($param)) : http_build_query($param); $sign_str = $param . '&apikey=' . $this->apiKey; // 签名 $sign = strtoupper(md5($type==2? $sign_str : urldecode($sign_str))); return $sign; } }