Base.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <?php
  2. namespace app\common\Service\Pay\Provider;
  3. use think\Log;
  4. use think\Exception;
  5. use Yansongda\Pay\Pay;
  6. use Yansongda\Pay\Contract\HttpClientInterface;
  7. use app\common\Enum\ChannelEnum;
  8. use app\common\model\pay\Config as PayConfig;
  9. use app\common\Service\Pay\HttpClient;
  10. /**
  11. * 支付提供器基类
  12. * 封装 yansongda 支付库的基础功能
  13. */
  14. class Base
  15. {
  16. /**
  17. * yansongda 支付示例
  18. * @var Yansongda\Pay\Pay
  19. */
  20. protected $pay = null;
  21. /**
  22. * 支付参数
  23. * @var array
  24. */
  25. public $config = null;
  26. /**
  27. * 支付服务实例
  28. * @var mixed
  29. */
  30. protected $payService = null;
  31. /**
  32. * 平台标识
  33. * @var string
  34. */
  35. protected $platform = null;
  36. /**
  37. * 渠道标识
  38. * @var string
  39. */
  40. protected $channel = null;
  41. /**
  42. * 构造函数
  43. * @param mixed $payService
  44. * @param string $platform
  45. * @param string $channel
  46. */
  47. public function __construct($payService = null, $platform = null, $channel = null)
  48. {
  49. $this->payService = $payService;
  50. $this->platform = $platform;
  51. $this->channel = $channel;
  52. }
  53. /**
  54. * yansongda 支付初始化
  55. * @param string $payment 支付类型
  56. * @param array $config 配置参数
  57. * @param string $type 配置类型
  58. * @return void
  59. * @throws Exception
  60. */
  61. public function init($payment, $config = [], $type = 'normal')
  62. {
  63. try {
  64. $this->config = $this->getConfig($payment, $config, $type);
  65. $this->pay = Pay::config($this->config);
  66. // 使用自定义 HTTP 客户端(如果可用)
  67. Pay::set(HttpClientInterface::class, HttpClient::instance());
  68. } catch (\Exception $e) {
  69. Log::error('支付初始化失败: ' . $e->getMessage(), [
  70. 'payment' => $payment,
  71. 'platform' => $this->platform,
  72. 'channel' => $this->channel
  73. ]);
  74. throw new Exception('支付初始化失败: ' . $e->getMessage());
  75. }
  76. }
  77. /**
  78. * 获取支付的所有参数
  79. * @param string $payment 支付类型
  80. * @param array $config 额外配置
  81. * @param string $type 配置类型
  82. * @return array
  83. * @throws Exception
  84. */
  85. protected function getConfig($payment, $config = [], $type = 'normal')
  86. {
  87. try {
  88. // 获取平台配置
  89. $platformConfig = $this->getPlatformConfig();
  90. if (!$platformConfig) {
  91. throw new Exception('平台配置获取失败');
  92. }
  93. // extract() 函数从数组中将变量导入到当前的符号表。
  94. //该函数使用数组键名作为变量名,使用数组键值作为变量值。针对数组中的每个元素,将在当前符号表中创建对应的一个变量。
  95. //该函数返回成功设置的变量数目。
  96. extract($platformConfig);
  97. $params = $this->getPayConfig($payment, $paymentConfig ?? []);
  98. // 格式化支付参数
  99. $params['mode'] = (int)($params['mode'] ?? 0);
  100. $params = $this->formatConfig($params, ['app_id' => $app_id ?? ''], $type);
  101. // 合并传入的参数
  102. $params = array_merge($params, $config);
  103. // 合并参数
  104. $config = $this->baseConfig();
  105. $config = array_merge($config, [$payment => ['default' => $params]]);
  106. return $config;
  107. } catch (\Exception $e) {
  108. Log::error('获取支付配置失败: ' . $e->getMessage());
  109. throw new Exception('支付配置获取失败');
  110. }
  111. }
  112. /**
  113. * 获取平台配置参数
  114. * @return array
  115. * @throws Exception
  116. */
  117. protected function getPlatformConfig()
  118. {
  119. try {
  120. // 优先从渠道获取配置
  121. if ($this->channel) {
  122. $platformConfig = $this->getChannelConfig($this->channel);
  123. }
  124. if (!$platformConfig) {
  125. throw new Exception('平台配置不存在');
  126. }
  127. $paymentConfig = $platformConfig['payment'] ?? [];
  128. $app_id = $platformConfig['app_id'] ?? '';
  129. // compact() 函数创建一个包含变量名和它们的值的数组。
  130. return compact('paymentConfig', 'app_id');
  131. } catch (\Exception $e) {
  132. throw new Exception('获取平台配置失败: ' . $e->getMessage());
  133. }
  134. }
  135. /**
  136. * 根据平台以及支付方式获取支付配置表的配置参数
  137. * @param string $payment 支付类型
  138. * @param array $paymentConfig 支付配置
  139. * @return array
  140. * @throws Exception
  141. */
  142. protected function getPayConfig($payment, $paymentConfig)
  143. {
  144. try {
  145. $methods = $paymentConfig['methods'] ?? [];
  146. $payment_config = $paymentConfig[$payment] ?? 0;
  147. if (!in_array($payment, $methods)) {
  148. throw new Exception('当前平台未开启该支付方式: ' . $payment);
  149. }
  150. if ($payment_config) {
  151. $payConfig = PayConfig::where('id', $payment_config)->find();
  152. if (!$payConfig) {
  153. throw new Exception('支付配置不存在,ID: ' . $payment_config);
  154. }
  155. // 解析参数
  156. $params = $payConfig->params ?? '';
  157. if (is_string($params)) {
  158. $params = json_decode($params, true) ?: [];
  159. }
  160. return $params;
  161. }
  162. throw new Exception('支付配置参数不存在');
  163. } catch (\Exception $e) {
  164. throw new Exception('获取支付配置失败: ' . $e->getMessage());
  165. }
  166. }
  167. /**
  168. * 获取对应的支付方法名
  169. *
  170. * @param strign $payment
  171. * @return string
  172. */
  173. protected function getMethod($payment)
  174. {
  175. $method = [
  176. 'wechat' => [
  177. 'WechatOfficialAccount' => 'mp', //公众号支付 Collection
  178. 'WechatMiniProgram' => 'mini', //小程序支付 Collection
  179. 'H5' => 'wap', //手机网站支付 Response
  180. 'App' => 'app' // APP 支付 JsonResponse
  181. ],
  182. 'alipay' => [
  183. 'WechatOfficialAccount' => 'wap', //手机网站支付 Response
  184. 'WechatMiniProgram' => 'wap', //小程序支付
  185. 'H5' => 'wap', //手机网站支付 Response
  186. 'App' => 'app' //APP 支付 JsonResponse
  187. ],
  188. ];
  189. return $method[$payment][$this->platform];
  190. }
  191. /**
  192. * yansongda 基础配置
  193. *
  194. * @return void
  195. */
  196. protected function baseConfig()
  197. {
  198. $log_path = RUNTIME_PATH . 'log/pay/';
  199. if (!is_dir($log_path)) {
  200. @mkdir($log_path, 0755, true);
  201. }
  202. return [
  203. 'logger' => [ // optional
  204. 'enable' => true,
  205. 'file' => $log_path . 'pay.log',
  206. 'level' => config('app_debug') ? 'debug' : 'info', // 建议生产环境等级调整为 info,开发环境为 debug
  207. 'type' => 'daily', // optional, 可选 daily.
  208. 'max_file' => 30, // optional, 当 type 为 daily 时有效,默认 30 天
  209. ],
  210. 'http' => [ // optional
  211. 'timeout' => 5.0,
  212. 'connect_timeout' => 5.0,
  213. // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
  214. ],
  215. ];
  216. }
  217. /**
  218. * 格式化配置参数(子类需要实现)
  219. * @param array $config
  220. * @param array $data
  221. * @param string $type
  222. * @return array
  223. */
  224. protected function formatConfig($config, $data = [], $type = 'normal')
  225. {
  226. // 基础实现,子类可以重写
  227. return array_merge($config, $data);
  228. }
  229. /**
  230. * 根据渠道获取配置
  231. * @param string $channel
  232. * @return array|null
  233. */
  234. protected function getChannelConfig($channel)
  235. {
  236. // 根据渠道类型获取对应的配置
  237. if (ChannelEnum::isWechatChannel($channel)) {
  238. return $this->getWechatChannelConfig($channel);
  239. } elseif (ChannelEnum::isMiniProgramChannel($channel)) {
  240. return $this->getMiniProgramChannelConfig($channel);
  241. } else {
  242. return $this->getDefaultChannelConfig($channel);
  243. }
  244. }
  245. /**
  246. * 获取微信渠道配置
  247. * @param string $channel
  248. * @return array|null
  249. */
  250. protected function getWechatChannelConfig($channel)
  251. {
  252. return [
  253. 'payment' => [
  254. 'methods' => ['wechat'],
  255. 'wechat' => 1,
  256. 'alipay' => 0,
  257. ],
  258. 'app_id' => config('wechat.app_id', ''),
  259. ];
  260. }
  261. /**
  262. * 获取小程序渠道配置
  263. * @param string $channel
  264. * @return array|null
  265. */
  266. protected function getMiniProgramChannelConfig($channel)
  267. {
  268. return [
  269. 'payment' => [
  270. 'methods' => ['wechat', 'alipay'],
  271. 'wechat' => 1,
  272. 'alipay' => 1,
  273. ],
  274. 'app_id' => config('mini.app_id', ''),
  275. ];
  276. }
  277. /**
  278. * 获取默认渠道配置
  279. * @param string $channel
  280. * @return array|null
  281. */
  282. protected function getDefaultChannelConfig($channel)
  283. {
  284. return [
  285. 'payment' => [
  286. 'methods' => ['wechat', 'alipay'],
  287. 'wechat' => 1,
  288. 'alipay' => 1,
  289. ],
  290. 'app_id' => '',
  291. ];
  292. }
  293. /**
  294. * 验证支付环境
  295. * @param string $payment
  296. * @throws Exception
  297. */
  298. protected function validatePaymentEnvironment($payment)
  299. {
  300. if ($this->channel) {
  301. // 验证渠道是否支持支付
  302. if (!ChannelEnum::channelSupportsFeature($this->channel, 'payment')) {
  303. throw new Exception('当前渠道不支持支付功能');
  304. }
  305. // 微信支付特殊验证
  306. if ($payment === 'wechat') {
  307. if (!ChannelEnum::isWechatChannel($this->channel) && $this->channel !== ChannelEnum::CHANNEL_H5) {
  308. throw new Exception('当前渠道不支持微信支付');
  309. }
  310. }
  311. }
  312. }
  313. /**
  314. * 记录支付日志
  315. * @param string $message
  316. * @param array $context
  317. * @param string $level
  318. */
  319. protected function logPayment($message, $context = [], $level = 'info')
  320. {
  321. $context = array_merge($context, [
  322. 'payment' => $this->payService ? $this->payService->getPayment() : 'unknown',
  323. 'platform' => $this->platform,
  324. 'channel' => $this->channel,
  325. 'timestamp' => date('Y-m-d H:i:s')
  326. ]);
  327. Log::$level('支付日志: ' . $message, $context);
  328. }
  329. }