Pay.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 addons\unishop\model\UserExtend;
  14. use EasyWeChat\Factory;
  15. use think\Db;
  16. use think\Exception;
  17. use think\Hook;
  18. use think\Log;
  19. /**
  20. * 支付
  21. */
  22. class Pay extends Base
  23. {
  24. protected $noNeedLogin = ['getPayType', 'notify', 'authRedirect', 'alipay', 'alinotify', 'weixinOauth2'];
  25. /**
  26. * @ApiTitle (获取支付类型)
  27. * @ApiSummary (获取支付类型)
  28. * @ApiMethod (POST)
  29. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  30. * @ApiHeaders (name=platform, type=string, required=true, description="客户端平台")
  31. * @ApiReturn ({"code":1,"msg":"","data":{}})
  32. *
  33. * @ApiReturnParams (name="alipay", type="bool", description="是否支持 支付宝支付")
  34. * @ApiReturnParams (name="wxpay", type="bool", description="是否支持 微信支付")
  35. * @ApiReturnParams (name="offline", type="bool", description="是否支持 货到付款")
  36. * @ApiReturnParams (name="score", type="bool", description="是否支持 积分兑换")
  37. */
  38. public function getPayType()
  39. {
  40. $platfrom = $this->request->header('platform');
  41. $type = [];
  42. $offline = Config::getByName('offline_pay')['value'] == 1 ? true : false;
  43. switch ($platfrom) {
  44. case 'APP-PLUS';
  45. $type = ['alipay' => true, 'wxpay' => true, 'offline' => $offline];
  46. break;
  47. case 'H5':
  48. $type = ['alipay' => true, 'wxpay' => true, 'offline' => $offline];
  49. // 如果是微信内访问 公众号等
  50. if (Wechat::h5InWechat()) {
  51. $type['alipay'] = false;
  52. }
  53. break;
  54. case 'MP-WEIXIN':
  55. $type = ['alipay' => false, 'wxpay' => true, 'offline' => $offline];
  56. break;
  57. case 'MP-ALIPAY':
  58. $type = ['alipay' => true, 'wxpay' => false, 'offline' => $offline];
  59. break;
  60. case 'MP-BAIDU':
  61. $type = ['alipay' => false, 'wxpay' => false, 'offline' => $offline];
  62. break;
  63. case 'MP-TOUTIAO':
  64. $type = ['alipay' => false, 'wxpay' => false, 'offline' => $offline];
  65. break;
  66. }
  67. $this->success('', $type);
  68. }
  69. /**
  70. * @ApiTitle (微信统一下单接口)
  71. * @ApiSummary (微信统一下单接口)
  72. * @ApiMethod (GET)
  73. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  74. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  75. * @ApiHeaders (name=platform, type=string, required=true, description="客户端平台")
  76. * @ApiParams (name="order_id", type="string",required=true, description="订单id")
  77. * @ApiReturn ({"code":1,"msg":"","data":{}})
  78. *
  79. * @ApiReturnParams (name="return_code", type="string", description="状态码")
  80. * @ApiReturnParams (name="result_code", type="string", description="状态码")
  81. * @ApiReturnParams (name="return_msg", type="string", description="状态信息")
  82. * @ApiReturnParams (name="appid", type="string", description="小程序app_id")
  83. * @ApiReturnParams (name="mch_id", type="string", description="商户号")
  84. * @ApiReturnParams (name="nonce_str", type="string", description="支付签名随机串")
  85. * @ApiReturnParams (name="sign", type="string", description="签名")
  86. * @ApiReturnParams (name="trade_type", type="string", description="支付类型")
  87. * @ApiReturnParams (name="timeStamp", type="string", description="时间戳")
  88. * @ApiReturnParams (name="paySign", type="string", description="支付签名")
  89. * @ApiReturnParams (name="prepay_id", type="string", description="统一支付接口返回的prepay_id参数值,提交格式如:package: 'prepay_id=' + data.prepay_id")
  90. *
  91. */
  92. public function unify(){
  93. $this->error('微信支付暂时关闭');
  94. Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
  95. $orderId = $this->request->request('order_id', 0);
  96. $orderId = Hashids::decodeHex($orderId);
  97. $orderModel = new \addons\unishop\model\Order();
  98. $order = $orderModel->where(['id' => $orderId])->find();
  99. Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_WXPAY]);
  100. $this->success('支付成功', []);
  101. }
  102. public function unify_old()
  103. {
  104. $orderId = $this->request->request('order_id', 0);
  105. $orderId = Hashids::decodeHex($orderId);
  106. $orderModel = new \addons\unishop\model\Order();
  107. $order = $orderModel->where(['id' => $orderId])->find();
  108. try {
  109. if (!$order) {
  110. $this->error(__('Order does not exist'));
  111. }
  112. //MWEB
  113. $platfrom = $this->request->header('platform', 'MP-WEIXIN');
  114. $platfrom = 'H5';
  115. switch ($platfrom) {
  116. case 'MP-WEIXIN':
  117. $trade_type = 'JSAPI';
  118. break;
  119. case 'H5':
  120. $trade_type = 'MWEB';
  121. break;
  122. case 'APP-PLUS':
  123. $trade_type = 'APP';
  124. break;
  125. }
  126. // 如果是微信内访问 公众号等
  127. if (Wechat::h5InWechat()) {
  128. $trade_type = 'JSAPI';
  129. }
  130. $trade_type = 'MWEB';
  131. $products = $order->products()->select();
  132. $body = Config::getByName('name')['value'];
  133. foreach ($products as $product) {
  134. $body .= '_' . $product['title'];
  135. break;
  136. }
  137. // $openid = Wechat::getOpenidByUserId($this->auth->id);
  138. $openid = '';
  139. $appid = Config::getByName('app_id')['value'];
  140. // 如果 JSAPI 必须传openid、
  141. if ($trade_type == 'JSAPI' && empty($openid)) {
  142. $this->success('', array(
  143. 'weixinOauth2' =>
  144. "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".urlencode("https://$_SERVER[HTTP_HOST]/addons/unishop/pay/weixinOauth2")."&response_type=code&scope=snsapi_base&state=".$this->request->request('order_id', 0)."#wechat_redirect"
  145. ,'trade_type' => 'JSAPI'));
  146. }
  147. $app = Wechat::initEasyWechat('payment');
  148. $result = $app->order->unify([
  149. 'body' => $body,
  150. 'out_trade_no' => $order['out_trade_no'],
  151. 'total_fee' => bcmul($order['total_price'],100),
  152. 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
  153. 'trade_type' => $trade_type, // 请对应换成你的支付方式对应的值类型
  154. 'openid' => $openid
  155. ]);
  156. if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
  157. if ($trade_type == 'JSAPI') {
  158. // 二次签名
  159. $result['timeStamp'] = (string)time();
  160. $result['paySign'] = Wechat::paySign([
  161. 'appId' => $appid,
  162. 'nonceStr' => $result['nonce_str'],
  163. 'package' => 'prepay_id='.$result['prepay_id'],
  164. 'timeStamp' => $result['timeStamp'],
  165. 'signType' => 'MD5'
  166. ], Config::getByName('key')['value']);
  167. } elseif ($trade_type == 'MWEB') {
  168. $page = '/pages/order/order?state=0';
  169. if ($platfrom == 'APP-PLUS') {
  170. $page = '/pages/index/index';
  171. }
  172. $result['mweb_url'] .= '&redirect_url='. urlencode('https://'.$_SERVER['HTTP_HOST'].'/h5/#'.$page);
  173. $result['referer'] = 'https://'.$_SERVER['HTTP_HOST'];
  174. } elseif ($trade_type == 'APP') {
  175. $result['orderInfo']['appid'] = $result['appid'];
  176. $result['orderInfo']['noncestr'] = $result['nonce_str'];
  177. $result['orderInfo']['package'] = "Sign=WXPay";
  178. $result['orderInfo']['partnerid'] = $result['mch_id'];
  179. $result['orderInfo']['prepayid'] = $result['prepay_id'];
  180. $result['orderInfo']['timestamp'] = (string)time();
  181. $result['orderInfo']['sign'] = Wechat::paySign(
  182. $result['orderInfo'],
  183. Config::getByName('key')['value']
  184. );
  185. }
  186. } else {
  187. $this->error($result['return_msg']);
  188. }
  189. } catch (Exception $e) {
  190. $this->error($e->getMessage());
  191. }
  192. $this->success('', $result);
  193. }
  194. /**
  195. * 微信订单支付通知回调
  196. * @ApiInternal
  197. */
  198. public function notify()
  199. {
  200. // 添加行为
  201. Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
  202. Hook::add('paid_fail', 'addons\\unishop\\behavior\\Order');
  203. $app = Wechat::initEasyWechat('payment');
  204. $response = $app->handlePaidNotify(function($message, $fail) use ($app){
  205. try {
  206. // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
  207. $orderModel = new \addons\unishop\model\Order(); //($message['out_trade_no']);
  208. $order = $orderModel->where(['out_trade_no' => $message['out_trade_no']])->find();
  209. if (!$order || $order->have_paid != \addons\unishop\model\Order::PAID_NO) {
  210. return true; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
  211. }
  212. // 这里调用微信的【订单查询】接口查一下该笔订单的情况,确认是已经支付
  213. $result = $app->order->queryByOutTradeNumber($message['out_trade_no']);
  214. if ($result['return_code'] == 'FAIL' || empty($result['result_code']) || $result['result_code'] == 'FAIL') {
  215. return $fail('订单未支付');
  216. }
  217. // 检查是否成功
  218. if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
  219. // 用户是否支付成功
  220. if ($message['result_code'] === 'SUCCESS') {
  221. Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_WXPAY]);
  222. } elseif ($message['result_code'] === 'FAIL') {
  223. // 用户支付失败
  224. Hook::listen('paid_fail', $order);
  225. }
  226. } else {
  227. return $fail('通信失败,请稍后再通知我');
  228. }
  229. return true;
  230. } catch (\Exception $e) {
  231. // 记录日志
  232. Log::record('支付回调错误:'. $e->getMessage());
  233. return $fail('通信失败,请稍后再通知我');
  234. }
  235. });
  236. $response->send();
  237. }
  238. /**
  239. * @ApiTitle (货到付款)
  240. * @ApiSummary (线下支付-货到付款)
  241. * @ApiMethod (GET)
  242. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  243. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  244. * @ApiParams (name="order_id", type="string",required=true, description="订单id")
  245. * @ApiReturn ({"code":1,"msg":"","data":true})
  246. *
  247. */
  248. public function offline()
  249. {
  250. $orderId = $this->request->get('order_id', 0);
  251. $orderId = Hashids::decodeHex($orderId);
  252. $orderModel = new \addons\unishop\model\Order();
  253. $order = $orderModel->where(['id' => $orderId])->find();
  254. if (!$order) {
  255. $this->error(__('Order does not exist'));
  256. }
  257. try {
  258. Db::startTrans();
  259. Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
  260. Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_OFFLINE]);
  261. Db::commit();
  262. } catch (Exception $e) {
  263. Db::rollback();
  264. $this->error($e->getMessage());
  265. }
  266. $this->success('', true);
  267. }
  268. /**
  269. * @ApiTitle (获取JSAPI配置)
  270. * @ApiSummary (微信内H5-JSAPI支付)
  271. * @ApiMethod (GET)
  272. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  273. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  274. * @ApiReturn ({"code":1,"msg":"","data":{}})
  275. *
  276. * @ApiReturnParams (name="debug", type="bool", description="调试模式")
  277. * @ApiReturnParams (name="jsApiList", type="array", description="授权功能列表")
  278. * @ApiReturnParams (name="appId", type="string", description="小程序app_id")
  279. * @ApiReturnParams (name="nonceStr", type="string", description="随机数")
  280. * @ApiReturnParams (name="timestamp", type="string", description="时间戳")
  281. * @ApiReturnParams (name="signature", type="string", description="签名")
  282. *
  283. */
  284. public function jssdkBuildConfig()
  285. {
  286. $app = Wechat::initEasyWechat('payment');
  287. $configData = $app->jssdk->buildConfig(['chooseWXPay'], false, true, false);
  288. $this->success('', $configData);
  289. }
  290. /**
  291. * @ApiTitle (支付宝支付)
  292. * @ApiSummary (支付宝支付)
  293. * @ApiMethod (GET)
  294. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  295. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  296. * @ApiParams (name="order_id", type="string",required=true, description="订单id")
  297. * @ApiReturn (重定向到支付宝支付网页)
  298. *
  299. */
  300. public function alipay_simple(){
  301. Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
  302. $orderId = $this->request->request('order_id', 0);
  303. $orderId = Hashids::decodeHex($orderId);
  304. $orderModel = new \addons\unishop\model\Order();
  305. $order = $orderModel->where(['id' => $orderId])->find();
  306. Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_ALIPAY]);
  307. $this->success('支付成功', []);
  308. }
  309. public function alipay_old()
  310. {
  311. $orderId = $this->request->request('order_id', 0);
  312. $orderId = Hashids::decodeHex($orderId);
  313. $orderModel = new \addons\unishop\model\Order();
  314. $order = $orderModel->where(['id' => $orderId])->find();
  315. try {
  316. if (!$order) {
  317. $this->error(__('Order does not exist'));
  318. }
  319. $products = $order->products()->select();
  320. $body = Config::getByName('name')['value'];
  321. foreach ($products as $product) {
  322. $body .= '_' . $product['title'];
  323. break;
  324. }
  325. $platfrom = $this->request->header('platform', 'H5');
  326. $alipay = Ali::initAliPay();
  327. $order = [
  328. 'out_trade_no' => $order->out_trade_no,
  329. 'total_amount' => $order->total_price,
  330. 'subject' => $body,
  331. 'http_method' => 'GET' // 如果想在 wap 支付时使用 GET 方式提交,请加上此参数。默认使用 POST 方式提交
  332. ];
  333. switch ($platfrom) {
  334. case 'H5':
  335. // 直接返回
  336. $alipay->wap($order)->send();
  337. break;
  338. case 'APP-PLUS':
  339. //$pay->app($order)->send();
  340. $this->success('', $alipay->app($order)->getContent());
  341. break;
  342. case 'MP-ALIPAY':
  343. break;
  344. default:
  345. $this->error('此平台不支持支付宝支付');
  346. }
  347. } catch (Exception $e) {
  348. $this->error($e->getMessage());
  349. }
  350. }
  351. /**
  352. * 支付宝回调地址
  353. * @ApiInternal
  354. */
  355. public function alinotify()
  356. {
  357. $alipay = Ali::initAliPay();
  358. try{
  359. $data = $alipay->verify(); // 是的,验签就这么简单!
  360. // 请自行对 trade_status 进行判断及其它逻辑进行判断,在支付宝的业务通知中,只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时,支付宝才会认定为买家付款成功。
  361. // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号;
  362. // 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额);
  363. // 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email);
  364. // 4、验证app_id是否为该商户本身。
  365. // 5、其它业务逻辑情况
  366. if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
  367. // 支付成功
  368. //Log::record('Alipay notify ,支付成功');
  369. // 条件一
  370. $orderModel = new \addons\unishop\model\Order(); //($message['out_trade_no']);
  371. $order = $orderModel->where(['out_trade_no' => $data['out_trade_no']])->find();
  372. if (!$order || $order->have_paid != \addons\unishop\model\Order::PAID_NO) {
  373. throw new Exception('订单不存在或已完成');
  374. }
  375. // 条件二
  376. if ($order->total_price > $data['total_amount'] || $order->total_price < $data['total_amount']) {
  377. throw new Exception('金额不一');
  378. }
  379. // 条件三
  380. if ($data['app_id'] != Config::getByName('ali_app_id')['value']) {
  381. throw new Exception('app_id不一');
  382. }
  383. // 添加行为
  384. Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
  385. Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_ALIPAY]);
  386. }
  387. } catch (\Exception $e) {
  388. Log::record('Alipay notify ,支付失败: '. $e->getMessage());
  389. return $alipay->success()->send();
  390. }
  391. return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`
  392. }
  393. /**
  394. * 微信网页授权
  395. * @ApiInternal
  396. */
  397. public function weixinOauth2()
  398. {
  399. $config = [
  400. 'app_id' => Config::getByName('app_id')['value'],
  401. 'secret' => Config::getByName('secret')['value'],
  402. // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
  403. 'response_type' => 'array',
  404. //...
  405. ];
  406. $app = Factory::officialAccount($config);
  407. $oauth = $app->oauth;
  408. $user = $oauth->user();
  409. $order_id = $this->request->request('state', 0);
  410. $orderId = Hashids::decodeHex($order_id);
  411. $orderModel = new \addons\unishop\model\Order();
  412. $order = $orderModel->where(['id' => $orderId])->find();
  413. if ($order) {
  414. $userExtend = (new UserExtend())->where(['user_id' => $order->user_id])->find();
  415. if (!$userExtend) {
  416. // 把openid写进去
  417. (new UserExtend())->save(['user_id' => $order->user_id, 'openid' => $user->getId()]);
  418. }
  419. //$_SERVER['HTTP_HOST'] = 'localhost:8080';
  420. $url = 'https://'.$_SERVER['HTTP_HOST'].'/h5/#/pages/money/pay?order_id='.$order_id.'&total='.$order->total_price.'&pay=1';
  421. header("Location: $url");
  422. }
  423. exit;
  424. }
  425. }