PayController.php 13 KB

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