【PHP】PHP服務端支付寶支付及回撥
阿新 • • 發佈:2018-12-09
支付寶支付
(由app端自行調起支付寶/微信)
<?php define('IN_ECS', true); /*App支付 PHP服務端*/ /*引入支付寶PHP SDK*/ header("Content-type:text/html;charset=utf-8;"); require_once('../alipay-sdk-PHP/aop/request/AlipayTradeAppPayRequest.php'); require_once('../alipay-sdk-PHP/aop/AopClient.php'); $user_id = isset($_REQUEST['user_id']) ? trim($_REQUEST['user_id']) : 0; $money = isset($_REQUEST['amount']) ? trim($_REQUEST['amount']) : 0; if($user_id == 0 || $money ==0){ $result = array('code' => 1,'data'=>'缺少引數' ); die(json_encode($result)); } $aop = new AopClient; $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do"; $aop->appId = "appid"; $aop->format = "json"; $aop->charset = "utf-8"; $aop->signType = "RSA2"; $aop->rsaPrivateKey = '開發者私鑰'; $aop->alipayrsaPublicKey = '支付寶公鑰'; //例項化具體API對應的request類,類名稱和介面名稱對應,當前呼叫介面名稱:alipay.trade.app.pay $request = new AlipayTradeAppPayRequest(); //SDK已經封裝掉了公共引數,這裡只需要傳入業務引數 $trade_no = chongzhi_sn(); //入庫資訊 require(dirname(__FILE__) . '../../includes/init.php'); include_once(ROOT_PATH .'includes/lib_clips.php'); $user_m = get_user_info($user_id); $dbcontent = array( 'user_id' => $user_id, 'amount' => $money, 'user_name' => $user_m['user_name'], 'payment' => "支付寶", 'cz_sn' => $trade_no, 'add_time' => gmtime() ); //傳參資訊 $bizcontent = array( 'body' =>(string)$trade_no, 'subject' =>'充值', 'total_amount' => $money, 'out_trade_no' => (string)$trade_no, 'product_code' => 'QUICK_MSECURITY_PAY', 'timeout_express'=> '30m' ); $bizcontent = json_encode($bizcontent); $request->setNotifyUrl("支付回撥地址"); $request->setBizContent($bizcontent); //這裡和普通的介面呼叫不同,使用的是sdkExecute $response = $aop->sdkExecute($request); //htmlspecialchars是為了輸出到頁面時防止被瀏覽器將關鍵引數html轉義,實際列印到日誌以及http傳輸不會有這個問題 //echo htmlspecialchars($response);//就是orderString 可以直接給客戶端請求,無需再做處理。 if($response){ if($GLOBALS['db']->autoExecute($ecs->table('user_chongzhi'), $dbcontent, 'INSERT')) { $result = array('code'=>0,'data'=>$response); }else{ $result = array('code'=>1,'data'=>'意外出錯,請聯絡客服。'); } die(json_encode($result)); } function chongzhi_sn() { /* 選擇一個隨機的方案 */ mt_srand((double) microtime() * 1000000); return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT); } ?>
回撥
<?php define('IN_ECS', true); require_once('../alipay-sdk-PHP/aop/request/AlipayTradeAppPayRequest.php'); require_once('../alipay-sdk-PHP/aop/AopClient.php'); $aop = new AopClient; $aop->alipayrsaPublicKey = '支付寶公鑰'; $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2"); $myfile = fopen("testfile.txt", "a"); fwrite($myfile, "\r\n"); fwrite($myfile, json_encode($_POST)); if($_POST['trade_status'] == 'TRADE_SUCCESS' ){ //業務處理 echo 'success'; }else{ echo 'fail'; } fclose($myfile); ?>
所需的私鑰公鑰獲取地址
1.私鑰 (下載rsa簽名驗籤工具)https://docs.open.alipay.com/291/105971/
2.支付寶公鑰
通過上傳私鑰,由支付寶生成公鑰 https://docs.open.alipay.com/291/105972/
3.支付寶聯調日誌排查 https://openmonitor.alipay.com/acceptance/cloudparse.htm