Payios.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use app\common\library\Transaction;
  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. $data['is_lianxu'] = $recharge_config['is_lianxu'];
  57. $orderid = Db::name('pay_order')->insertGetId($data);
  58. $this->success('success',$data['out_trade_no']);
  59. }
  60. ////////////////////////////////
  61. //金币充值
  62. public function gold_config_ios(){
  63. $list = Db::name('paygold_webcon_ios')->field('id,money,gold,bundle_id')->where('is_show',1)->order('weigh asc,id asc')->select();
  64. $data['goldconfig'] = $list;
  65. $wallet = model('wallet')->getWallet($this->auth->id);
  66. $data['wallet'] = $wallet;
  67. $data['money_to_gold'] = config('site.money_to_gold');
  68. $this->success('success',$data);
  69. }
  70. //充值金币 创建订单
  71. public function gold_recharge_ios(){
  72. $rc_id = input_post('rc_id',0);
  73. $pay_type = 'ios';
  74. $platform = 'app';
  75. $uid = $this->auth->id;
  76. if(!$rc_id){
  77. $this->error('请选择充值金额');
  78. }
  79. if(!$this->user_auth_limit()){
  80. $this->error('请先完成实名认证');
  81. }
  82. //赋值money
  83. $recharge_config = Db::name('paygold_webcon_ios')->where('id',$rc_id)->find();
  84. $money = $recharge_config['money'] ?: 0;
  85. $gold = $recharge_config['gold'] ?: 0;
  86. //
  87. if($money<=0)
  88. {
  89. $this->error('支付金额必须大于0');
  90. }
  91. if($money > 10000){
  92. $this->error('支付金额太大');
  93. }
  94. //创建订单
  95. $data['user_id'] = $uid;
  96. $data['out_trade_no'] = createUniqueNo('P',$uid); // 数据库订单号加密
  97. $data['order_amount'] = $money;
  98. $data['createtime'] = time();
  99. $data['pay_type'] = $pay_type;
  100. $data['platform'] = $platform;
  101. $data['order_status'] = 0;
  102. $data['table_name'] = 'gold_recharge';
  103. $data['table_id'] = 0;
  104. $data['args'] = json_encode(['gold'=>$gold]);
  105. $data['bundle_id'] = $recharge_config['bundle_id'];
  106. $orderid = Db::name('pay_order')->insertGetId($data);
  107. $this->success('success',$data['out_trade_no']);
  108. }
  109. ////////////////////////////////////////
  110. //订阅信息处理,续订情况下,单独分支方法
  111. public function expires(){
  112. //苹果订阅的验证收据
  113. $original_transaction_id = input('original_transaction_id','','trim');
  114. $receipt_data = input('apple_receipt', '', 'trim');
  115. $transaction_id = input('transaction_id', '', 'trim');
  116. $out_trade_no = input('out_trade_no', '', 'trim');
  117. filePut("\r\n\r\n".'新请求VIP订阅');
  118. $prefix = 'iosVIP订阅登录user_id:'.$this->auth->id.',传入original_transaction_id:'.$original_transaction_id.',传入transaction_id:'.$transaction_id.'。';
  119. filePut($prefix.'参数apple_receipt:'.$receipt_data);
  120. if (!$receipt_data || !$original_transaction_id || !$transaction_id) {
  121. $this->error('缺少参数');
  122. }
  123. //检查重复订单
  124. $check_map = [
  125. 'original_transaction_id' => $original_transaction_id,
  126. 'transaction_id' => $transaction_id,
  127. ];
  128. $check_order = Db::name('user_vipxufei_task')->where($check_map)->field('id')->find();
  129. if($check_order){
  130. filePut($prefix.'续费早已完成');
  131. $this->success('充值早已完成');
  132. }
  133. // 验证支付状态
  134. $result = $this->validate_apple_pay($receipt_data);
  135. if (!$result['status']) {// 验证不通过
  136. filePut($prefix.'验证'.$result['message']);
  137. $this->error($result['message']);
  138. }
  139. $in_app = $result['data']['receipt']['in_app'];
  140. $only_trans = [];
  141. foreach($in_app as $key => $trans){
  142. //非订阅信息,原始信息,不验证product_id因为可能换了新的套餐
  143. if($trans['transaction_id'] == $transaction_id && $original_transaction_id == $trans['original_transaction_id']/* && $trans['product_id'] == $order_info['bundle_id']*/){
  144. $only_trans = $trans;
  145. break;
  146. }
  147. }
  148. if(empty($only_trans)){
  149. filePut($prefix.'未找到匹配的交易');
  150. $this->error('未找到匹配的交易');
  151. }
  152. Db::startTrans();
  153. //查找订单,可能找到以前的,非当前用户的。根据原始id 和 用户id不是终生绑定
  154. $order_map = [
  155. 'original_transaction_id' => $original_transaction_id,
  156. ];
  157. $order_info = Db::name('user_vipxufei_task')->where($order_map)->order('expires_date_ms desc')->find();
  158. if (!$order_info) {
  159. Db::rollback();
  160. filePut($prefix.'不存在的订单');
  161. $this->error('不存在的订单');
  162. }
  163. //续订,但是换了产品了,重新定义order_info
  164. //原始id换给别人用了
  165. $order_info_bundle_id = $order_info['bundle_id'];
  166. $order_info_user_id = $order_info['user_id'];
  167. //在app里,不能连续购买同一个续费规格(bunder_id),可以升级或降级另一个续费规格。也可以在苹果商店直接修改规格(不产生新订单)。
  168. if($only_trans['product_id'] != $order_info['bundle_id'] || $order_info['user_id'] != $this->auth->id){
  169. $pay_order_map = [
  170. 'user_id' => ($order_info['user_id'] != $this->auth->id) ? $this->auth->id : $order_info['user_id'],
  171. 'bundle_id' => ($order_info['bundle_id'] != $only_trans['product_id']) ? $only_trans['product_id'] : $order_info['bundle_id'],
  172. 'order_status' => 0,
  173. 'table_name' => 'vip_recharge',
  174. ];
  175. $pay_order = Db::name('pay_order')->where($pay_order_map)->order('id desc')->lock(true)->find();
  176. if(!$pay_order){
  177. /*Db::rollback();
  178. filePut($prefix.'未找到匹配的交易,新订单找不到');
  179. $this->error('未找到匹配的新订单');*/
  180. //创建订单
  181. $recharge_config = Db::name('payvip_config_ios')->where('bundle_id',$pay_order_map['bundle_id'])->find();
  182. $new_order = [
  183. 'user_id' => $pay_order_map['user_id'],
  184. 'out_trade_no'=> createUniqueNo('NV',$pay_order_map['user_id']), // 数据库订单号加密
  185. 'order_amount'=> $recharge_config['money'],
  186. 'createtime'=> time(),
  187. 'pay_type'=> 'ios',
  188. 'platform'=> 'app',
  189. 'order_status'=> 0,
  190. 'table_name'=> 'vip_recharge',
  191. 'table_id'=> 0,
  192. 'args'=> json_encode(['days'=>$recharge_config['days']]),
  193. 'bundle_id'=> $recharge_config['bundle_id'],
  194. 'is_lianxu'=> $recharge_config['is_lianxu'],
  195. ];
  196. $new_orderid = Db::name('pay_order')->insertGetId($new_order);
  197. if(!$new_orderid){
  198. Db::rollback();
  199. filePut($prefix.'未找到匹配的交易,创建新订单失败');
  200. $this->error('创建新订单失败');
  201. }
  202. $pay_order = $new_order;
  203. $pay_order['id'] = $new_orderid;
  204. }
  205. // 修改订单状态
  206. $update_order = [
  207. 'notifytime'=>time(),
  208. 'order_status'=>1,
  209. 'original_transaction_id' => $only_trans['original_transaction_id'],
  210. 'in_app_one' => json_encode($only_trans),
  211. ];
  212. $ros = Db::name('pay_order')->where(['id' => $pay_order['id']])->update($update_order);
  213. if($ros === false) {
  214. filePut($prefix.'修改订单状态失败');
  215. Db::rollback();
  216. $this->error('充值失败');
  217. }
  218. $args = json_decode($pay_order['args'],true);
  219. //修改order_info
  220. $order_info['order_id'] = $pay_order['id'];
  221. $order_info['user_id'] = $pay_order['user_id'];
  222. $order_info['bundle_id'] = $pay_order['bundle_id'];
  223. $order_info['days'] = $args['days'];
  224. $order_info['original_transaction_id'] = $only_trans['original_transaction_id'];//多余
  225. }
  226. //验证时间,不得小于最新的一条预定信息
  227. // if($order_info_user_id == $this->auth->id){
  228. if($only_trans['purchase_date_ms'] <= $order_info['purchase_date_ms']/* || $only_trans['expires_date_ms'] <= $order_info['expires_date_ms']*/){
  229. Db::rollback();
  230. filePut($prefix.'时间对不上,返回成功,finish掉');
  231. $this->success('时间对不上,返回成功,finish掉');
  232. }
  233. // }
  234. //逻辑开始
  235. //先充值
  236. $user_info = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->lock(true)->find();
  237. if($user_info['vip_endtime'] < time()){
  238. //过期了
  239. $vip_endtime = time() + (intval($order_info['days']) * 86400);
  240. $vip_type = 1;
  241. }else{
  242. //追加vip
  243. $vip_endtime = $user_info['vip_endtime'] + (intval($order_info['days']) * 86400);
  244. $vip_type = 2;
  245. }
  246. $update_data = [
  247. 'vip_endtime'=>$vip_endtime,
  248. ];
  249. $result = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->update($update_data);
  250. if($result === false)
  251. {
  252. filePut($prefix.'逻辑续费vip时间失败');
  253. Db::rollback();
  254. $this->error('充值失败');
  255. }
  256. //记录日志
  257. $log_data = [
  258. 'user_id' => $order_info['user_id'],
  259. 'before' => $user_info['vip_endtime'],
  260. 'change_value' => intval($order_info['days']) * 86400,
  261. 'remain' => $vip_endtime,
  262. 'remark' => 'ios续费vip',
  263. 'createtime' => time(),
  264. 'vip_type' => $vip_type,
  265. ];
  266. Db::name('user_vip_log')->insertGetId($log_data);
  267. //逻辑结束
  268. //添加新的一个task
  269. $task_data = $order_info;
  270. unset($task_data['id']);
  271. unset($task_data['transaction_info']);
  272. $task_data['createtime'] = time();
  273. $task_data['apple_receipt'] = $receipt_data;
  274. $task_data['in_app_one'] = json_encode($only_trans);
  275. $task_data['transaction_id'] = $transaction_id;
  276. $task_data['times'] = $order_info['times'] + 1;
  277. $task_data['original_purchase_date_ms'] = $only_trans['original_purchase_date_ms'];
  278. $task_data['purchase_date_ms'] = $only_trans['purchase_date_ms'];
  279. $task_data['expires_date_ms'] = $only_trans['expires_date_ms'];
  280. //换了产品了,或者订单的user_id被改过了
  281. if($only_trans['product_id'] != $order_info_bundle_id || $order_info['user_id'] != $order_info_user_id){
  282. $task_data['times'] = 1;//回归1
  283. }
  284. $task_id = Db::name('user_vipxufei_task')->insertGetId($task_data);
  285. if(!$task_id)
  286. {
  287. filePut($prefix.'用户添加vipxufei_task失败');
  288. Db::rollback();
  289. $this->error('充值失败');
  290. }
  291. Db::commit();
  292. filePut($prefix.'充值成功'.$task_id);
  293. $this->success('充值成功'.$task_id);
  294. //逻辑结束
  295. }
  296. //金币+vip,苹果内购支付回调,app请求的接口
  297. public function gold_notify_iosnew(){
  298. $original_transaction_id = input('original_transaction_id','','trim');
  299. if(!empty($original_transaction_id)){
  300. //订阅信息
  301. $this->expires();
  302. }
  303. //苹果内购的验证收据
  304. $receipt_data = input('apple_receipt', '', 'trim');
  305. $out_trade_no = input('out_trade_no', '', 'trim');
  306. $transaction_id = input('transaction_id', '', 'trim');
  307. filePut("\r\n\r\n".'新请求');
  308. $prefix = 'ios充值,登录user_id:'.$this->auth->id.',out_trade_no:'.$out_trade_no.',传入transaction_id:'.$transaction_id.'。';
  309. filePut($prefix.'参数apple_receipt:'.$receipt_data);
  310. if (!$receipt_data || !$out_trade_no || !$transaction_id) {
  311. $this->error('缺少参数');
  312. }
  313. Db::startTrans();
  314. // 查找订单
  315. $order_map = [
  316. // 'user_id' => $this->auth->id,
  317. 'out_trade_no' => $out_trade_no,
  318. //'original_transaction_id' => $transaction_id,
  319. ];
  320. $order_info = Db::name('pay_order')->where($order_map)->lock(true)->find();
  321. if (!$order_info) {
  322. Db::rollback();
  323. filePut($prefix.'不存在的订单');
  324. $this->error('不存在的订单');
  325. }
  326. if ($order_info['order_status'] == 1) {
  327. Db::rollback();
  328. filePut($prefix.'充值早已完成');
  329. $this->success('充值已完成');
  330. }
  331. // 验证支付状态
  332. $result = $this->validate_apple_pay($receipt_data);
  333. if (!$result['status']) {// 验证不通过
  334. Db::rollback();
  335. filePut($prefix.'验证'.$result['message']);
  336. $this->error($result['message']);
  337. }
  338. $in_app = $result['data']['receipt']['in_app'];
  339. $only_trans = [];
  340. foreach($in_app as $key => $trans){
  341. //非订阅信息,原始信息
  342. // $trans['transaction_id'] == $transaction_id 这个不重要,重要的是后面2个。应该也重要,保证这次处理的是初始交易
  343. if($trans['transaction_id'] == $transaction_id && $transaction_id == $trans['original_transaction_id']){
  344. if($trans['product_id'] == $order_info['bundle_id']){
  345. $only_trans = $trans;
  346. break;
  347. }else{
  348. //找上一个真正的订单
  349. $order_map = [
  350. 'user_id' => $this->auth->id,
  351. 'order_status' => 0,
  352. 'bundle_id' => $trans['product_id']
  353. ];
  354. $order_info = Db::name('pay_order')->where($order_map)->lock(true)->find();
  355. if (!$order_info) {
  356. Db::rollback();
  357. filePut($prefix.'不存在的正确产品订单');
  358. $this->error('不存在的正确产品订单');
  359. }
  360. $only_trans = $trans;
  361. break;
  362. }
  363. }
  364. }
  365. if(empty($only_trans)){
  366. Db::rollback();
  367. filePut($prefix.'未找到匹配的交易,产品id'.$order_info['bundle_id'].',原始交易id'.$transaction_id);
  368. $this->error('未找到匹配的交易,产品id'.$order_info['bundle_id'].',原始交易id'.$transaction_id);
  369. }
  370. //逻辑开始
  371. $args = json_decode($order_info['args'],true);
  372. //先充值
  373. if($order_info['table_name'] == 'gold_recharge'){
  374. $result = model('Wallet')->lockChangeAccountRemain($order_info['user_id'],'gold',$args['gold'],10, '金币充值','pay_order',$order_info['id']);
  375. if($result['status']===false)
  376. {
  377. filePut($prefix.'逻辑添加金币失败');
  378. Db::rollback();
  379. $this->error('充值失败');
  380. }
  381. }
  382. //先充值
  383. if($order_info['table_name'] == 'vip_recharge'){
  384. $user_info = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->lock(true)->find();
  385. if($user_info['vip_endtime'] < time()){
  386. //过期了
  387. $vip_endtime = time() + (intval($args['days']) * 86400);
  388. $vip_type = 1;
  389. }else{
  390. //追加vip
  391. $vip_endtime = $user_info['vip_endtime'] + (intval($args['days']) * 86400);
  392. $vip_type = 2;
  393. }
  394. $update_data = [
  395. 'vip_endtime'=>$vip_endtime,
  396. ];
  397. $result = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->update($update_data);
  398. if($result === false)
  399. {
  400. filePut($prefix.'逻辑续费vip时间失败');
  401. Db::rollback();
  402. $this->error('充值失败');
  403. }
  404. //记录日志
  405. $log_data = [
  406. 'user_id' => $order_info['user_id'],
  407. 'before' => $user_info['vip_endtime'],
  408. 'change_value' => intval($args['days']) * 86400,
  409. 'remain' => $vip_endtime,
  410. 'remark' => 'ios购买vip',
  411. 'createtime' => time(),
  412. 'vip_type' => $vip_type,
  413. ];
  414. Db::name('user_vip_log')->insertGetId($log_data);
  415. //订阅vip需要多加的逻辑
  416. if($order_info['is_lianxu'] == 1){
  417. $task_data = [
  418. 'order_id' => $order_info['id'],
  419. 'user_id' => $order_info['user_id'],
  420. 'bundle_id' => $order_info['bundle_id'],
  421. 'days' => $args['days'],
  422. 'createtime' => time(),
  423. 'apple_receipt' => $receipt_data,
  424. 'in_app_one' => json_encode($only_trans),
  425. 'original_transaction_id' => $only_trans['original_transaction_id'],
  426. 'transaction_id' => $only_trans['transaction_id'],
  427. 'status' => 1,
  428. 'times' => 1,
  429. //'notification_type' => 'INITIAL_BUY'.',首次订阅',
  430. 'original_purchase_date_ms' => $only_trans['original_purchase_date_ms'],
  431. 'purchase_date_ms' => $only_trans['purchase_date_ms'],
  432. 'expires_date_ms' => $only_trans['purchase_date_ms'], //第一次借用购买时间戳
  433. ];
  434. $task_id = Db::name('user_vipxufei_task')->insertGetId($task_data);
  435. if(!$task_id)
  436. {
  437. filePut($prefix.'用户添加vipxufei_task失败');
  438. Db::rollback();
  439. $this->error('充值失败');
  440. }
  441. }
  442. }
  443. // 修改订单状态
  444. $update_order = [
  445. 'notifytime'=>time(),
  446. 'order_status'=>1,
  447. 'original_transaction_id' => $only_trans['original_transaction_id'],//理论上与 transaction_id 相等
  448. 'in_app_one' => json_encode($only_trans),
  449. ];
  450. $ros = Db::name('pay_order')->where(['id' => $order_info['id']])->update($update_order);
  451. if($ros === false) {
  452. filePut($prefix.'修改订单状态失败');
  453. Db::rollback();
  454. $this->error('充值失败');
  455. }
  456. Db::commit();
  457. filePut($prefix.'充值成功');
  458. $this->success('充值成功');
  459. //逻辑结束
  460. }
  461. ////////////////////////////////////
  462. /**
  463. * ios 事件通知
  464. * @return bool
  465. */
  466. public function auto_renewal_vip_notify()
  467. {
  468. $this->notify_log_start('ios');
  469. try {
  470. $raw = file_get_contents("php://input");
  471. //filePut("\r\n\r\n".'入口:'.$raw);
  472. $raw = json_decode($raw,true);
  473. $token = isset($raw['signedPayload']) ? $raw['signedPayload'] : '';
  474. $data = $this->verifyAppleToken($token);
  475. dump($data);
  476. if (empty($data)) {
  477. //timbao add
  478. //记录苹果通知逻辑中的bug
  479. exit;
  480. }
  481. $transaction_info = $this->verifyAppleToken($data['data']['signedTransactionInfo']);
  482. dump($transaction_info);
  483. $rs = '默认';
  484. switch ($data['notificationType']) {
  485. case 'DID_RENEW': // 续订
  486. $rs = Transaction::autoRenew($transaction_info);
  487. break;
  488. case 'REFUND': // 退款
  489. $rs = Transaction::refund($transaction_info);
  490. break;
  491. case 'DID_CHANGE_RENEWAL_STATUS': // 连续续订状态 变更
  492. $rs = Transaction::changeRenewStatus($transaction_info, $data['subtype']);
  493. break;
  494. case 'EXPIRED': // 过期通知
  495. $rs = Transaction::updateExpiredTrans($transaction_info);
  496. break;
  497. case 'SUBSCRIBED': // 订阅通知
  498. $rs = Transaction::updateSubscribed($transaction_info, $data['subtype']);
  499. break;
  500. case 'DID_FAIL_TO_RENEW': // 续订失败
  501. $rs = Transaction::updateRenewFailTrans($transaction_info);
  502. break;
  503. case 'DID_CHANGE_RENEWAL_PREF': //升级 降级
  504. if ($data['subtype'] == 'UPGRADE') {
  505. $rs = Transaction::autoRenew($transaction_info, true);
  506. }
  507. break;
  508. }
  509. dump($rs);
  510. exit;
  511. }catch (Exception $e) {
  512. echo $e->getMessage();
  513. exit;
  514. }
  515. }
  516. ////////////////////////////////私有方法///////////////////////////////////////////////////////////////
  517. //异步日志
  518. private function notify_log_start($paytype = 'ios'){
  519. //记录支付回调数据
  520. ignore_user_abort(); // run script in background
  521. set_time_limit(30);
  522. // 日志文件 start
  523. $log_base_dir = '../paylog/'.$paytype.'/';
  524. if (!is_dir($log_base_dir))
  525. {
  526. mkdir($log_base_dir, 0770, true);
  527. @chmod($log_base_dir, 0770);
  528. }
  529. $notify_file = $log_base_dir.'notify.txt';
  530. if(!file_exists($notify_file)) {
  531. @touch($notify_file);
  532. @chmod($notify_file, 0770);
  533. }
  534. if(filesize($notify_file)>5242880)//大于5M自动切换
  535. {
  536. rename($notify_file, $log_base_dir.'notify_'.date('Y_m_d_H_i_s').'.txt');
  537. }
  538. if(!file_exists($notify_file)) {
  539. @touch($notify_file);
  540. @chmod($notify_file, 0770);
  541. }
  542. // 日志文件 end
  543. //开始写入
  544. $_REQUEST = isset($_REQUEST) ? $_REQUEST : array();
  545. if($_REQUEST && $paytype == 'alipay') {
  546. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收request]".json_encode($_REQUEST), FILE_APPEND);
  547. } else {
  548. $xml = file_get_contents("php://input");
  549. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流原始数据] \n".$xml, FILE_APPEND);
  550. /*$xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  551. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流] ".json_encode($xmlObj), FILE_APPEND);*/
  552. }
  553. ini_set('display_errors','On');
  554. return $notify_file;
  555. }
  556. public function test(){
  557. $a = '';
  558. $b = $this->validate_apple_pay($a);
  559. echo json_encode($b);
  560. }
  561. /**
  562. * 验证AppStore内付
  563. * @param string $receipt_data 付款后凭证
  564. * @return array 验证是否成功
  565. * https://juejin.cn/post/7049626884765646884 报错代码
  566. */
  567. function validate_apple_pay($receipt_data = '') {
  568. // 验证参数
  569. if (strlen($receipt_data) < 20) {
  570. $result = array(
  571. 'status' => false,
  572. 'message' => '非法参数'
  573. );
  574. return $result;
  575. }
  576. // 请求验证
  577. $html = $this->curl($receipt_data);
  578. $data = json_decode($html, true);
  579. $data['sandbox'] = '0';
  580. // p($data);die;
  581. if ($data['status'] == '21002') {
  582. $result = array(
  583. 'status' => false,
  584. 'message' => 'status:21002'
  585. );
  586. return $result;
  587. }
  588. // 如果是沙盒数据 则验证沙盒模式 21008;正式数据 21007
  589. if ($data['status'] == '21007') {
  590. // 请求验证
  591. $html = $this->curl($receipt_data, 1);
  592. $data = json_decode($html, true);
  593. $data['sandbox'] = '1';
  594. }
  595. if (isset($_GET['debug'])) {
  596. exit(json_encode($data));
  597. }
  598. if ($data['receipt']['bundle_id'] != 'com.jianxun.company') {
  599. $result = array(
  600. 'status' => false,
  601. 'message' => '非法请求',
  602. 'data' => $data
  603. );
  604. return $result;
  605. }
  606. // 判断是否购买成功
  607. if (intval($data['status']) === 0) {
  608. $result = array(
  609. 'status' => true,
  610. 'message' => '购买成功',
  611. 'data' => $data
  612. );
  613. } else {
  614. $result = array(
  615. 'status' => false,
  616. 'message' => '购买失败 status:' . $data['status']
  617. );
  618. }
  619. // dump($result);
  620. return $result;
  621. }
  622. /**
  623. * 0 票据校验成功
  624. * 21000 App Store不能读取你提供的JSON对象25
  625. * 21002 receipt-data域的数据有问题
  626. * 21003 receipt无法通过验证
  627. * 21004 提供的shared secret不匹配你账号中的shared secret
  628. * 21005 receipt服务器当前不可用
  629. * 21006 receipt合法,但是订阅已过期。服务器接收到这个状态码时,receipt数据仍然会解码并一起发送
  630. * 21007 receipt是Sandbox receipt,但却发送至生产系统的验证服务
  631. * 21008 receipt是生产receipt,但却发送至Sandbox环境的验证服务
  632. */
  633. //苹果也是建议这个校验逻辑由服务端完成。服务器需要先去请求正式环境。如果receipt是正式环境的,那么这个时候苹果会返回(21007)告诉我们这个是沙盒的receipt,那么服务器再去请求sandbox环境。
  634. function curl($receipt_data,$sandbox = 0) {
  635. //小票信息
  636. $POSTFIELDS = [
  637. 'receipt-data' => $receipt_data,
  638. 'password' => 'e2d7987f2cc44862988e5e9e5b543315'
  639. ];
  640. $POSTFIELDS = json_encode($POSTFIELDS, JSON_UNESCAPED_UNICODE);
  641. //正式购买地址 沙盒购买地址
  642. $url_buy = "https://buy.itunes.apple.com/verifyReceipt";
  643. $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
  644. //默认后台控制
  645. if (config('site.ios_pay_sandbox') > 0 ) {
  646. $url = $url_buy;
  647. } else {
  648. $url = $url_sandbox;
  649. }
  650. //强制沙盒
  651. if($sandbox == 1){
  652. $url = $url_sandbox;
  653. }
  654. $ch = curl_init($url);
  655. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  656. curl_setopt($ch, CURLOPT_POST, true);
  657. curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
  658. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //这两行一定要加,不加会报SSL 错误
  659. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  660. $response = curl_exec($ch);
  661. $errno = curl_errno($ch);
  662. curl_close($ch);
  663. if ($errno != 0) {
  664. return $errno;
  665. } else {
  666. return $response;
  667. }
  668. }
  669. /**
  670. * 苹果token解密
  671. *
  672. * @param $token
  673. * @return array|bool|mixed|string
  674. */
  675. private function verifyAppleToken($token)
  676. {
  677. $arr = explode('.',$token);
  678. if(count($arr) != 3){
  679. return [];
  680. }
  681. $header = $arr[0];
  682. $header = base64_decode($header);
  683. $header = json_decode($header,true);
  684. if(empty($header)){
  685. return [];
  686. }
  687. if($header['alg'] != 'ES256'){
  688. return [];
  689. }
  690. $data = $arr[1];
  691. $data = base64_decode($data);
  692. $data = json_decode($data,true);
  693. if(empty($data)){
  694. return [];
  695. }
  696. $sign = $arr[2];
  697. if(empty($sign)){
  698. return [];
  699. }
  700. return $data;
  701. }
  702. }