PayController.php 16 KB

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