Pay.php 19 KB

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