Pay.php 19 KB

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