Payios.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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. if (!$receipt_data || !$original_transaction_id || !$transaction_id) {
  118. $this->error('缺少参数');
  119. }
  120. filePut("\r\n\r\n".'新请求VIP订阅');
  121. $prefix = 'iosVIP订阅登录user_id:'.$this->auth->id.',传入original_transaction_id:'.$original_transaction_id.',传入transaction_id:'.$transaction_id.'。';
  122. filePut($prefix.'参数apple_receipt:'.$receipt_data);
  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. if($only_trans['product_id'] != $order_info['bundle_id'] || $order_info['user_id'] != $this->auth->id){
  168. $pay_order_map = [
  169. 'user_id' => $this->auth->id,
  170. 'bundle_id' => $only_trans['product_id'],
  171. 'order_status' => 0,
  172. 'table_name' => 'vip_recharge',
  173. ];
  174. $pay_order = Db::name('pay_order')->where($pay_order_map)->order('id desc')->lock(true)->find();
  175. if(!$pay_order){
  176. Db::rollback();
  177. filePut($prefix.'未找到匹配的交易,新订单找不到');
  178. $this->error('未找到匹配的新订单');
  179. }
  180. // 修改订单状态
  181. $update_order = [
  182. 'notifytime'=>time(),
  183. 'order_status'=>1,
  184. 'original_transaction_id' => $only_trans['original_transaction_id'],
  185. 'in_app_one' => json_encode($only_trans),
  186. ];
  187. $ros = Db::name('pay_order')->where(['id' => $pay_order['id']])->update($update_order);
  188. if($ros === false) {
  189. filePut($prefix.'修改订单状态失败');
  190. Db::rollback();
  191. $this->error('充值失败');
  192. }
  193. $args = json_decode($pay_order['args'],true);
  194. //修改order_info
  195. $order_info['order_id'] = $pay_order['id'];
  196. $order_info['user_id'] = $pay_order['user_id'];
  197. $order_info['bundle_id'] = $pay_order['bundle_id'];
  198. $order_info['days'] = $args['days'];
  199. $order_info['original_transaction_id'] = $only_trans['original_transaction_id'];//多余
  200. }
  201. //验证时间,不得小于最新的一条预定信息
  202. if($order_info_user_id == $this->auth->id){
  203. if($only_trans['purchase_date_ms'] <= $order_info['purchase_date_ms'] || $only_trans['expires_date_ms'] <= $order_info['expires_date_ms']){
  204. Db::rollback();
  205. filePut($prefix.'时间对不上,返回成功,finish掉');
  206. $this->success(1);
  207. }
  208. }
  209. //逻辑开始
  210. //先充值
  211. $user_info = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->lock(true)->find();
  212. if($user_info['vip_endtime'] < time()){
  213. //过期了
  214. $vip_endtime = time() + (intval($order_info['days']) * 86400);
  215. }else{
  216. //追加vip
  217. $vip_endtime = $user_info['vip_endtime'] + (intval($order_info['days']) * 86400);
  218. }
  219. $update_data = [
  220. 'vip_endtime'=>$vip_endtime,
  221. ];
  222. $result = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->update($update_data);
  223. if($result === false)
  224. {
  225. filePut($prefix.'逻辑续费vip时间失败');
  226. Db::rollback();
  227. $this->error('充值失败');
  228. }
  229. //逻辑结束
  230. //添加新的一个task
  231. $task_data = $order_info;
  232. unset($task_data['id']);
  233. $task_data['createtime'] = time();
  234. $task_data['apple_receipt'] = $receipt_data;
  235. $task_data['in_app_one'] = json_encode($only_trans);
  236. $task_data['transaction_id'] = $transaction_id;
  237. $task_data['times'] = $order_info['times'] + 1;
  238. $task_data['original_purchase_date_ms'] = $only_trans['original_purchase_date_ms'];
  239. $task_data['purchase_date_ms'] = $only_trans['purchase_date_ms'];
  240. $task_data['expires_date_ms'] = $only_trans['expires_date_ms'];
  241. //换了产品了,或者订单的user_id被改过了
  242. if($only_trans['product_id'] != $order_info_bundle_id || $order_info['user_id'] != $order_info_user_id){
  243. $task_data['times'] = 1;//回归1
  244. }
  245. $task_id = Db::name('user_vipxufei_task')->insertGetId($task_data);
  246. if(!$task_id)
  247. {
  248. filePut($prefix.'用户添加vipxufei_task失败');
  249. Db::rollback();
  250. $this->error('充值失败');
  251. }
  252. Db::commit();
  253. filePut($prefix.'充值成功');
  254. $this->success('充值成功');
  255. //逻辑结束
  256. }
  257. //金币+vip,苹果内购支付回调,app请求的接口
  258. public function gold_notify_iosnew(){
  259. $original_transaction_id = input('original_transaction_id','','trim');
  260. if(!empty($original_transaction_id)){
  261. //订阅信息
  262. $this->expires();
  263. }
  264. //苹果内购的验证收据
  265. $receipt_data = input('apple_receipt', '', 'trim');
  266. $out_trade_no = input('out_trade_no', '', 'trim');
  267. $transaction_id = input('transaction_id', '', 'trim');
  268. if (!$receipt_data || !$out_trade_no || !$transaction_id) {
  269. $this->error('缺少参数');
  270. }
  271. filePut("\r\n\r\n".'新请求');
  272. $prefix = 'ios充值,登录user_id:'.$this->auth->id.',out_trade_no:'.$out_trade_no.',传入transaction_id:'.$transaction_id.'。';
  273. filePut($prefix.'参数apple_receipt:'.$receipt_data);
  274. Db::startTrans();
  275. // 查找订单
  276. $order_map = [
  277. // 'user_id' => $this->auth->id,
  278. 'out_trade_no' => $out_trade_no,
  279. ];
  280. $order_info = Db::name('pay_order')->where($order_map)->lock(true)->find();
  281. if (!$order_info) {
  282. Db::rollback();
  283. filePut($prefix.'不存在的订单');
  284. $this->error('不存在的订单');
  285. }
  286. if ($order_info['order_status'] == 1) {
  287. Db::rollback();
  288. filePut($prefix.'充值早已完成');
  289. $this->success('充值已完成');
  290. }
  291. // 验证支付状态
  292. $result = $this->validate_apple_pay($receipt_data);
  293. if (!$result['status']) {// 验证不通过
  294. Db::rollback();
  295. filePut($prefix.'验证'.$result['message']);
  296. $this->error($result['message']);
  297. }
  298. $in_app = $result['data']['receipt']['in_app'];
  299. $only_trans = [];
  300. foreach($in_app as $key => $trans){
  301. //非订阅信息,原始信息
  302. // $trans['transaction_id'] == $transaction_id 这个不重要,重要的是后面2个。应该也重要,保证这次处理的是初始交易
  303. if($trans['transaction_id'] == $transaction_id && $transaction_id == $trans['original_transaction_id'] && $trans['product_id'] == $order_info['bundle_id']){
  304. $only_trans = $trans;
  305. break;
  306. }
  307. }
  308. if(empty($only_trans)){
  309. Db::rollback();
  310. filePut($prefix.'未找到匹配的交易,产品id'.$order_info['bundle_id'].',原始交易id'.$transaction_id);
  311. $this->error('未找到匹配的交易,产品id'.$order_info['bundle_id'].',原始交易id'.$transaction_id);
  312. }
  313. //逻辑开始
  314. $args = json_decode($order_info['args'],true);
  315. //先充值
  316. if($order_info['table_name'] == 'gold_recharge'){
  317. $result = model('Wallet')->lockChangeAccountRemain($order_info['user_id'],'gold',$args['gold'],10, '金币充值','pay_order',$order_info['id']);
  318. if($result['status']===false)
  319. {
  320. filePut($prefix.'逻辑添加金币失败');
  321. Db::rollback();
  322. $this->error('充值失败');
  323. }
  324. }
  325. //先充值
  326. if($order_info['table_name'] == 'vip_recharge'){
  327. $user_info = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->lock(true)->find();
  328. if($user_info['vip_endtime'] < time()){
  329. //过期了
  330. $vip_endtime = time() + (intval($args['days']) * 86400);
  331. }else{
  332. //追加vip
  333. $vip_endtime = $user_info['vip_endtime'] + (intval($args['days']) * 86400);
  334. }
  335. $update_data = [
  336. 'vip_endtime'=>$vip_endtime,
  337. ];
  338. $result = Db::name('user_wallet')->where('user_id',$order_info['user_id'])->update($update_data);
  339. if($result === false)
  340. {
  341. filePut($prefix.'逻辑续费vip时间失败');
  342. Db::rollback();
  343. $this->error('充值失败');
  344. }
  345. //订阅vip需要多加的逻辑
  346. if($order_info['is_lianxu'] == 1){
  347. $task_data = [
  348. 'order_id' => $order_info['id'],
  349. 'user_id' => $order_info['user_id'],
  350. 'bundle_id' => $order_info['bundle_id'],
  351. 'days' => $args['days'],
  352. 'createtime' => time(),
  353. 'apple_receipt' => $receipt_data,
  354. 'in_app_one' => json_encode($only_trans),
  355. 'original_transaction_id' => $only_trans['original_transaction_id'],
  356. 'transaction_id' => $only_trans['transaction_id'],
  357. 'status' => 1,
  358. 'times' => 1,
  359. //'notification_type' => 'INITIAL_BUY'.',首次订阅',
  360. 'original_purchase_date_ms' => $only_trans['original_purchase_date_ms'],
  361. 'purchase_date_ms' => $only_trans['purchase_date_ms'],
  362. 'expires_date_ms' => $only_trans['purchase_date_ms'], //第一次借用购买时间戳
  363. ];
  364. $task_id = Db::name('user_vipxufei_task')->insertGetId($task_data);
  365. if(!$task_id)
  366. {
  367. filePut($prefix.'用户添加vipxufei_task失败');
  368. Db::rollback();
  369. $this->error('充值失败');
  370. }
  371. }
  372. }
  373. // 修改订单状态
  374. $update_order = [
  375. 'notifytime'=>time(),
  376. 'order_status'=>1,
  377. 'original_transaction_id' => $only_trans['original_transaction_id'],//理论上与 transaction_id 相等
  378. 'in_app_one' => json_encode($only_trans),
  379. ];
  380. $ros = Db::name('pay_order')->where(['id' => $order_info['id']])->update($update_order);
  381. if($ros === false) {
  382. filePut($prefix.'修改订单状态失败');
  383. Db::rollback();
  384. $this->error('充值失败');
  385. }
  386. Db::commit();
  387. filePut($prefix.'充值成功');
  388. $this->success('充值成功');
  389. //逻辑结束
  390. }
  391. ////////////////////////////////////
  392. /**
  393. * ios 事件通知
  394. * @return bool
  395. */
  396. public function auto_renewal_vip_notify()
  397. {
  398. $this->notify_log_start('ios');
  399. try {
  400. $raw = file_get_contents("php://input");
  401. filePut("\r\n\r\n".'入口:'.$raw);
  402. $raw = json_decode($raw,true);
  403. $token = isset($raw['signedPayload']) ? $raw['signedPayload'] : '';
  404. $data = $this->verifyAppleToken($token);
  405. dump($data);
  406. if (empty($data)) {
  407. //timbao add
  408. //记录苹果通知逻辑中的bug
  409. exit;
  410. }
  411. $transaction_info = $this->verifyAppleToken($data['data']['signedTransactionInfo']);
  412. dump($transaction_info);
  413. $rs = '默认';
  414. switch ($data['notificationType']) {
  415. case 'DID_RENEW': // 续订
  416. $rs = Transaction::autoRenew($transaction_info);
  417. break;
  418. case 'REFUND': // 退款
  419. $rs = Transaction::refund($transaction_info);
  420. break;
  421. case 'DID_CHANGE_RENEWAL_STATUS': // 连续续订状态 变更
  422. $rs = Transaction::changeRenewStatus($transaction_info, $data['subtype']);
  423. break;
  424. case 'EXPIRED': // 过期通知
  425. $rs = Transaction::updateExpiredTrans($transaction_info);
  426. break;
  427. case 'SUBSCRIBED': // 订阅通知
  428. $rs = Transaction::updateSubscribed($transaction_info, $data['subtype']);
  429. break;
  430. case 'DID_FAIL_TO_RENEW': // 续订失败
  431. $rs = Transaction::updateRenewFailTrans($transaction_info);
  432. break;
  433. case 'DID_CHANGE_RENEWAL_PREF': //升级 降级
  434. if ($data['subtype'] == 'UPGRADE') {
  435. $rs = Transaction::autoRenew($transaction_info, true);
  436. }
  437. break;
  438. }
  439. dump($rs);
  440. exit;
  441. }catch (Exception $e) {
  442. echo $e->getMessage();
  443. exit;
  444. }
  445. }
  446. ////////////////////////////////私有方法///////////////////////////////////////////////////////////////
  447. //异步日志
  448. private function notify_log_start($paytype = 'ios'){
  449. //记录支付回调数据
  450. ignore_user_abort(); // run script in background
  451. set_time_limit(30);
  452. // 日志文件 start
  453. $log_base_dir = '../paylog/'.$paytype.'/';
  454. if (!is_dir($log_base_dir))
  455. {
  456. mkdir($log_base_dir, 0770, true);
  457. @chmod($log_base_dir, 0770);
  458. }
  459. $notify_file = $log_base_dir.'notify.txt';
  460. if(!file_exists($notify_file)) {
  461. @touch($notify_file);
  462. @chmod($notify_file, 0770);
  463. }
  464. if(filesize($notify_file)>5242880)//大于5M自动切换
  465. {
  466. rename($notify_file, $log_base_dir.'notify_'.date('Y_m_d_H_i_s').'.txt');
  467. }
  468. if(!file_exists($notify_file)) {
  469. @touch($notify_file);
  470. @chmod($notify_file, 0770);
  471. }
  472. // 日志文件 end
  473. //开始写入
  474. $_REQUEST = isset($_REQUEST) ? $_REQUEST : array();
  475. if($_REQUEST && $paytype == 'alipay') {
  476. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收request]".json_encode($_REQUEST), FILE_APPEND);
  477. } else {
  478. $xml = file_get_contents("php://input");
  479. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流原始数据] \n".$xml, FILE_APPEND);
  480. /*$xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  481. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流] ".json_encode($xmlObj), FILE_APPEND);*/
  482. }
  483. ini_set('display_errors','On');
  484. return $notify_file;
  485. }
  486. public function test(){
  487. $a = input('apple_receipt');
  488. $b = $this->validate_apple_pay($a);
  489. echo json_encode($b);
  490. }
  491. /**
  492. * 验证AppStore内付
  493. * @param string $receipt_data 付款后凭证
  494. * @return array 验证是否成功
  495. * https://juejin.cn/post/7049626884765646884 报错代码
  496. */
  497. function validate_apple_pay($receipt_data = '') {
  498. // 验证参数
  499. if (strlen($receipt_data) < 20) {
  500. $result = array(
  501. 'status' => false,
  502. 'message' => '非法参数'
  503. );
  504. return $result;
  505. }
  506. // 请求验证
  507. $html = $this->curl($receipt_data);
  508. $data = json_decode($html, true);
  509. $data['sandbox'] = '0';
  510. // p($data);die;
  511. if ($data['status'] == '21002') {
  512. $result = array(
  513. 'status' => false,
  514. 'message' => 'status:21002'
  515. );
  516. return $result;
  517. }
  518. // 如果是沙盒数据 则验证沙盒模式 21008;正式数据 21007
  519. if ($data['status'] == '21007') {
  520. // 请求验证
  521. $html = $this->curl($receipt_data, 1);
  522. $data = json_decode($html, true);
  523. $data['sandbox'] = '1';
  524. }
  525. if (isset($_GET['debug'])) {
  526. exit(json_encode($data));
  527. }
  528. if ($data['receipt']['bundle_id'] != 'com.huxiu.tken') {
  529. $result = array(
  530. 'status' => false,
  531. 'message' => '非法请求',
  532. 'data' => $data
  533. );
  534. return $result;
  535. }
  536. // 判断是否购买成功
  537. if (intval($data['status']) === 0) {
  538. $result = array(
  539. 'status' => true,
  540. 'message' => '购买成功',
  541. 'data' => $data
  542. );
  543. } else {
  544. $result = array(
  545. 'status' => false,
  546. 'message' => '购买失败 status:' . $data['status']
  547. );
  548. }
  549. // dump($result);
  550. return $result;
  551. }
  552. /**
  553. * 0 票据校验成功
  554. * 21000 App Store不能读取你提供的JSON对象25
  555. * 21002 receipt-data域的数据有问题
  556. * 21003 receipt无法通过验证
  557. * 21004 提供的shared secret不匹配你账号中的shared secret
  558. * 21005 receipt服务器当前不可用
  559. * 21006 receipt合法,但是订阅已过期。服务器接收到这个状态码时,receipt数据仍然会解码并一起发送
  560. * 21007 receipt是Sandbox receipt,但却发送至生产系统的验证服务
  561. * 21008 receipt是生产receipt,但却发送至Sandbox环境的验证服务
  562. */
  563. //苹果也是建议这个校验逻辑由服务端完成。服务器需要先去请求正式环境。如果receipt是正式环境的,那么这个时候苹果会返回(21007)告诉我们这个是沙盒的receipt,那么服务器再去请求sandbox环境。
  564. function curl($receipt_data,$sandbox = 0) {
  565. //小票信息
  566. $POSTFIELDS = [
  567. 'receipt-data' => $receipt_data,
  568. 'password' => '09ef214173a944808ac648b15fa02167'
  569. ];
  570. $POSTFIELDS = json_encode($POSTFIELDS, 320);
  571. //正式购买地址 沙盒购买地址
  572. $url_buy = "https://buy.itunes.apple.com/verifyReceipt";
  573. $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
  574. //默认后台控制
  575. if (config('site.ios_pay_sandbox') > 0 ) {
  576. $url = $url_buy;
  577. } else {
  578. $url = $url_sandbox;
  579. }
  580. //强制沙盒
  581. if($sandbox == 1){
  582. $url = $url_sandbox;
  583. }
  584. $ch = curl_init($url);
  585. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  586. curl_setopt($ch, CURLOPT_POST, true);
  587. curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
  588. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //这两行一定要加,不加会报SSL 错误
  589. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  590. $response = curl_exec($ch);
  591. $errno = curl_errno($ch);
  592. curl_close($ch);
  593. if ($errno != 0) {
  594. return $errno;
  595. } else {
  596. return $response;
  597. }
  598. }
  599. /**
  600. * 苹果token解密
  601. *
  602. * @param $token
  603. * @return array|bool|mixed|string
  604. */
  605. private function verifyAppleToken($token)
  606. {
  607. $arr = explode('.',$token);
  608. if(count($arr) != 3){
  609. return [];
  610. }
  611. $header = $arr[0];
  612. $header = base64_decode($header);
  613. $header = json_decode($header,true);
  614. if(empty($header)){
  615. return [];
  616. }
  617. if($header['alg'] != 'ES256'){
  618. return [];
  619. }
  620. $data = $arr[1];
  621. $data = base64_decode($data);
  622. $data = json_decode($data,true);
  623. if(empty($data)){
  624. return [];
  625. }
  626. $sign = $arr[2];
  627. if(empty($sign)){
  628. return [];
  629. }
  630. return $data;
  631. }
  632. }