Summarize and share how PHP handles IOS automatic renewal!
This article will introduce to you how the PHP server handles IOS automatic renewal. I summarized it myself. I hope it will be helpful to my friends~
The app made by the company needs to do IAP subscription payment. You can do it yourself. To sum up, I hope it is helpful to my friends and I am very happy. If the code is not well written, please don’t criticize me. [Recommended: PHP Video Tutorial]
First let me talk about my business logic:
First picture
Details below Let’s talk about what to do as a server and paste the corresponding code:
Step one:
Generate an order through the recept (ticket) passed from the client [Note that you need to verify whether the order already exists], and the order generation returns relevant information to the client;
public function pay() { $uid = $this->request->header('uid'); $receipt_data = $this->request->post('receipt'); if (!$uid || !$receipt_data) return $this->rep(400); $info = $this->getReceiptData($receipt_data, $this->isSandbox);//去苹果进行验证,防止收到的是伪造的数据 Log::info(['uid'=>$uid,'receipt'=>$receipt_data,'iap_info'=>$info]); if (is_array($info) && $info['status'] == 0) {//没有错误就进行生成订单的业务逻辑的处理 } elseif (is_array($info) && $info['status'] == 21007) { $new_info = $this->getReceiptData($receipt_data, true);//接着去苹果官网进行二次验证(沙盒) // 进行生成订单的业务逻辑的处理 } }
private function getReceiptData($receipt, $isSandbox = false) { if ($isSandbox) { $endpoint = 'https://sandbox.itunes.apple.com/verifyReceipt';//沙箱地址 } else { $endpoint = 'https://buy.itunes.apple.com/verifyReceipt';//真实运营地址 } $postData = json_encode(['receipt-data' => $receipt, 'password'=>'abde7d535c']); $ch = curl_init($endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $response = curl_exec($ch); $errno = curl_errno($ch); curl_close($ch); if ($errno != 0) {//curl请求有错误 $order['status'] = 408; } else { $data = json_decode($response, true); if (isset($data['status'])) { //返回产品的信息 $order = isset($data['receipt']) ? $data['receipt'] : []; $order['status'] = $data['status']; } else { $order['status'] = 30000; } } return $order; }
Step 2:
Automatic subscription renewal function (automatic subscription renewal can only be performed on the basis of payment) For the renewal function, the interface here does not need to be called up by the client. This is automatically called back by Apple. You need to fill in the callback link on Apple’s official website, as shown below:)
Next Code with automatic callback:
/* * 自动续费订阅回调 * Doc: https://developer.apple.com/documentation/appstoreservernotifications/notification_type */ public function renew(){ $resp_str = $this->request->post(); Log::info(['resp_str'=>$resp_str]); if(!empty($resp_str)) { // $data = json_decode($resp_str,true); // $data = $resp_str['unified_receipt']; //有时候苹果那边会传空数据调用 // notification_type 几种状态描述 // INITIAL_BUY 初次购买订阅。latest_receipt通过在App Store中验证,可以随时将您的服务器存储在服务器上以验证用户的订阅状态。 // CANCEL Apple客户支持取消了订阅。检查Cancellation Date以了解订阅取消的日期和时间。 // RENEWAL 已过期订阅的自动续订成功。检查Subscription Expiration Date以确定下一个续订日期和时间。 // INTERACTIVE_RENEWAL 客户通过使用用App Store中的App Store以交互方式续订订阅。服务立即可用。 // DID_CHANGE_RENEWAL_PREF 客户更改了在下次续订时生效的计划。当前的有效计划不受影响。 $notification_type = $resp_str['notification_type'];//通知类型 $password = $resp_str['password']; // 共享秘钥 if ($password == "abde7d5353") { $receipt = isset($data['latest_receipt_info']) ? $data['latest_receipt_info'] : $data['latest_expired_receipt_info']; //latest_expired_receipt_info 好像只有更改续订状态才有 //找出来最近的那一组信息 $receipt = self::arraySort($receipt, 'purchase_date', 'desc'); $original_transaction_id = $receipt['original_transaction_id']; // //原始交易ID $transaction_id = $receipt['transaction_id']; // //交易的标识 $purchaseDate = str_replace(' America/Los_Angeles','',$receipt['purchase_date_pst']); $orderinfo = Order::field('uid,original_transaction_id,money,order_no,pay_time')->where(['original_transaction_id' => $original_transaction_id])->find(); $user_info = User::field('app_uid,device_id,unionid')->get($orderinfo['uid']); if ($notification_type == 'CANCEL') { //取消订阅,做个记录 IpaLog::addLog($orderinfo['uid'], $orderinfo['order_no'], $receipt, $resp_str); } else { if ($notification_type == "INTERACTIVE_RENEWAL" || $notification_type == "RENEWAL" || $notification_type == 'INITIAL_BUY') { // $transTime = $this->toTimeZone($receipt['purchase_date']); IapRenew::addRenew($orderinfo['uid'], $receipt, $data['latest_receipt'],1,$notification_type,$user_info['app_uid'],$purchaseDate); IpaLog::addLog($orderinfo['uid'], $orderinfo['order_no'], $receipt, $resp_str); } else { IapRenew::addRenew($orderinfo['uid'], $receipt, $data['latest_receipt'],0,$notification_type,$user_info['app_uid'],$purchaseDate); IpaLog::addLog($orderinfo['uid'], $orderinfo['order_no'], $receipt, $resp_str); } } } else { Log::info('通知传递的密码不正确--password:'.$password); } } } private function toTimeZone($src, $from_tz = 'Etc/GMT', $to_tz = 'Asia/Shanghai', $fm = 'Y-m-d H:i:s') { $datetime = new \DateTime($src, new \DateTimeZone($from_tz)); $datetime->setTimezone(new \DateTimeZone($to_tz)); return $datetime->format($fm); } private static function arraySort($arr, $key, $type='asc') { $keyArr = []; // 初始化存放数组将要排序的字段值 foreach ($arr as $k=>$v){ $keyArr[$k] = $v[$key]; // 循环获取到将要排序的字段值 } if($type == 'asc'){ asort($keyArr); // 排序方式,将一维数组进行相应排序 }else{ arsort($keyArr); } foreach ($keyArr as $k=>$v){ $newArray[$k] = $arr[$k]; // 循环将配置的值放入响应的下标下 } $newArray = array_merge($newArray); // 重置下标 return $newArray[0]; // 数据返回 }
The above is the detailed content of Summarize and share how PHP handles IOS automatic renewal!. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
