Payios.php 26 KB

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