需求:将苹果支付的订单记录处理,与本地数据库对账。
涉及到一个问题:请求苹果的账单,返回的是一个压缩文件,解压后才是xls文件。
思路:将请求到的文件流置入一个zip文件,解压这个文件后,将文件内容转为数组处理。
实现代码(写了个示例如下,数据处理也附上):
苹果账单api地址:https://developer.apple.com/documentation/appstoreconnectapi,在此有个需要注意的点:请求的数据所属时区:报告采用太平洋标准时间(PST)。一天包括从 12:00 AM 至 11:59 PM(PST)之间所发生的交易。所以以北京时间发起请求,昨天的数据可能是取不到的。
$dir=dirname(__FILE__);
$url = "http://1.1.1.1/onlinepay/iap/salesreport/download?refersource=ttt&frequency=DAILY&reportDate=2019-08-01&reportSubType=SUMMARY&reportType=SALES&version=1_0";
//苹果账单只能查询到两天前的数据(我猜测是时差原因)
//$report_date = date("Y-m-d",strtotime("-2 days"));
$post_arr = "...此处省略"
$result = req_post($url,$post_arr);
$res = make_bill_file($dir,$result);
if($res){
//数组参数
$arr = array("SKU","Title","Product Type Identifier","Developer Proceeds","End Date","Customer Price");
$data = get_apple_bill_data($dir,$arr);
//$data不为空 继续执行
if(empty($data)){ return false;}
//筛选数据 Product Type Identifier = IA9
$data_a = array();
foreach($data as $k => $v) {
if($v['Product Type Identifier'] == 'IA9'){
$data_a[] = $v;
}else{
continue;
}
}
unset($data);
unlink($dir."/apple_bill");
unlink($dir."/apple_bill.gz");
}
//读取数据
function get_apple_bill_data($dir,$arr){
$path = $dir."/apple_bill";
$file = fopen($path, 'r');
//标题行读取(第一行)
$row = fgets($file);
$row = explode("\t", $row);
$title = array();
foreach($row as $k => $v) {
$title[$k] = str_replace("\n", '', $v);
}
//内容读取
$data = array();
$count = 0;
while(!feof($file)) {
$row = fgets($file);
$row = explode("\t", $row);
if(!$row[0]) continue;//去除第一行
foreach($title as $k => $v) {
if(in_array($v, $arr)){
$data[$count][$v] = str_replace("\n", '', $row[$k]);
}else{
continue;
}
}
$count ++;
}
fclose($file);
return $data;
}
//将压缩文件流转为压缩文件,并解压 $dir:压缩文件保存地址 $result 请求的文件流
function make_bill_file($dir,$result){
$myfile = fopen($dir."/apple_bill.gz", "wb") or die("Unable to open file!");
fwrite($myfile, $result);
$buffer_size = 4096; // read 4kb at a time
$file = gzopen($dir."/apple_bill.gz", 'rb');
$out_file = fopen($dir."/apple_bill", 'wb');
$str='';
while(!gzeof($file)) {
fwrite($out_file, gzread($file, $buffer_size));
}
$res_close = fclose($out_file);
$res_gzclose = gzclose($file);
if($res_close && $res_gzclose){
return true;
}else{
return false;
}
}
function req_post($url, $post_data = '', $timeout = 10){
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
if($post_data != ''){
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, false);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}