当前位置: 首页 > 后端技术 > PHP

PHP验证IOS原生支付是否成功(完整代码)

时间:2023-03-29 23:10:31 PHP

前言IOS原生支付后,需要调用服务端接口进行验证,查看是否真正支付成功!$code,'message'=>$msg,'data'=>$data,];返回json_encode($result,true);}/**code400*@paramstring$msg*@returnstring*/privatefunctioncode400($msg='parametererror!'){return$this->jsonRet(400,$msg);}/**code200*@paramstring$msg*@returnstring*/privatefunctioncode200($msg='操作成功!'){return$this->jsonRet(200,$msg);}/**log*@param$info*/privatefunctionlog($info){//日志信息}/**iosapple支付验证*@returnstring*/publicfunctionapple(){//苹果支付认证证书(base64后的数据)$receipt=$_POST('receipt');if(empty($receipt)){return$this->code400();}//环境配置if($this->sandbox){$endpoint='https://sandbox.itunes.apple.com/verifyReceipt';//沙盒地址}else{$endpoint='https://buy.itunes.apple.com/verifyReceipt';//真实操作地址}//数据组装//$receipt='MIITg45+CLLy37vkb0ADflcoqEY/3mH1Rc9rC4q3/O7eG/sT7MntcVH1gc8GiEuZZ1T0Qormu2TFRrg866YxxI0LVfxencode==';(array('receipt-data'=>$receipt),JSON_UNESCAPED_SLASHES);//记录$this->log($postData);//curl操作$ch=curl_init($endpoint);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POST,true);curl_setopt($ch,CURLOPT_POSTFIELDS,$postData);curl_setoptt($ch,CURLOPT_SSL_VERIFYPEER,0);//这两行必须加上,否则会报SSL错误curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);$response=curl_exec($ch);$errno=curl_errno($ch);curl_close($ch);if($errno!=0){return$this->code400('curl请求错误!');}else{$data=json_decode($response,true);if(!is_array($data)){return$this->code400('dataerror!');}//判断购买是否成功if(!isset($data['status'])||$data['status']!=0){return$this->code400('iOS支付数据无效!');}//无效的bundle_idif(!in_array($data['receipt']['bundle_id'],['ios应用的bundle_id与付费的app_id相似'])){return$this->code400('Invalidbundle_id:'.$data['receipt']['bundle_id']);}//购买多个商品时//in_app是多个(坑)//ios一次可能会返回多个支付,可能上次成功后没有及时返回,这次成功后会返回最后一个or最后一次成功返回if(!empty($inAppData=$data['receipt']['in_app'])){//商品配置,对应ios应用的product_ideg:yw_6支付6元$productB=['yw_6'];//多条信息foreach($inAppDataas$product){//订单重复校验$appleData=$product->check('自有业务去重');如果($appleData){继续;//return$this->code400('重复交易号,请勿重复验证!id:'.$transactionId);}if(isset($productB[$product['product_id']])){$productId=$product['product_id'];$money=$productB[$productId];if(!$money){return$this->code400('没有找到对应商品的金额,ID:'.$product['product_id']);}//业务逻辑处理//添加余额,记录资金日志等操作$product['add_balance']=true;}//环境$product['is_sandbox']=$this->sandbox;//数据$product['receipt_data']=$receipt;//时间$product['time']=date('YmdHis');//返回码$product['err_no']='200';//save$productsavedata}}//根据自己需要返回数据$returnData=[];返回$this->code200($returnData);}}}