AlipayTradeWapService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace service;
  12. use app\wap\model\activity\EventSignUp;
  13. use app\wap\model\store\StoreOrder;
  14. use think\Log;
  15. use think\Request;
  16. use think\Url;
  17. use behavior\wechat\PaymentBehavior;
  18. use service\HookService;
  19. use service\SystemConfigService;
  20. class AlipayTradeWapService
  21. {
  22. /**
  23. * 异步通知地址
  24. * @var string
  25. */
  26. protected static $notifyUrl;
  27. /**
  28. * 同步跳转地址
  29. * @var mixed
  30. */
  31. protected static $returnUrl;
  32. /**
  33. * 支付宝公钥
  34. * @var mixed
  35. */
  36. protected static $alipayPublicKey;
  37. /**
  38. * 应用appid
  39. * @var mixed
  40. */
  41. protected static $alipayAppId;
  42. /**
  43. * 应用私钥
  44. * @var mixed
  45. */
  46. protected static $alipayPrivateKey;
  47. /**
  48. * 编码格式
  49. * @var mixed|string
  50. */
  51. protected static $charset = 'UTF-8';
  52. /**
  53. * 请求网管
  54. * @var string
  55. */
  56. protected static $gatewayUrl = 'https://openapi.alipay.com/gateway.do';
  57. /**
  58. * 加密方式
  59. * @var mixed|string
  60. */
  61. protected static $signType = 'RSA2';
  62. /**
  63. * 是否开启调试模式
  64. * @var bool
  65. */
  66. public static $isDeBug = true;
  67. /**
  68. * 获取不到配置信息错误次数
  69. * @var int
  70. */
  71. private static $ErrorCount = 0;
  72. /**
  73. * 获取不到配置信息错误最大次数
  74. * @var int
  75. */
  76. private static $ErrorSum = 3;
  77. /**
  78. * AlipayTradeWapService constructor.
  79. * @param array $confing
  80. * @throws \Exception
  81. */
  82. public function __construct($confing = [])
  83. {
  84. self::$ErrorCount++;
  85. if (self::$ErrorCount >= self::$ErrorSum) return exception('请配置支付宝公钥私钥APPID');
  86. if ((!self::$alipayAppId || !self::$alipayPublicKey || !self::$alipayPrivateKey) && !$confing) self::confing(true);
  87. if (isset($confing['returnUrl'])) self::$returnUrl = $confing['returnUrl'];
  88. if (isset($confing['notifyUrl'])) self::$returnUrl = $confing['notifyUrl'];
  89. if (isset($confing['signType'])) self::$signType = $confing['signType'];
  90. if (isset($confing['charset'])) self::$charset = $confing['charset'];
  91. if (isset($confing['alipay_app_id'])) self::$alipayAppId = $confing['alipay_app_id'];
  92. if (isset($confing['alipay_public_key'])) self::$alipayPublicKey = $confing['alipay_public_key'];
  93. if (isset($confing['alipay_private_key'])) self::$alipayPrivateKey = $confing['alipay_private_key'];
  94. if (!self::$alipayAppId || !self::$alipayPublicKey || !self::$alipayPrivateKey) exception('请配置支付宝公钥私钥APPID');
  95. self::$ErrorCount = 0;
  96. }
  97. /**
  98. * 设置加密方式
  99. * @param $signType
  100. * @return $this
  101. */
  102. public function setSignType($signType)
  103. {
  104. self::$signType = $signType;
  105. return $this;
  106. }
  107. /**
  108. * 设置同步回调地址
  109. * @param $returnUrl
  110. * @return $this
  111. */
  112. public function setReturnUrl($returnUrl)
  113. {
  114. self::$returnUrl = $returnUrl;
  115. return $this;
  116. }
  117. /**
  118. * 设置异步回调地址
  119. * @param $notifyUrl
  120. */
  121. public function setNotifyUrl($notifyUrl)
  122. {
  123. self::$notifyUrl = $notifyUrl;
  124. return $this;
  125. }
  126. /**
  127. * 设置业务参数
  128. * @param array $biz_content
  129. * @return string
  130. */
  131. protected static function setBizContent(array $biz_content = [])
  132. {
  133. if (isset($biz_content['passback_params'])) $biz_content['passback_params'] = urlencode($biz_content['passback_params']);
  134. if (isset($biz_content['trade_no']) && empty($biz_content['trade_no'])) unset($biz_content['trade_no']);
  135. $bizContent = json_encode($biz_content);
  136. //打印业务参数
  137. self::$isDeBug && self::WriteLog($bizContent);
  138. return $bizContent;
  139. }
  140. /**
  141. * 获取同步回调地址
  142. * @return mixed
  143. */
  144. public function getReturnUrl()
  145. {
  146. return self::$returnUrl;
  147. }
  148. /**
  149. * 获取异步回调地址
  150. * @return mixed
  151. */
  152. public function getNotifyUrl()
  153. {
  154. return self::$notifyUrl;
  155. }
  156. /**
  157. * 读取系统配置赋值给静态变量 并加载支付宝官方支付sdk
  158. * @param bool $isReturn
  159. * @return AlipayTradeWapService
  160. */
  161. public static function confing($isReturn = false)
  162. {
  163. $confing = SystemConfigService::more([
  164. 'alipay_public_key',
  165. 'alipay_app_id',
  166. 'alipay_private_key',
  167. ]);
  168. self::$alipayAppId = isset($confing['alipay_app_id']) ? trim($confing['alipay_app_id']) : '';
  169. self::$alipayPublicKey = isset($confing['alipay_public_key']) ? trim($confing['alipay_public_key']) : '';
  170. self::$alipayPrivateKey = isset($confing['alipay_private_key']) ? trim($confing['alipay_private_key']) : '';
  171. self::$returnUrl = SystemConfigService::get('site_url') . Url::build('wap/Alipay/alipay_success_synchro');
  172. self::$notifyUrl = SystemConfigService::get('site_url') . Url::build('wap/Alipay/alipay_success_notify');
  173. vendor('alipay.AopSdk');
  174. if ($isReturn == false) return new self;
  175. }
  176. /**
  177. * 静态调用初始化数据
  178. * @return AlipayTradeWapService
  179. */
  180. public static function init()
  181. {
  182. return self::confing();
  183. }
  184. /**
  185. * 支付宝异步回调
  186. */
  187. public static function handleNotify()
  188. {
  189. self::init()->AliPayNotify(function ($data, $result) {
  190. if($result && isset($data->out_trade_no) && $data->passback_params) {
  191. if($data->passback_params=='special') {
  192. StoreOrder::where('order_id', $data->out_trade_no)->where('type',0)->update(['trade_no' => $data->trade_no]);
  193. }elseif ($data->passback_params=='signup'){
  194. EventSignUp::where('order_id', $data->out_trade_no)->update(['trade_no' => $data->trade_no]);
  195. }elseif ($data->passback_params=='member'){
  196. StoreOrder::where('order_id', $data->out_trade_no)->where('type',1)->update(['trade_no' => $data->trade_no]);
  197. }elseif ($data->passback_params=='goods'){
  198. StoreOrder::where('order_id', $data->out_trade_no)->where('type',2)->update(['trade_no' => $data->trade_no]);
  199. }
  200. HookService::listen('wechat_pay_success', $data, null, true, PaymentBehavior::class);
  201. }
  202. });
  203. }
  204. /**
  205. * 支付宝异步回调
  206. * @param callable $notifyFn 闭包函数 参数1,回调返回的参数,回调结果
  207. * @return bool
  208. */
  209. protected function AliPayNotify(callable $notifyFn)
  210. {
  211. $post = Request::instance()->post();
  212. $result = self::AliPaycheck($post);
  213. if ($result) {
  214. //商户订单号
  215. $post['out_trade_no'] = isset($post['out_trade_no']) ? $post['out_trade_no'] : '';
  216. //支付宝交易号
  217. $post['trade_no'] = isset($post['trade_no']) ? $post['trade_no'] : '';
  218. //交易状态
  219. $post['trade_status'] = isset($post['trade_status']) ? $post['trade_status'] : '';
  220. //备注
  221. $post['attach'] = isset($post['passback_params']) ? urldecode($post['passback_params']) : '';
  222. //异步回调成功执行
  223. try {
  224. if (is_callable($notifyFn)) $notifyFn((object)$post, $result);
  225. } catch (\Exception $e) {
  226. self::$isDeBug && self::WriteLog('支付宝支付成功,订单号为:' . $post['out_trade_no'] . '.回调报错:' . $e->getMessage());
  227. }
  228. echo 'success';
  229. } else {
  230. echo 'fail';
  231. }
  232. self::$isDeBug && self::WriteLog($result);
  233. return true;
  234. }
  235. /**
  236. * 支付宝同步回调
  237. * @return array
  238. */
  239. public function AliPayReturn()
  240. {
  241. //获取返回参数
  242. $get = Request::instance()->get();
  243. //验签成功与否
  244. $result = self::AliPaycheck($get);
  245. //记录日志
  246. self::$isDeBug && self::WriteLog(compact('result', 'get'));
  247. return compact('result', 'get');
  248. }
  249. /**
  250. * 验签方法
  251. * @param $arr 验签支付宝返回的信息,使用支付宝公钥。
  252. * @return boolean
  253. */
  254. protected static function AliPaycheck($post)
  255. {
  256. $aop = new \AopClient();
  257. $aop->alipayrsaPublicKey = self::$alipayPublicKey;
  258. return $aop->rsaCheckV1($post, self::$alipayPrivateKey, self::$signType);
  259. }
  260. /**
  261. * 初始化参数
  262. * @param $request
  263. * @param bool $ispage
  264. * @return mixed|\SimpleXMLElement|string|\提交表单HTML文本
  265. * @throws \Exception
  266. */
  267. protected static function AopclientRequestExecute($request, $ispage = false)
  268. {
  269. $aop = new \AopClient ();
  270. //网管地址
  271. $aop->gatewayUrl = self::$gatewayUrl;
  272. //appid
  273. $aop->appId = self::$alipayAppId;
  274. //私钥
  275. $aop->rsaPrivateKey = self::$alipayPrivateKey;
  276. //公钥
  277. $aop->alipayrsaPublicKey = self::$alipayPublicKey;
  278. //版本
  279. $aop->apiVersion = "1.0";
  280. //编码格式
  281. $aop->postCharset = self::$charset;
  282. //内容格式
  283. $aop->format = 'json';
  284. //加密方式
  285. $aop->signType = self::$signType;
  286. // 开启页面信息输出
  287. $aop->debugInfo = true;
  288. if ($ispage) {
  289. $result = $aop->pageExecute($request, "post");
  290. echo $result;
  291. } else
  292. $result = $aop->Execute($request);
  293. //打开后,将报文写入log文件
  294. self::$isDeBug && self::WriteLog($result);
  295. return $result;
  296. }
  297. /**
  298. * alipay.trade.wap.pay 下单支付手机网站支付版本
  299. * @param $out_trade_no 下单号
  300. * @param $total_amount 订单金额 单位元
  301. * @param $subject 订单标题
  302. * @param $passback_params 订单备注 会原样返回通常用于回调监听函数
  303. * @param $product_code 销售产品码,商家和支付宝签约的产品码
  304. * @param $ispage 是否直接输出
  305. * @return $response 支付宝返回的信息
  306. */
  307. public function AliPayWap($out_trade_no, $total_amount, $subject, $passback_params, $product_code = 'QUICK_MSECURITY_PAY', $ispage = true)
  308. {
  309. $request = new \AlipayTradeWapPayRequest();
  310. $request->setNotifyUrl(self::$notifyUrl);
  311. $request->setReturnUrl(self::$returnUrl);
  312. $request->setBizContent(self::setBizContent(compact('out_trade_no', 'total_amount', 'subject', 'passback_params', 'product_code')));
  313. return self::AopclientRequestExecute($request, $ispage);
  314. }
  315. /**
  316. * alipay.trade.query (统一收单线下交易查询)
  317. * @param $out_trade_no 下单号
  318. * @param $trade_no 支付宝订单号
  319. * @param $passback_params 订单备注 会原样返回通常用于回调监听函数
  320. * @return $response 支付宝返回的信息
  321. */
  322. public function AliPayQuery($out_trade_no, $trade_no, $passback_params)
  323. {
  324. $request = new \AlipayTradeQueryRequest();
  325. $request->setBizContent(self::setBizContent(compact('out_trade_no', 'passback_params', 'trade_no')));
  326. return self::AopclientRequestExecute($request);
  327. }
  328. /**
  329. * alipay.trade.refund (统一收单交易退款接口)
  330. * @param $out_trade_no 下单订单号
  331. * @param $trade_no 支付宝订单号
  332. * @param $refund_amount 退款金额
  333. * @param $refund_reason 退款说明
  334. * @param $passback_params 备注
  335. * @return $response 支付宝返回的信息
  336. */
  337. public function AliPayRefund($out_trade_no, $trade_no, $refund_amount, $refund_reason, $passback_params)
  338. {
  339. $request = new \AlipayTradeRefundRequest();
  340. $request->setBizContent(self::setBizContent(compact('out_trade_no', 'trade_no', 'refund_amount', 'refund_reason', 'passback_params', 'product_code')));
  341. $result=self::AopclientRequestExecute($request);
  342. $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
  343. $resultCode = $result->$responseNode->code;
  344. return $resultCode;
  345. }
  346. /**
  347. * alipay.trade.close (统一收单交易关闭接口)
  348. * @param $out_trade_no 订单号
  349. * @param $trade_no 支付宝订单号
  350. * @return $response 支付宝返回的信息
  351. */
  352. public function AliPayClose($out_trade_no, $trade_no)
  353. {
  354. $request = new \AlipayTradeCloseRequest();
  355. $request->setBizContent(self::setBizContent(compact('out_trade_no', 'trade_no')));
  356. return self::AopclientRequestExecute($request);
  357. }
  358. /**
  359. * 写入日志
  360. * @param $content string | array | object
  361. * @return boolen
  362. * */
  363. public static function WriteLog($content)
  364. {
  365. try {
  366. Log::init([
  367. 'type' => 'File',
  368. 'path' => LOG_PATH . 'alipay/'
  369. ]);
  370. if (is_array($content)) $content = 'response: ' . var_export($content, true);
  371. if (is_object($content)) $content = 'response: ' . var_export($content, true);
  372. Log::write(date('Y-m-d H:i:s', time()) . ' ' . $content);
  373. } catch (\Exception $e) {
  374. }
  375. }
  376. }