PayController.php 13 KB

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