Base.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. 'douyin' => [
  189. 'DouyinMiniProgram' => 'mini', //抖音小程序的
  190. ],
  191. ];
  192. return $method[$payment][$this->platform];
  193. }
  194. /**
  195. * yansongda 基础配置
  196. *
  197. * @return void
  198. */
  199. protected function baseConfig()
  200. {
  201. $log_path = RUNTIME_PATH . 'log/pay/';
  202. if (!is_dir($log_path)) {
  203. @mkdir($log_path, 0755, true);
  204. }
  205. return [
  206. 'logger' => [ // optional
  207. 'enable' => true,
  208. 'file' => $log_path . 'pay.log',
  209. 'level' => config('app_debug') ? 'debug' : 'info', // 建议生产环境等级调整为 info,开发环境为 debug
  210. 'type' => 'daily', // optional, 可选 daily.
  211. 'max_file' => 30, // optional, 当 type 为 daily 时有效,默认 30 天
  212. ],
  213. 'http' => [ // optional
  214. 'timeout' => 5.0,
  215. 'connect_timeout' => 5.0,
  216. // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
  217. ],
  218. ];
  219. }
  220. /**
  221. * 格式化配置参数(子类需要实现)
  222. * @param array $config
  223. * @param array $data
  224. * @param string $type
  225. * @return array
  226. */
  227. protected function formatConfig($config, $data = [], $type = 'normal')
  228. {
  229. // 基础实现,子类可以重写
  230. return array_merge($config, $data);
  231. }
  232. /**
  233. * 根据渠道获取配置
  234. * @param string $channel
  235. * @return array|null
  236. */
  237. protected function getChannelConfig($channel)
  238. {
  239. // 根据渠道类型获取对应的配置
  240. if (ChannelEnum::isWechatChannel($channel)) {
  241. return $this->getWechatChannelConfig($channel);
  242. } elseif (ChannelEnum::isMiniProgramChannel($channel)) {
  243. return $this->getMiniProgramChannelConfig($channel);
  244. } else {
  245. return $this->getDefaultChannelConfig($channel);
  246. }
  247. }
  248. /**
  249. * 获取微信渠道配置
  250. * @param string $channel
  251. * @return array|null
  252. */
  253. protected function getWechatChannelConfig($channel)
  254. {
  255. return [
  256. 'payment' => [
  257. 'methods' => ['wechat'],
  258. 'wechat' => 1,
  259. 'alipay' => 0,
  260. ],
  261. 'app_id' => config('wechat.app_id', ''),
  262. ];
  263. }
  264. /**
  265. * 获取小程序渠道配置
  266. * @param string $channel
  267. * @return array|null
  268. */
  269. protected function getMiniProgramChannelConfig($channel)
  270. {
  271. return [
  272. 'payment' => [
  273. 'methods' => ['wechat', 'alipay'],
  274. 'wechat' => 1,
  275. 'alipay' => 1,
  276. ],
  277. 'app_id' => config('mini.app_id', ''),
  278. ];
  279. }
  280. /**
  281. * 获取默认渠道配置
  282. * @param string $channel
  283. * @return array|null
  284. */
  285. protected function getDefaultChannelConfig($channel)
  286. {
  287. return [
  288. 'payment' => [
  289. 'methods' => ['wechat', 'alipay'],
  290. 'wechat' => 1,
  291. 'alipay' => 1,
  292. ],
  293. 'app_id' => '',
  294. ];
  295. }
  296. /**
  297. * 验证支付环境
  298. * @param string $payment
  299. * @throws Exception
  300. */
  301. protected function validatePaymentEnvironment($payment)
  302. {
  303. if ($this->channel) {
  304. // 验证渠道是否支持支付
  305. if (!ChannelEnum::channelSupportsFeature($this->channel, 'payment')) {
  306. throw new Exception('当前渠道不支持支付功能');
  307. }
  308. // 微信支付特殊验证
  309. if ($payment === 'wechat') {
  310. if (!ChannelEnum::isWechatChannel($this->channel) && $this->channel !== ChannelEnum::CHANNEL_H5) {
  311. throw new Exception('当前渠道不支持微信支付');
  312. }
  313. }
  314. }
  315. }
  316. /**
  317. * 记录支付日志
  318. * @param string $message
  319. * @param array $context
  320. * @param string $level
  321. */
  322. protected function logPayment($message, $context = [], $level = 'info')
  323. {
  324. $context = array_merge($context, [
  325. 'payment' => $this->payService ? $this->payService->getPayment() : 'unknown',
  326. 'platform' => $this->platform,
  327. 'channel' => $this->channel,
  328. 'timestamp' => date('Y-m-d H:i:s')
  329. ]);
  330. Log::$level('支付日志: ' . $message, $context);
  331. }
  332. }