PayController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. $this->logAccount($tp, $u->id, $u->name,
  85. AccountLog::OP_CHARGE, $cType, $master_amount,
  86. AccountLog::DIRECTION_INC, $cType == AccountLog::TYPE_BALANCE ? $u->balance : $u->credit, AccountLog::CHANNEL_ALIPAY);
  87. \Log::info('支付完成');
  88. } else {
  89. DB::rollBack();
  90. \Log::error('保存数据失败');
  91. }
  92. DB::commit();
  93. return 'success';
  94. }else{
  95. \Log::error('支付失败');
  96. return 'fail';
  97. }
  98. } catch (\Exception $e) {
  99. \Log::error('支付异常' . $e->getMessage());
  100. return 'fail';
  101. }
  102. }
  103. public function wechatpayNotify() {
  104. \Log::debug('wechatpay callback');
  105. // \Log::debug(Request::all());
  106. $config = Config::get('laravel-omnipay.gateways.wechatpay');
  107. $gateway = Omnipay::create("WechatPay");
  108. // $gateway->setEnvironment('sandbox');
  109. $gateway->setAppId($config['options']['appid']);
  110. $gateway->setMchId($config['options']['merchant_id']);
  111. $gateway->setApiKey($config['options']['apikey']);
  112. $response = $gateway->completePurchase([
  113. 'request_params' => file_get_contents('php://input')
  114. ])->send();
  115. try {
  116. if ($response->isPaid()) {
  117. //pay success
  118. $rawInfo = $response->getRequestData();
  119. \Log::debug($rawInfo);
  120. \Log::info('支付成功');
  121. $out_trade_no = $rawInfo['out_trade_no'];
  122. $order = OrderInfoModel::where('transaction_id', '=', $out_trade_no)->first();
  123. if (!$order) {
  124. \Log::error('找不到订单' . $out_trade_no);
  125. return 'fail';
  126. }
  127. $u = UserInfoModel::find($order->user_id);
  128. if (!$u) {
  129. \Log::error('用户不存在' . $order->user_id . ', ' . $order->user_id);
  130. return 'success';
  131. }
  132. DB::beginTransaction();
  133. $cType = AccountLog::TYPE_COIN;
  134. $u->coin += $order->number;
  135. if ($u->save()) {
  136. //更新订单状态
  137. $order->status = OrderInfoModel::STATUS_FINISHED;
  138. $order->save();
  139. //记日志
  140. // $this->logAccount($tp, $u->id, $u->name,
  141. // AccountLog::OP_CHARGE, $cType, $master_amount,
  142. // AccountLog::DIRECTION_INC, $cType == AccountLog::TYPE_BALANCE ? $u->balance : $u->credit, AccountLog::CHANNEL_WECHATPAY);
  143. \Log::info('支付完成');
  144. } else {
  145. DB::rollBack();
  146. \Log::error('保存数据失败');
  147. }
  148. DB::commit();
  149. return 'success';
  150. }else{
  151. //pay fail
  152. \Log::error($response->getData());
  153. return 'fail';
  154. }
  155. } catch (\Exception $e) {
  156. \Log::error('支付异常' . $e->getMessage());
  157. return 'fail';
  158. }
  159. }
  160. /**
  161. * @api {post} /api/pay/charge 充值
  162. * @apiDescription 充值(向平台充值)
  163. * @apiGroup Merchant
  164. * @apiPermission Passport
  165. * @apiVersion 0.1.0
  166. * @apiParam {int} [goods=1] 充值商品(1:梦想币)
  167. * @apiParam {int} number 充值数量,人民币,以分表示
  168. * @apiParam {int} type 支付类型(1:支付宝,2:微信支付)
  169. * @apiSuccessExample {json} Success-Response:
  170. * HTTP/1.1 200 OK
  171. * {
  172. * "state": true,
  173. * "code": 0,
  174. * "message": "",
  175. * "data": {
  176. * "id": 2,
  177. * "code": "ALIPAY_201610231314145719",
  178. * "transaction_id": "201610231314145719",
  179. * "user_type": 2,
  180. * "user_id": 1,
  181. * "goods_type": 1,
  182. * "price": 1,
  183. * "number": 1,
  184. * "amount": 1,
  185. * "pay_type": 1,
  186. * "status": 0,
  187. * "created_at": "2016-10-23 13:14:14",
  188. * "updated_at": "2016-10-23 13:14:14",
  189. * "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"
  190. * }
  191. * }
  192. * @apiErrorExample {json} Error-Response:
  193. * HTTP/1.1 400 Bad Request
  194. * {
  195. * "state": false,
  196. * "code": 1000,
  197. * "message": "传入参数不正确",
  198. * "data": null or []
  199. * }
  200. * 可能出现的错误代码:
  201. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  202. */
  203. public function charge(Request $request)
  204. {
  205. $goodsTypes = OrderInfoModel::getAllGoodsTypes();
  206. $gTypes = array_keys($goodsTypes);
  207. $payTypes = OrderInfoModel::getAllPayTypes();
  208. $pTypes = array_keys($payTypes);
  209. $validator = Validator::make($data = $request->all(),
  210. [
  211. 'number' => 'required|integer|min:1',
  212. 'type' => 'required|in:' . join(',', $pTypes),
  213. 'goods' => 'in:' . join(',', $gTypes),
  214. ],
  215. [
  216. 'number.required' => '请输入梦想币数量',
  217. 'number.integer' => '梦想币数量必须为整数',
  218. 'number.min' => '充值梦想币数量至少为1',
  219. 'type.required' => '支付类型必填',
  220. 'type.in' => '支付类型非法',
  221. 'goods.in' => '充值商品非法',
  222. ]
  223. );
  224. if ($validator->fails()) {
  225. return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
  226. }
  227. $user = Auth::user();
  228. $data['goods_id'] = 1;
  229. if (!isset($data['goods'])) {//默认充余额
  230. $data['goods'] = OrderInfoModel::GOODS_TYPE_COIN;
  231. }
  232. $data['user_id'] = $user->id;
  233. if ($data['type'] == OrderInfoModel::PAY_TYPE_ALIPAY) {
  234. $result = $this->createAlipayCharge($data);
  235. } else {
  236. $result = $this->createWechatpayCharge($data);
  237. }
  238. if ($result === false) {
  239. return $this->error(ErrorCode::ORDER_GENERATE_FAILED);
  240. }
  241. //log
  242. // $data['amount'] = $data['number'];
  243. // $this->chargeLog('Merchant', $merchant->id, $merchant->name,
  244. // 'balance', $data['amount'], 'balance', $data['amount'],
  245. // 'Merchant', $user->id, $merchant->name);
  246. return $this->api($result);
  247. }
  248. }