Payios.php 27 KB

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