PayController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php
  2. namespace App\Http\Controllers\Api\V1;
  3. use App\Helper\PayHelper;
  4. use App\User;
  5. use App\Models\OrderInfoModel;
  6. use App\Models\AccountLog;
  7. use App\Services\Base\ErrorCode;
  8. use Request, Config, DB;
  9. class PayController extends Controller
  10. {
  11. use PayHelper, LogHelper,JpushHelper;
  12. /**
  13. * p++ webhooks通知
  14. */
  15. // public function pppNotify() {
  16. // $sig = Request::header('x-pingplusplus-signature');
  17. // $request = Request::instance();
  18. // $data = $request->getContent();
  19. //
  20. // if (!$this->checkPppSignature($data, $sig)) {//验签失败
  21. // header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
  22. // exit("fail");
  23. // }
  24. //
  25. // $event = json_decode($data);
  26. // if (!isset($event->type)) {
  27. //// return Response::make('fail', 400);
  28. // header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
  29. // exit("fail");
  30. // }
  31. // switch ($event->type) {
  32. // case "charge.succeeded":
  33. // // 开发者在此处加入对支付异步通知的处理代码
  34. // header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
  35. // break;
  36. // case "refund.succeeded":
  37. // // 开发者在此处加入对退款异步通知的处理代码
  38. // header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
  39. // break;
  40. // default:
  41. // header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
  42. // break;
  43. // }
  44. // }
  45. public function alipayNotify() {
  46. $rawInfo = Request::all();
  47. \Log::info('aliplay callback');
  48. \Log::info($rawInfo);
  49. $config = Config::get('laravel-omnipay.gateways.alipay');
  50. $gateway = Omnipay::create($config['driver']);
  51. $gateway->setEnvironment($config['options']['environment']);
  52. $gateway->setAppId($config['options']['appid']);
  53. $gateway->setEncryptKey($config['options']['encrypt_key']);
  54. $gateway->setPrivateKey($config['options']['prikey']);
  55. $gateway->setAlipayPublicKey($config['options']['ali_pubkey']);
  56. $gateway->setNotifyUrl($config['options']['notify_url']);
  57. $request = $gateway->completePurchase();
  58. $request->setParams($rawInfo);//Optional
  59. try {
  60. $response = $request->send();
  61. if($response->isPaid()){
  62. \Log::info('支付成功');
  63. $out_trade_no = $rawInfo['out_trade_no'];
  64. $order = Order::where('transaction_id', '=', $out_trade_no)->first();
  65. if (!$order) {
  66. \Log::error('找不到订单' . $out_trade_no);
  67. return 'fail';
  68. }
  69. $master_amount = $order->number;
  70. $slave_amount = 0;
  71. if (!empty($order->ext_info)) {
  72. $extInfo = json_decode($order->ext_info, true);
  73. if ($extInfo !== null) {
  74. $cc = $extInfo['cc_bonus'];
  75. $master_amount = round(($cc / 100) * $order->number);
  76. $slave_amount = $order->number - $master_amount;
  77. }
  78. }
  79. $tp = '';
  80. // $u = null;
  81. if ($order->user_type == Order::USER_TYPE_MERCHANT) {
  82. $tp = 'Merchant';
  83. // $u = Merchant::find($order->user_id);
  84. } elseif ($order->user_type == Order::USER_TYPE_MEMBER) {
  85. $tp = 'Member';
  86. //Not handled here
  87. }
  88. $u = User::find($order->user_id);
  89. if (!$u) {
  90. \Log::error('用户不存在' . $order->user_type . ', ' . $order->user_id);
  91. return 'success';
  92. }
  93. DB::beginTransaction();
  94. if ($order->goods_type == Order::GOODS_TYPE_BALANCE||$order->goods_type == Order::GOODS_TYPE_COSUME) {
  95. $cType = AccountLog::TYPE_BALANCE;
  96. // $u->account_balance += $order->number;
  97. $u->balance += $master_amount;
  98. } elseif ($order->goods_type == Order::GOODS_TYPE_CREDIT) {
  99. $cType = AccountLog::TYPE_CREDIT;
  100. // $u->credit_balance += $order->number;
  101. $u->credit += $master_amount;
  102. } else {
  103. \Log::error('商品不存在' . $order->goods_type);
  104. return 'success';
  105. }
  106. \Log::info('支付金额 '.$master_amount);
  107. if ($u->save()) {
  108. //更新订单状态
  109. $order->status = Order::STATUS_FINISHED;
  110. $order->save();
  111. //记日志
  112. $amount = $rawInfo['total_amount'] * 100;
  113. if (empty($extInfo)) {
  114. $this->logAccount($tp, $u->id, $u->name,
  115. AccountLog::OP_CHARGE, $cType, $master_amount,
  116. AccountLog::DIRECTION_INC, $cType == AccountLog::TYPE_BALANCE ? $u->balance : $u->credit, AccountLog::CHANNEL_ALIPAY);
  117. } else {
  118. //续消费
  119. $this->continue_consume($order);
  120. $this->logAccount($tp, $u->id, $u->name,
  121. AccountLog::OP_CC, $cType, $master_amount,
  122. AccountLog::DIRECTION_INC, $cType == AccountLog::TYPE_BALANCE ? $u->balance : $u->credit, AccountLog::CHANNEL_ALIPAY);
  123. }
  124. \Log::info('支付完成');
  125. } else {
  126. DB::rollBack();
  127. \Log::error('保存数据失败');
  128. }
  129. DB::commit();
  130. return 'success';
  131. }else{
  132. \Log::error('支付失败');
  133. return 'fail';
  134. }
  135. } catch (\Exception $e) {
  136. \Log::error('支付异常' . $e->getMessage());
  137. return 'fail';
  138. }
  139. }
  140. public function wechatpayNotify() {
  141. \Log::debug('wechatpay callback');
  142. // \Log::debug(Request::all());
  143. $config = Config::get('laravel-omnipay.gateways.wechatpay');
  144. $gateway = Omnipay::create("WechatPay");
  145. // $gateway->setEnvironment('sandbox');
  146. $gateway->setAppId($config['options']['appid']);
  147. $gateway->setMchId($config['options']['merchant_id']);
  148. $gateway->setApiKey($config['options']['apikey']);
  149. $response = $gateway->completePurchase([
  150. 'request_params' => file_get_contents('php://input')
  151. ])->send();
  152. try {
  153. if ($response->isPaid()) {
  154. //pay success
  155. $rawInfo = $response->getRequestData();
  156. \Log::debug($rawInfo);
  157. \Log::info('支付成功');
  158. $out_trade_no = $rawInfo['out_trade_no'];
  159. $order = Order::where('transaction_id', '=', $out_trade_no)->first();
  160. if (!$order) {
  161. \Log::error('找不到订单' . $out_trade_no);
  162. return 'fail';
  163. }
  164. $master_amount = $order->number;
  165. $slave_amount = 0;
  166. if (!empty($order->ext_info)) {
  167. $extInfo = json_decode($order->ext_info, true);
  168. if ($extInfo !== null) {
  169. $cc = $extInfo['cc_bonus'];
  170. $master_amount = round(($cc / 100) * $order->number);
  171. $slave_amount = $order->number - $master_amount;
  172. }
  173. }
  174. $tp = '';
  175. // $u = null;
  176. if ($order->user_type == Order::USER_TYPE_MERCHANT) {
  177. $tp = 'Merchant';
  178. // $u = Merchant::find($order->user_id);
  179. } elseif ($order->user_type == Order::USER_TYPE_MEMBER) {
  180. $tp = 'Member';
  181. //Not handled here
  182. }
  183. $u = User::find($order->user_id);
  184. if (!$u) {
  185. \Log::error('用户不存在' . $order->user_type . ', ' . $order->user_id);
  186. return 'success';
  187. }
  188. DB::beginTransaction();
  189. if ($order->goods_type == Order::GOODS_TYPE_BALANCE||$order->goods_type == Order::GOODS_TYPE_COSUME) {
  190. $cType = AccountLog::TYPE_BALANCE;
  191. // $u->account_balance += $order->number;
  192. $u->balance += $master_amount;
  193. } elseif ($order->goods_type == Order::GOODS_TYPE_CREDIT) {
  194. $cType = AccountLog::TYPE_CREDIT;
  195. // $u->credit_balance += $order->number;
  196. $u->credit += $master_amount;
  197. } else {
  198. \Log::error('商品不存在' . $order->goods_type);
  199. return 'success';
  200. }
  201. //测试
  202. \Log::info('支付金额 '.$master_amount);
  203. if ($u->save()) {
  204. //更新订单状态
  205. $order->status = Order::STATUS_FINISHED;
  206. $order->save();
  207. //记日志
  208. $amount = $rawInfo['total_fee'] * 100;
  209. if (empty($extInfo)) {
  210. $this->logAccount($tp, $u->id, $u->name,
  211. AccountLog::OP_CHARGE, $cType, $master_amount,
  212. AccountLog::DIRECTION_INC, $cType == AccountLog::TYPE_BALANCE ? $u->balance : $u->credit, AccountLog::CHANNEL_WECHATPAY);
  213. } else {
  214. $this->logAccount($tp, $u->id, $u->name,
  215. AccountLog::OP_CC, $cType, $master_amount,
  216. AccountLog::DIRECTION_INC, $cType == AccountLog::TYPE_BALANCE ? $u->balance : $u->credit, AccountLog::CHANNEL_WECHATPAY);
  217. }
  218. \Log::info('支付完成');
  219. } else {
  220. DB::rollBack();
  221. \Log::error('保存数据失败');
  222. }
  223. DB::commit();
  224. return 'success';
  225. }else{
  226. //pay fail
  227. \Log::error($response->getData());
  228. return 'fail';
  229. }
  230. } catch (\Exception $e) {
  231. \Log::error('支付异常' . $e->getMessage());
  232. return 'fail';
  233. }
  234. }
  235. function continue_consume($order){
  236. }
  237. /**
  238. * @api {post} /api/pay/charge 充值
  239. * @apiDescription 充值(向平台充值)
  240. * @apiGroup Merchant
  241. * @apiPermission Passport
  242. * @apiVersion 0.1.0
  243. * @apiParam {int} [goods=1] 充值商品(1:梦想币)
  244. * @apiParam {int} number 充值数量,人民币,以分表示
  245. * @apiParam {int} type 支付类型(1:支付宝,2:微信支付)
  246. * @apiSuccessExample {json} Success-Response:
  247. * HTTP/1.1 200 OK
  248. * {
  249. * "state": true,
  250. * "code": 0,
  251. * "message": "",
  252. * "data": {
  253. * "id": 2,
  254. * "code": "ALIPAY_201610231314145719",
  255. * "transaction_id": "201610231314145719",
  256. * "user_type": 2,
  257. * "user_id": 1,
  258. * "goods_type": 1,
  259. * "price": 1,
  260. * "number": 1,
  261. * "amount": 1,
  262. * "pay_type": 1,
  263. * "status": 0,
  264. * "created_at": "2016-10-23 13:14:14",
  265. * "updated_at": "2016-10-23 13:14:14",
  266. * "orderString": "alipay_sdk=lokielse%2Fomnipay-alipay&app_id=2016091201894867&biz_content=%7B%22subject%22%3A%22%5Cu7532%5Cu8c61%5Cu8054%5Cu5408-%5Cu4f59%5Cu989d%5Cu5145%5Cu503c%22%2C%22out_trade_no%22%3A%22201610231314145719%22%2C%22total_amount%22%3A0.01%2C%22product_code%22%3A1%7D&charset=UTF-8&format=JSON&method=alipay.trade.app.pay&notify_url=http%3A%2F%2Fweb%2Fapi%2Fpay%2Falipay%2Fnotify&sign_type=RSA&timestamp=2016-10-23+13%3A14%3A14&version=1.0&sign=oxKM0qGMHLWDlMrXHIiy9%2Fk2BXJq3rC3RKdmcfFwkBJVRXvtG6cBoAYPll6VxJYOMQWeu78Ibfov%2FxIVCuN9yUfzEiokfQrzBoptc94bCQ5k0pNyJcSdgezOUKHB12P5Zmm3Hd6AAbGRDV9UCaLVz0wYkFJPrCyUv1ZfhrM%2BBqc%3D"
  267. * }
  268. * }
  269. * @apiErrorExample {json} Error-Response:
  270. * HTTP/1.1 400 Bad Request
  271. * {
  272. * "state": false,
  273. * "code": 1000,
  274. * "message": "传入参数不正确",
  275. * "data": null or []
  276. * }
  277. * 可能出现的错误代码:
  278. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  279. */
  280. public function charge(Request $request)
  281. {
  282. $goodsTypes = OrderInfoModel::getAllGoodsTypes();
  283. $gTypes = array_keys($goodsTypes);
  284. $payTypes = OrderInfoModel::getAllPayTypes();
  285. $pTypes = array_keys($payTypes);
  286. $validator = Validator::make($data = $request->input(),
  287. [
  288. 'number' => 'required|integer|min:1',
  289. 'type' => 'required|in:' . join(',', $pTypes),
  290. 'goods' => 'in:' . join(',', $gTypes),
  291. ],
  292. [
  293. 'number.required' => '充值金额必填',
  294. 'number.integer' => '金额必须为整数',
  295. 'number.min' => '充值金额至少为1',
  296. 'type.required' => '支付类型必填',
  297. 'type.in' => '支付类型非法',
  298. 'goods.in' => '充值商品非法',
  299. ]
  300. );
  301. if ($validator->fails()) {
  302. return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
  303. }
  304. $user = Auth::user();
  305. $data['goods_id'] = 0;
  306. if (!isset($data['goods'])) {//默认充余额
  307. $data['goods'] = OrderInfoModel::GOODS_TYPE_COIN;
  308. }
  309. $data['user_type'] = OrderInfoModel::USER_TYPE_USER;
  310. $data['user_id'] = $user->id;
  311. if ($data['type'] == Order::PAY_TYPE_ALIPAY) {
  312. $result = $this->createAlipayCharge($data);
  313. } else {
  314. $result = $this->createWechatpayCharge($data);
  315. }
  316. if ($result === false) {
  317. return $this->error(ErrorCode::ORDER_GENERATE_FAILED);
  318. }
  319. //log
  320. // $data['amount'] = $data['number'];
  321. // $this->chargeLog('Merchant', $merchant->id, $merchant->name,
  322. // 'balance', $data['amount'], 'balance', $data['amount'],
  323. // 'Merchant', $user->id, $merchant->name);
  324. return $this->api($result);
  325. }
  326. }