Payios.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use addons\epay\library\Service;
  6. /**
  7. * 充值配置与充值订单
  8. */
  9. class Payios extends Api
  10. {
  11. protected $noNeedLogin = ['auto_renewal_vip_notify'];
  12. protected $noNeedRight = ['*'];
  13. //vip ios用的
  14. public function vip_config_ios(){
  15. $list = Db::name('payvip_config_ios')->field('id,money,days,title,info,bundle_id,is_lianxu')->where('is_show',1)->order('weight asc,id asc')->select();
  16. $data['vipconfig'] = $list;
  17. $data['vip_endtime'] = model('wallet')->getWallet($this->auth->id,'vip_endtime');
  18. $data['is_vip'] = $data['vip_endtime'] > time() ? 1 : 0;
  19. $data['avatar'] = localpath_to_netpath($this->auth->avatar);
  20. $this->success('success',$data);
  21. }
  22. //vip用的,创建订单
  23. public function vip_recharge_ios(){
  24. $rc_id = input('rc_id',0);
  25. $platform = 'app';
  26. $uid = $this->auth->id;
  27. if(!$rc_id){
  28. $this->error('请选择会员套餐');
  29. }
  30. if(!$this->user_auth_limit()){
  31. $this->error('请先完成实名认证');
  32. }
  33. //赋值money
  34. $recharge_config = Db::name('payvip_config_ios')->where('id',$rc_id)->find();
  35. $money = $recharge_config['money'];
  36. if($money<=0)
  37. {
  38. $this->error('支付金额必须大于0');
  39. }
  40. if($money > 10000){
  41. $this->error('支付金额太大');
  42. }
  43. //创建订单
  44. $data = [];
  45. $data['user_id'] = $uid;
  46. $data['out_trade_no'] = createUniqueNo('V',$uid); // 数据库订单号加密
  47. $data['order_amount'] = $money;
  48. $data['createtime'] = time();
  49. $data['pay_type'] = 'ios';
  50. $data['platform'] = $platform;
  51. $data['order_status'] = 0;
  52. $data['table_name'] = 'vip_recharge';
  53. $data['table_id'] = 0;
  54. $data['args'] = json_encode(['days'=>$recharge_config['days']]);
  55. $data['bundle_id'] = $recharge_config['bundle_id'];
  56. $orderid = Db::name('pay_order')->insertGetId($data);
  57. $this->success('success',$data['out_trade_no']);
  58. }
  59. //vip,苹果内购支付回调
  60. //因前端不传入订单号,作废,且与gold_notify_iosnew 已完成合并
  61. public function vip_notify_ios(){
  62. //苹果内购的验证收据
  63. $receipt_data = input('apple_receipt', '', 'trim');
  64. $order_no = input('order_no', '', 'trim');
  65. filePut('VIP ios充值:参数apple_receipt='.$receipt_data.',order_no='.$order_no);
  66. if (!$receipt_data || !$order_no) {
  67. $this->error('缺少参数');
  68. }
  69. Db::startTrans();
  70. // 查找订单
  71. $order_info = Db::name('pay_order')->where(['out_trade_no' => $order_no])->lock(true)->find();
  72. if (!$order_info) {
  73. Db::rollback();
  74. filePut('VIP ios充值:订单丢失out_trade_no='.$order_no);
  75. $this->error('订单丢失');
  76. }
  77. if ($order_info['order_status'] == 1) {
  78. Db::rollback();
  79. $this->success('充值成功');
  80. }
  81. // 验证支付状态
  82. $result = $this->validate_apple_pay($receipt_data);
  83. if (!$result['status']) {// 验证不通过
  84. Db::rollback();
  85. filePut('VIP ios充值:验证out_trade_no='.$order_no.','.$result['message']);
  86. $this->error($result['message']);
  87. }
  88. $count = count($result['data']['receipt']['in_app']);
  89. $use_count = $count - 1;
  90. $args = json_decode($order_info['args'],true);
  91. if ($result['data']['receipt']['in_app'][$use_count]['product_id'] != $order_info['bundle_id']) {
  92. Db::rollback();
  93. filePut('VIP ios充值:非法请求,请立刻停止out_trade_no='.$order_no.','.$result['message'].','.$result['data']['receipt']['in_app'][$use_count]['product_id'].'!='.$order_info['bundle_id']);
  94. $this->error('非法请求,请立刻停止');
  95. }
  96. //逻辑开始
  97. //先充值
  98. $user_info = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->lock(true)->find();
  99. if($user_info['vip_endtime'] < time()){
  100. //过期了
  101. $vip_endtime = time() + (intval($args['days']) * 86400);
  102. }else{
  103. //追加vip
  104. $vip_endtime = $user_info['vip_endtime'] + (intval($args['days']) * 86400);
  105. }
  106. $update_data = [
  107. 'vip_endtime'=>$vip_endtime,
  108. ];
  109. $result = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->update($update_data);
  110. if($result === false)
  111. {
  112. Db::rollback();
  113. filePut('VIP ios充值:验证out_trade_no='.$order_no.',逻辑续费vip时间失败');
  114. $this->error('充值失败');
  115. }
  116. // 修改订单状态
  117. $ros = Db::name('pay_order')->where(['out_trade_no' => $order_no])->update(['order_status'=>1,'notifytime'=>time()]);
  118. if($ros === false) {
  119. filePut('VIP ios充值:充值失败out_trade_no='.$order_no.','.$result['message'].','.'修改订单状态失败');
  120. Db::rollback();
  121. $this->error('充值失败');
  122. }
  123. Db::commit();
  124. $this->success('充值成功');
  125. //逻辑结束
  126. }
  127. ////////////////////////////////
  128. //金币充值
  129. public function gold_config_ios(){
  130. $list = Db::name('paygold_webcon_ios')->field('id,money,gold,bundle_id')->where('is_show',1)->order('weigh asc,id asc')->select();
  131. $data['goldconfig'] = $list;
  132. $wallet = model('wallet')->getWallet($this->auth->id);
  133. $data['wallet'] = $wallet;
  134. $data['money_to_gold'] = config('site.money_to_gold');
  135. $this->success('success',$data);
  136. }
  137. //充值金币 创建订单
  138. public function gold_recharge_ios(){
  139. $rc_id = input_post('rc_id',0);
  140. $pay_type = 'ios';
  141. $platform = 'app';
  142. $uid = $this->auth->id;
  143. if(!$rc_id){
  144. $this->error('请选择充值金额');
  145. }
  146. if(!$this->user_auth_limit()){
  147. $this->error('请先完成实名认证');
  148. }
  149. //赋值money
  150. $recharge_config = Db::name('paygold_webcon_ios')->where('id',$rc_id)->find();
  151. $money = $recharge_config['money'] ?: 0;
  152. $gold = $recharge_config['gold'] ?: 0;
  153. //
  154. if($money<=0)
  155. {
  156. $this->error('支付金额必须大于0');
  157. }
  158. if($money > 10000){
  159. $this->error('支付金额太大');
  160. }
  161. //创建订单
  162. $data['user_id'] = $uid;
  163. $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
  164. $data['order_amount'] = $money;
  165. $data['createtime'] = time();
  166. $data['pay_type'] = $pay_type;
  167. $data['platform'] = $platform;
  168. $data['order_status'] = 0;
  169. $data['table_name'] = 'gold_recharge';
  170. $data['table_id'] = 0;
  171. $data['args'] = json_encode(['gold'=>$gold]);
  172. $data['bundle_id'] = $recharge_config['bundle_id'];
  173. $orderid = Db::name('pay_order')->insertGetId($data);
  174. $this->success('success',$data['out_trade_no']);
  175. }
  176. //金币+vip,苹果内购支付回调,app请求的接口
  177. public function gold_notify_iosnew(){
  178. //苹果内购的验证收据
  179. $receipt_data = input('apple_receipt', '', 'trim');
  180. $password = input('password', '', 'trim');
  181. $out_trade_no = input('out_trade_no', '', 'trim');
  182. $transaction_id = input('transaction_id', '', 'trim');
  183. if (!$receipt_data || !$out_trade_no || !$transaction_id) {
  184. $this->error('缺少参数');
  185. }
  186. filePut("\r\n\r\n".'新请求');
  187. $prefix = 'ios充值,登录user_id:'.$this->auth->id.',out_trade_no:'.$out_trade_no.',传入transaction_id:'.$transaction_id.'。';
  188. filePut($prefix.'参数apple_receipt:'.$receipt_data);
  189. Db::startTrans();
  190. // 查找订单
  191. $order_map = [
  192. // 'user_id' => $this->auth->id,
  193. 'out_trade_no' => $out_trade_no,
  194. ];
  195. $order_info = Db::name('pay_order')->where($order_map)->lock(true)->find();
  196. if (!$order_info) {
  197. Db::rollback();
  198. filePut($prefix.'不存在的订单');
  199. $this->error('不存在的订单');
  200. }
  201. if ($order_info['order_status'] == 1) {
  202. Db::rollback();
  203. filePut($prefix.'充值早已完成');
  204. $this->success('充值已完成');
  205. }
  206. // 验证支付状态
  207. $result = $this->validate_apple_pay($receipt_data,$password);
  208. if (!$result['status']) {// 验证不通过
  209. Db::rollback();
  210. filePut($prefix.'验证'.$result['message']);
  211. $this->error($result['message']);
  212. }
  213. $in_app = $result['data']['receipt']['in_app'];
  214. $only_trans = [];
  215. foreach($in_app as $key => $trans){
  216. if($trans['transaction_id'] == $transaction_id && $trans['product_id'] == $order_info['bundle_id']){
  217. $only_trans = $trans;
  218. }
  219. }
  220. if(empty($only_trans)){
  221. Db::rollback();
  222. filePut($prefix.'未找到匹配的交易,产品id'.$order_info['bundle_id'].',交易id'.$transaction_id);
  223. $this->error('未找到匹配的交易,产品id'.$order_info['bundle_id'].',交易id'.$transaction_id);
  224. }
  225. /*
  226. $count = count($result['data']['receipt']['in_app']);
  227. $use_count = $count - 1;
  228. $product_id = $result['data']['receipt']['in_app'][$use_count]['product_id'];
  229. $my_transaction_id = $result['data']['receipt']['in_app'][$use_count]['transaction_id'];
  230. if($product_id != $order_info['bundle_id']){
  231. Db::rollback();
  232. filePut($prefix.'验证'.'非法请求,请立刻停止product_id:'.$product_id.'!='.$order_info['bundle_id']);
  233. $this->error('非法请求,请立刻停止,产品id错误');
  234. }
  235. if($my_transaction_id != $transaction_id){
  236. Db::rollback();
  237. filePut($prefix.'验证'.'非法请求,请立刻停止transaction_id:'.$my_transaction_id.'!='.$transaction_id);
  238. $this->error('非法请求,请立刻停止,交易id错误');
  239. }*/
  240. //逻辑开始
  241. $args = json_decode($order_info['args'],true);
  242. //先充值
  243. if($order_info['table_name'] == 'gold_recharge'){
  244. $result = model('Wallet')->lockChangeAccountRemain($order_info['user_id'],'gold',$args['gold'],10, '金币充值','pay_order',$order_info['id']);
  245. if($result['status']===false)
  246. {
  247. filePut($prefix.'逻辑添加金币失败');
  248. Db::rollback();
  249. $this->error('充值失败');
  250. }
  251. }
  252. //先充值
  253. if($order_info['table_name'] == 'vip_recharge'){
  254. $user_info = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->lock(true)->find();
  255. if($user_info['vip_endtime'] < time()){
  256. //过期了
  257. $vip_endtime = time() + (intval($args['days']) * 86400);
  258. }else{
  259. //追加vip
  260. $vip_endtime = $user_info['vip_endtime'] + (intval($args['days']) * 86400);
  261. }
  262. $update_data = [
  263. 'vip_endtime'=>$vip_endtime,
  264. ];
  265. $result = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->update($update_data);
  266. if($result === false)
  267. {
  268. filePut($prefix.'逻辑续费vip时间失败');
  269. Db::rollback();
  270. $this->error('充值失败');
  271. }
  272. }
  273. // 修改订单状态
  274. $ros = Db::name('pay_order')->where(['id' => $order_info['id']])->update(['order_status'=>1,'transaction_id' => $transaction_id,'notifytime'=>time()]);
  275. if($ros === false) {
  276. filePut($prefix.'修改订单状态失败');
  277. Db::rollback();
  278. $this->error('充值失败');
  279. }
  280. Db::commit();
  281. filePut($prefix.'充值成功');
  282. $this->success('充值成功');
  283. //逻辑结束
  284. }
  285. //因前端不传入订单号,作废
  286. public function gold_notify_ios(){
  287. //苹果内购的验证收据
  288. $receipt_data = input('apple_receipt', '', 'trim');
  289. $order_no = input('order_no', '', 'trim');
  290. filePut('金币 ios充值:参数apple_receipt='.$receipt_data.',order_no='.$order_no);
  291. if (!$receipt_data || !$order_no) {
  292. $this->error('缺少参数');
  293. }
  294. Db::startTrans();
  295. // 查找订单
  296. $order_info = Db::name('pay_order')->where(['out_trade_no' => $order_no])->lock(true)->find();
  297. if (!$order_info) {
  298. Db::rollback();
  299. filePut('金币 ios充值:订单丢失out_trade_no='.$order_no);
  300. $this->error('订单丢失');
  301. }
  302. if ($order_info['order_status'] == 1) {
  303. Db::rollback();
  304. $this->success('充值成功');
  305. }
  306. // 验证支付状态
  307. $result = $this->validate_apple_pay($receipt_data);
  308. if (!$result['status']) {// 验证不通过
  309. Db::rollback();
  310. filePut('金币 ios充值:验证out_trade_no='.$order_no.','.$result['message']);
  311. $this->error($result['message']);
  312. }
  313. $count = count($result['data']['receipt']['in_app']);
  314. $use_count = $count - 1;
  315. $args = json_decode($order_info['args'],true);
  316. if ($result['data']['receipt']['in_app'][$use_count]['product_id'] != $order_info['bundle_id']) {
  317. Db::rollback();
  318. filePut('金币 ios充值:非法请求,请立刻停止out_trade_no='.$order_no.','.$result['message'].','.$result['data']['receipt']['in_app'][$use_count]['product_id'].'!='.$order_info['bundle_id']);
  319. $this->error('非法请求,请立刻停止');
  320. }
  321. //逻辑开始
  322. //先充值
  323. $result = model('Wallet')->lockChangeAccountRemain($order_info['user_id'],'gold',$args['gold'],10, '金币充值','pay_order',$order_info['id']);
  324. if($result['status']===false)
  325. {
  326. filePut('金币 ios充值:验证out_trade_no='.$order_no.',逻辑添加金币失败');
  327. Db::rollback();
  328. return false;
  329. }
  330. // 修改订单状态
  331. $ros = Db::name('pay_order')->where(['out_trade_no' => $order_no])->update(['order_status'=>1,'notifytime'=>time()]);
  332. if($ros === false) {
  333. filePut('金币 ios充值:充值失败out_trade_no='.$order_no.','.$result['message'].','.'修改订单状态失败');
  334. Db::rollback();
  335. $this->error('充值失败');
  336. }
  337. Db::commit();
  338. $this->success('充值成功');
  339. //逻辑结束
  340. }
  341. ////////////////////////////////////
  342. //苹果自动扣费回调
  343. public function auto_renewal_vip_notify(){
  344. $this->notify_log_start('ios');
  345. }
  346. ///////////////////////////////////////////////////////////////////////////////////////////////
  347. //异步日志
  348. private function notify_log_start($paytype = 'ios'){
  349. //记录支付回调数据
  350. ignore_user_abort(); // run script in background
  351. set_time_limit(30);
  352. // 日志文件 start
  353. $log_base_dir = '../paylog/'.$paytype.'/';
  354. if (!is_dir($log_base_dir))
  355. {
  356. mkdir($log_base_dir, 0770, true);
  357. @chmod($log_base_dir, 0770);
  358. }
  359. $notify_file = $log_base_dir.'notify.txt';
  360. if(!file_exists($notify_file)) {
  361. @touch($notify_file);
  362. @chmod($notify_file, 0770);
  363. }
  364. if(filesize($notify_file)>5242880)//大于5M自动切换
  365. {
  366. rename($notify_file, $log_base_dir.'notify_'.date('Y_m_d_H_i_s').'.txt');
  367. }
  368. if(!file_exists($notify_file)) {
  369. @touch($notify_file);
  370. @chmod($notify_file, 0770);
  371. }
  372. // 日志文件 end
  373. //开始写入
  374. $_REQUEST = isset($_REQUEST) ? $_REQUEST : array();
  375. if($_REQUEST && $paytype == 'alipay') {
  376. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收request]".json_encode($_REQUEST), FILE_APPEND);
  377. } else {
  378. $xml = file_get_contents("php://input");
  379. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流原始数据] \n".$xml, FILE_APPEND);
  380. $xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  381. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流] ".json_encode($xmlObj), FILE_APPEND);
  382. }
  383. ini_set('display_errors','On');
  384. return $notify_file;
  385. }
  386. /**
  387. * 验证AppStore内付
  388. * @param string $receipt_data 付款后凭证
  389. * @return array 验证是否成功
  390. */
  391. function validate_apple_pay($receipt_data = '',$password = '') {
  392. // 验证参数
  393. if (strlen($receipt_data) < 20) {
  394. $result = array(
  395. 'status' => false,
  396. 'message' => '非法参数'
  397. );
  398. return $result;
  399. }
  400. // 请求验证
  401. $html = $this->curl($receipt_data,$password);
  402. $data = json_decode($html, true);
  403. // p($data);die;
  404. if ($data['status'] == '21002') {
  405. // $this->error('21002');
  406. $result = array(
  407. 'status' => false,
  408. 'message' => 'status:21002'
  409. );
  410. return $result;
  411. }
  412. // 如果是沙盒数据 则验证沙盒模式 21008;正式数据 21007
  413. // if ($data['status'] == '21007') {
  414. // // 请求验证
  415. // $html = $this->curl($receipt_data, 1);
  416. // $data = json_decode($html, true);
  417. // $data['sandbox'] = '1';
  418. // }
  419. if (isset($_GET['debug'])) {
  420. exit(json_encode($data));
  421. }
  422. // if ($data['receipt']['bundle_id'] != 'com.liuniukeji.mayivideo') {
  423. if ($data['receipt']['bundle_id'] != 'com.huxiu.tken') {
  424. $result = array(
  425. 'status' => false,
  426. 'message' => '非法请求',
  427. 'data' => $data
  428. );
  429. return $result;
  430. }
  431. // 判断是否购买成功
  432. if (intval($data['status']) === 0) {
  433. $result = array(
  434. 'status' => true,
  435. 'message' => '购买成功',
  436. 'data' => $data
  437. );
  438. } else {
  439. $result = array(
  440. 'status' => false,
  441. 'message' => '购买失败 status:' . $data['status']
  442. );
  443. }
  444. return $result;
  445. }
  446. /**
  447. * 0 票据校验成功
  448. * 21000 App Store不能读取你提供的JSON对象25
  449. * 21002 receipt-data域的数据有问题
  450. * 21003 receipt无法通过验证
  451. * 21004 提供的shared secret不匹配你账号中的shared secret
  452. * 21005 receipt服务器当前不可用
  453. * 21006 receipt合法,但是订阅已过期。服务器接收到这个状态码时,receipt数据仍然会解码并一起发送
  454. * 21007 receipt是Sandbox receipt,但却发送至生产系统的验证服务
  455. * 21008 receipt是生产receipt,但却发送至Sandbox环境的验证服务
  456. */
  457. //苹果也是建议这个校验逻辑由服务端完成。服务器需要先去请求正式环境。如果receipt是正式环境的,那么这个时候苹果会返回(21007)告诉我们这个是沙盒的receipt,那么服务器再去请求sandbox环境。
  458. function curl($receipt_data, $password = '') {
  459. //小票信息
  460. $POSTFIELDS = array("receipt-data" => $receipt_data);
  461. if(!empty($password)){
  462. $POSTFIELDS['password'] = $password;
  463. }
  464. $POSTFIELDS = json_encode($POSTFIELDS, 320);
  465. // $POSTFIELDS = '{' . '"receipt-data":' . '"' . $receipt_data . '"' .'}';
  466. // p($POSTFIELDS);die;
  467. //正式购买地址 沙盒购买地址
  468. $url_buy = "https://buy.itunes.apple.com/verifyReceipt";
  469. $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
  470. // if ($sandbox > 0) {
  471. if (config('site.ios_pay_sandbox') > 0) {
  472. $url = $url_buy;
  473. } else {
  474. $url = $url_sandbox;
  475. }
  476. // 上架通过直接使用正式地址
  477. // $url = $url_sandbox;
  478. $ch = curl_init($url);
  479. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  480. curl_setopt($ch, CURLOPT_POST, true);
  481. curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
  482. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //这两行一定要加,不加会报SSL 错误
  483. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  484. $response = curl_exec($ch);
  485. $errno = curl_errno($ch);
  486. curl_close($ch);
  487. if ($errno != 0) {
  488. return $errno;
  489. } else {
  490. return $response;
  491. }
  492. }
  493. }