Payios.php 26 KB

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