PayController.php 13 KB

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