PayController.php 15 KB

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