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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
