Pay.php 19 KB

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