Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

340 righe
12 KiB

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zhengmingwei
  5. * Date: 2020/1/7
  6. * Time: 10:01 下午
  7. */
  8. namespace addons\unishop\controller;
  9. use addons\unishop\extend\Ali;
  10. use addons\unishop\extend\Hashids;
  11. use addons\unishop\extend\Wechat;
  12. use addons\unishop\model\Config;
  13. use think\Db;
  14. use think\Exception;
  15. use think\Hook;
  16. use think\Log;
  17. class Pay extends Base
  18. {
  19. protected $noNeedLogin = ['getPayType', 'notify', 'unify','authRedirect', 'alipay', 'alinotify'];
  20. /**
  21. * 获取支付类型
  22. */
  23. public function getPayType()
  24. {
  25. $platfrom = $this->request->header('platform');
  26. $type = [];
  27. $offline = Config::getByName('offline_pay')['value'] == 1 ? true : false;
  28. switch ($platfrom) {
  29. case 'APP-PLUS';
  30. $type = ['alipay' => true, 'wxpay' => true, 'offline' => $offline];
  31. break;
  32. case 'H5':
  33. $type = ['alipay' => true, 'wxpay' => true, 'offline' => $offline];
  34. // 如果是微信内访问 公众号等
  35. if (Wechat::h5InWechat()) {
  36. $type['alipay'] = false;
  37. }
  38. break;
  39. case 'MP-WEIXIN':
  40. $type = ['alipay' => false, 'wxpay' => true, 'offline' => $offline];
  41. break;
  42. case 'MP-ALIPAY':
  43. $type = ['alipay' => true, 'wxpay' => false, 'offline' => $offline];
  44. break;
  45. case 'MP-BAIDU':
  46. $type = ['alipay' => false, 'wxpay' => false, 'offline' => $offline];
  47. break;
  48. case 'MP-TOUTIAO':
  49. $type = ['alipay' => false, 'wxpay' => false, 'offline' => $offline];
  50. break;
  51. }
  52. $this->success('', $type);
  53. }
  54. /**
  55. * 微信统一下单接口
  56. */
  57. public function unify()
  58. {
  59. $orderId = $this->request->request('order_id', 0);
  60. $orderId = Hashids::decodeHex($orderId);
  61. $orderModel = new \addons\unishop\model\Order();
  62. $order = $orderModel->where(['id' => $orderId])->find();
  63. try {
  64. if (!$order) {
  65. $this->error(__('Order does not exist'));
  66. }
  67. //MWEB
  68. $platfrom = $this->request->header('platform', 'MP-WEIXIN');
  69. switch ($platfrom) {
  70. case 'MP-WEIXIN':
  71. $trade_type = 'JSAPI';
  72. break;
  73. case 'H5':
  74. case 'APP-PLUS':
  75. $trade_type = 'MWEB';
  76. break;
  77. }
  78. // 如果是微信内访问 公众号等
  79. if (Wechat::h5InWechat()) {
  80. $trade_type = 'JSAPI';
  81. }
  82. $products = $order->products()->select();
  83. $body = Config::getByName('name')['value'];
  84. foreach ($products as $product) {
  85. $body .= '_' . $product['title'];
  86. }
  87. $app = Wechat::initEasyWechat('payment');
  88. $result = $app->order->unify([
  89. 'body' => $body,
  90. 'out_trade_no' => $order['out_trade_no'],
  91. 'total_fee' => bcmul($order['total_price'],100),
  92. 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
  93. 'trade_type' => $trade_type, // 请对应换成你的支付方式对应的值类型
  94. 'openid' => Wechat::getOpenidByUserId($this->auth->id)
  95. ]);
  96. if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
  97. if ($trade_type == 'JSAPI') {
  98. // 二次签名
  99. $result['timeStamp'] = (string)time();
  100. $result['paySign'] = Wechat::paySign([
  101. 'appId' => Config::getByName('app_id')['value'],
  102. 'nonceStr' => $result['nonce_str'],
  103. 'package' => 'prepay_id='.$result['prepay_id'],
  104. 'timeStamp' => $result['timeStamp'],
  105. 'signType' => 'MD5'
  106. ], Config::getByName('key')['value']);
  107. } elseif ($trade_type == 'MWEB') {
  108. $page = '/pages/order/order?state=0';
  109. if ($platfrom == 'APP-PLUS') {
  110. $page = '/pages/index/index';
  111. }
  112. $result['mweb_url'] .= '&redirect_url='. urlencode('https://'.$_SERVER['HTTP_HOST'].'/h5/#'.$page);
  113. $result['referer'] = 'https://'.$_SERVER['HTTP_HOST'];
  114. }
  115. $this->success('', $result);
  116. } else {
  117. $this->error($result['return_msg']);
  118. }
  119. } catch (Exception $e) {
  120. $this->error($e->getMessage());
  121. }
  122. }
  123. /**
  124. * 微信订单支付通知回调
  125. */
  126. public function notify()
  127. {
  128. // 添加行为
  129. Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
  130. Hook::add('paid_fail', 'addons\\unishop\\behavior\\Order');
  131. $app = Wechat::initEasyWechat('payment');
  132. $response = $app->handlePaidNotify(function($message, $fail) use ($app){
  133. try {
  134. // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
  135. $orderModel = new \addons\unishop\model\Order(); //($message['out_trade_no']);
  136. $order = $orderModel->where(['out_trade_no' => $message['out_trade_no']])->find();
  137. if (!$order || $order->have_paid != \addons\unishop\model\Order::PAID_NO) {
  138. return true; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
  139. }
  140. // 这里调用微信的【订单查询】接口查一下该笔订单的情况,确认是已经支付
  141. $result = $app->order->queryByOutTradeNumber($message['out_trade_no']);
  142. if ($result['return_code'] == 'FAIL' || empty($result['result_code']) || $result['result_code'] == 'FAIL') {
  143. return $fail('订单未支付');
  144. }
  145. // 检查是否成功
  146. if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
  147. // 用户是否支付成功
  148. if ($message['result_code'] === 'SUCCESS') {
  149. Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_WXPAY]);
  150. } elseif ($message['result_code'] === 'FAIL') {
  151. // 用户支付失败
  152. Hook::listen('paid_fail', $order);
  153. }
  154. } else {
  155. return $fail('通信失败,请稍后再通知我');
  156. }
  157. return true;
  158. } catch (\Exception $e) {
  159. // 记录日志
  160. Log::record('支付回调错误:'. $e->getMessage());
  161. return $fail('通信失败,请稍后再通知我');
  162. }
  163. });
  164. $response->send();
  165. }
  166. /**
  167. * 在线支付
  168. */
  169. public function offline()
  170. {
  171. $orderId = $this->request->get('order_id', 0);
  172. $orderId = Hashids::decodeHex($orderId);
  173. $orderModel = new \addons\unishop\model\Order();
  174. $order = $orderModel->where(['id' => $orderId])->find();
  175. if (!$order) {
  176. $this->error(__('Order does not exist'));
  177. }
  178. try {
  179. Db::startTrans();
  180. Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
  181. Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_OFFLINE]);
  182. Db::commit();
  183. } catch (Exception $e) {
  184. Db::rollback();
  185. $this->error($e->getMessage());
  186. }
  187. $this->success('', true);
  188. }
  189. /**
  190. * 微信内H5-JSAPI支付
  191. */
  192. public function jssdkBuildConfig()
  193. {
  194. $app = Wechat::initEasyWechat('payment');
  195. $configData = $app->jssdk->buildConfig(['chooseWXPay'], false, true, false);
  196. $this->success('', $configData);
  197. }
  198. /**
  199. * 支付宝支付
  200. */
  201. public function alipay()
  202. {
  203. $orderId = $this->request->request('order_id', 0);
  204. $orderId = Hashids::decodeHex($orderId);
  205. $orderModel = new \addons\unishop\model\Order();
  206. $order = $orderModel->where(['id' => $orderId])->find();
  207. try {
  208. if (!$order) {
  209. $this->error(__('Order does not exist'));
  210. }
  211. $products = $order->products()->select();
  212. $body = Config::getByName('name')['value'];
  213. foreach ($products as $product) {
  214. $body .= '_' . $product['title'];
  215. }
  216. $platfrom = $this->request->header('platform', 'H5');
  217. $alipay = Ali::initAliPay();
  218. $order = [
  219. 'out_trade_no' => $order->out_trade_no,
  220. 'total_amount' => $order->total_price,
  221. 'subject' => $body,
  222. 'http_method' => 'GET' // 如果想在 wap 支付时使用 GET 方式提交,请加上此参数。默认使用 POST 方式提交
  223. ];
  224. switch ($platfrom) {
  225. case 'H5':
  226. // 直接返回
  227. $alipay->wap($order)->send();
  228. break;
  229. case 'APP-PLUS':
  230. //$pay->app($order)->send();
  231. $this->success('', $alipay->app($order)->getContent());
  232. break;
  233. case 'MP-ALIPAY':
  234. break;
  235. default:
  236. $this->error('此平台不支持支付宝支付');
  237. }
  238. } catch (Exception $e) {
  239. $this->error($e->getMessage());
  240. }
  241. }
  242. /**
  243. * 支付宝回调地址
  244. */
  245. public function alinotify()
  246. {
  247. $alipay = Ali::initAliPay();
  248. try{
  249. $data = $alipay->verify(); // 是的,验签就这么简单!
  250. // 请自行对 trade_status 进行判断及其它逻辑进行判断,在支付宝的业务通知中,只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时,支付宝才会认定为买家付款成功。
  251. // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号;
  252. // 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额);
  253. // 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email);
  254. // 4、验证app_id是否为该商户本身。
  255. // 5、其它业务逻辑情况
  256. if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
  257. // 支付成功
  258. //Log::record('Alipay notify ,支付成功');
  259. // 条件一
  260. $orderModel = new \addons\unishop\model\Order(); //($message['out_trade_no']);
  261. $order = $orderModel->where(['out_trade_no' => $data['out_trade_no']])->find();
  262. if (!$order || $order->have_paid != \addons\unishop\model\Order::PAID_NO) {
  263. throw new Exception('订单不存在或已完成');
  264. }
  265. // 条件二
  266. if ($order->total_price > $data['total_amount'] || $order->total_price < $data['total_amount']) {
  267. throw new Exception('金额不一');
  268. }
  269. // 条件三
  270. if ($data['app_id'] != Config::getByName('ali_app_id')['value']) {
  271. throw new Exception('app_id不一');
  272. }
  273. // 添加行为
  274. Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
  275. Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_ALIPAY]);
  276. }
  277. } catch (\Exception $e) {
  278. Log::record('Alipay notify ,支付失败: '. $e->getMessage());
  279. return $alipay->success()->send();
  280. }
  281. return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`
  282. }
  283. }