YzyController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Models\Coupon;
  5. use App\Http\Models\CouponLog;
  6. use App\Http\Models\Goods;
  7. use App\Http\Models\Order;
  8. use App\Http\Models\Payment;
  9. use App\Http\Models\PaymentCallback;
  10. use App\Http\Models\ReferralLog;
  11. use App\Http\Models\User;
  12. use Illuminate\Http\Request;
  13. use Response;
  14. use Redirect;
  15. use Cache;
  16. use DB;
  17. use Log;
  18. /**
  19. * 有赞云支付
  20. * Class YzyController
  21. *
  22. * @package App\Http\Controllers
  23. */
  24. class YzyController extends Controller
  25. {
  26. protected static $config;
  27. private $accessToken;
  28. function __construct()
  29. {
  30. self::$config = $this->systemConfig();
  31. $this->accessToken = $this->getAccessToken();
  32. }
  33. // 获取accessToken
  34. private function getAccessToken()
  35. {
  36. if (Cache::has('YZY_TOKEN')) {
  37. return Cache::get('YZY_TOKEN')['access_token'];
  38. }
  39. $clientId = self::$config['youzan_client_id']; // f531e5282e4689712a
  40. $clientSecret = self::$config['youzan_client_secret']; // 4020b1743633ef334fd06a32190ee677
  41. $type = 'self';
  42. $keys['kdt_id'] = self::$config['kdt_id']; // 40503761
  43. $token = (new \Youzan\Open\Token($clientId, $clientSecret))->getToken($type, $keys);
  44. Cache::put('YZY_TOKEN', $token, 10000);
  45. return $token['access_token'];
  46. }
  47. // 接收GET请求
  48. public function index(Request $request)
  49. {
  50. \Log::info("YZY-GET:" . var_export($request->all()));
  51. }
  52. // 接收POST请求
  53. public function store(Request $request)
  54. {
  55. \Log::info("YZY-POST:" . var_export($request->all()));
  56. $json = file_get_contents('php://input');
  57. $data = json_decode($json, true);
  58. if (!$data) {
  59. Log::info('YZY-POST:回调数据无法解析,可能是非法请求');
  60. exit();
  61. }
  62. // 判断消息是否合法
  63. $msg = $data['msg'];
  64. $sign_string = self::$config['youzan_client_id'] . "" . $msg . "" . self::$config['youzan_client_secret'];
  65. $sign = md5($sign_string);
  66. if ($sign != $data['sign']) {
  67. Log::info('YZY-POST:回调数据签名错误,可能是非法请求');
  68. exit();
  69. } else {
  70. // 返回请求成功标识给有赞
  71. var_dump(["code" => 0, "msg" => "success"]);
  72. }
  73. // 先写入回调日志
  74. $this->callbackLog($data['client_id'], $data['id'], $data['kdt_id'], $data['kdt_name'], $data['mode'], $data['msg'], $data['sendCount'], $data['sign'], $data['status'], $data['test'], $data['type'], $data['version']);
  75. // msg内容经过 urlencode 编码,进行解码
  76. $msg = json_decode(urldecode($msg), true);
  77. if ($data['type'] == 'TRADE_ORDER_STATE') {
  78. // 读取订单信息
  79. $client = new \Youzan\Open\Client($this->accessToken);
  80. $result = $client->post('youzan.trade.get', '3.0.0', ['tid' => $msg['tid']]);
  81. if (isset($result['error_response'])) {
  82. Log::info('【有赞云】回调订单信息错误:' . $result['error_response']['msg']);
  83. exit();
  84. }
  85. $payment = Payment::query()->where('qr_id', $result['response']['trade']['qr_id'])->first();
  86. if (!$payment) {
  87. Log::info('【有赞云】回调订单不存在');
  88. exit();
  89. }
  90. // 等待支付
  91. if ($data['status'] == 'WAIT_BUYER_PAY') {
  92. Log::info('【有赞云】等待支付' . urldecode($data['msg']));
  93. exit();
  94. }
  95. // 交易成功
  96. if ($data['status'] == 'TRADE_SUCCESS') {
  97. if ($payment->status != '0') {
  98. Log::info('【有赞云】回调订单状态不正确');
  99. exit();
  100. }
  101. // 处理订单
  102. DB::beginTransaction();
  103. try {
  104. // 更新支付单
  105. $payment->pay_way = $msg['pay_type'] == '微信支付' ? 1 : 2; // 1-微信、2-支付宝
  106. $payment->status = 1;
  107. $payment->save();
  108. // 更新订单
  109. $order = Order::query()->with(['user'])->where('oid', $payment->oid)->first();
  110. $order->status = 2;
  111. $order->save();
  112. // 优惠券置为已使用
  113. $coupon = Coupon::query()->where('id', $order->coupon_id)->first();
  114. if ($coupon) {
  115. if ($coupon->usage == 1) {
  116. $coupon->status = 1;
  117. $coupon->save();
  118. }
  119. // 写入日志
  120. $couponLog = new CouponLog();
  121. $couponLog->coupon_id = $coupon->id;
  122. $couponLog->goods_id = $order->goods_id;
  123. $couponLog->order_id = $order->oid;
  124. $couponLog->save();
  125. }
  126. // 如果买的是套餐,则先将之前购买的所有套餐置都无效,并扣掉之前所有套餐的流量
  127. $goods = Goods::query()->where('id', $order->goods_id)->first();
  128. if ($goods->type == 2) {
  129. $existOrderList = Order::query()
  130. ->with(['goods'])
  131. ->whereHas('goods', function ($q) {
  132. $q->where('type', 2);
  133. })
  134. ->where('user_id', $order->user_id)
  135. ->where('oid', '<>', $order->oid)
  136. ->where('is_expire', 0)
  137. ->get();
  138. foreach ($existOrderList as $vo) {
  139. Order::query()->where('oid', $vo->oid)->update(['is_expire' => 1]);
  140. User::query()->where('id', $order->user_id)->decrement('transfer_enable', $vo->goods->traffic * 1048576);
  141. }
  142. }
  143. // 把商品的流量加到账号上
  144. User::query()->where('id', $order->user_id)->increment('transfer_enable', $goods->traffic * 1048576);
  145. // 套餐就改流量重置日,加油包不改
  146. if ($goods->type == 2) {
  147. // 将商品的有效期和流量自动重置日期加到账号上
  148. $traffic_reset_day = in_array(date('d'), [29, 30, 31]) ? 28 : abs(date('d'));
  149. User::query()->where('id', $order->user_id)->update(['traffic_reset_day' => $traffic_reset_day, 'expire_time' => date('Y-m-d', strtotime("+" . $goods->days . " days", strtotime($order->user->expire_time))), 'enable' => 1]);
  150. } else {
  151. // 将商品的有效期和流量自动重置日期加到账号上
  152. User::query()->where('id', $order->user_id)->update(['expire_time' => date('Y-m-d', strtotime("+" . $goods->days . " days")), 'enable' => 1]);
  153. }
  154. // 写入返利日志
  155. if ($order->user->referral_uid) {
  156. $referralLog = new ReferralLog();
  157. $referralLog->user_id = $order->user_id;
  158. $referralLog->ref_user_id = $order->user->referral_uid;
  159. $referralLog->order_id = $order->oid;
  160. $referralLog->amount = $order->totalPrice;
  161. $referralLog->ref_amount = $order->totalPrice * self::$config['referral_percent'];
  162. $referralLog->status = 0;
  163. $referralLog->save();
  164. }
  165. DB::commit();
  166. } catch (\Exception $e) {
  167. DB::rollBack();
  168. Log::info('【有赞云】更新支付单和订单异常');
  169. }
  170. exit();
  171. }
  172. // 超时自动关闭订单
  173. if ($data['status'] == 'TRADE_CLOSED') {
  174. if ($payment->status != 0) {
  175. Log::info('【有赞云】自动关闭支付单异常,本地支付单状态不正确');
  176. exit();
  177. }
  178. $order = Order::query()->where('oid', $payment->oid)->first();
  179. if ($order->status != 0) {
  180. Log::info('【有赞云】自动关闭支付单异常,本地订单状态不正确');
  181. exit();
  182. }
  183. DB::beginTransaction();
  184. try {
  185. // 关闭支付单
  186. $payment->status = -1;
  187. $payment->save();
  188. // 关闭订单
  189. $order->status = -1;
  190. $order->save();
  191. DB::commit();
  192. } catch (\Exception $e) {
  193. DB::rollBack();
  194. Log::info('【有赞云】更新支付单和订单异常');
  195. }
  196. exit();
  197. }
  198. }
  199. if ($data['type'] == 'TRADE') {
  200. if ($data['status'] == 'WAIT_BUYER_PAY') {
  201. Log::info('【有赞云】等待支付' . urldecode($data['msg']));
  202. exit();
  203. }
  204. if ($data['status'] == 'TRADE_SUCCESS') {
  205. Log::info('【有赞云】支付成功' . urldecode($data['msg']));
  206. exit();
  207. }
  208. if ($data['status'] == 'TRADE_CLOSED') {
  209. Log::info('【有赞云】超时未支付自动支付' . urldecode($data['msg']));
  210. exit();
  211. }
  212. }
  213. exit();
  214. }
  215. public function show(Request $request)
  216. {
  217. exit('show');
  218. }
  219. // 写入回调请求日志
  220. private function callbackLog($client_id, $yz_id, $kdt_id, $kdt_name, $mode, $msg, $sendCount, $sign, $status, $test, $type, $version)
  221. {
  222. $paymentCallback = new PaymentCallback();
  223. $paymentCallback->client_id = $client_id;
  224. $paymentCallback->yz_id = $yz_id;
  225. $paymentCallback->kdt_id = $kdt_id;
  226. $paymentCallback->kdt_name = $kdt_name;
  227. $paymentCallback->mode = $mode;
  228. $paymentCallback->msg = urldecode($msg);
  229. $paymentCallback->sendCount = $sendCount;
  230. $paymentCallback->sign = $sign;
  231. $paymentCallback->status = $status;
  232. $paymentCallback->test = $test;
  233. $paymentCallback->type = $type;
  234. $paymentCallback->version = $version;
  235. $paymentCallback->save();
  236. return $paymentCallback->id;
  237. }
  238. }