這是我本身摸索再結合網上搜索的一大堆內容搞出來的,官方的文件對於新手來講很難理解,什麼文件放什麼位置,該怎麼引用,都要一一嘗試,我這就直接列出來了,照樣放就是了.一樣適用於tp5,我這個也是tp5的php
1. 先把PayModel 放在app下你作項目的model裏,須要修改內容: 修改的內容我會標紅html
<?php /* * author : * link : */ namespace app\product_mall\model; use think\Validate; use think\Log; use think\Db; class PayModel extends \think\Model { public static $alipay_config = [ 'partner' => '2088821XXXXXXXXX',//支付寶partner,2088開頭數字 'seller_id' => '208882160XXXXXXX',//支付寶partner,2088開頭數字 上面這兩處都是一樣的內容,在支付寶開發平臺->帳戶中心->老版wap支付密鑰->合做夥伴身份(PID) 'key' => 'yb4uaif17i9nm92kcq89rcnvf7fq1yms',//支付寶密鑰 老版wap支付密鑰->安全校驗碼(key)->md5密匙 'sign_type' => 'MD5', 'input_charset' => 'utf-8', 'cacert' => '', 'transport' => 'http', 'payment_type' => '1', 'service' => 'alipay.wap.create.direct.pay.by.user',//這個是wap支付,就是手機網站支付打開支付寶 //create_direct_pay_by_user 這個是電腦網站支付,掃碼或者帳號登陸支付,不能同時存在
'anti_phishing_key' => '', 'exter_invoke_ip' => '', ];
public function alipay($data=[])
{
$config = self::$alipay_config;
vendor('alipay.alipay');
$parameter = [
"service" => $config['service'],
"partner" => $config['partner'],
"seller_id" => $config['seller_id'],
"payment_type" => $config['payment_type'],
"notify_url" => $data['notify_url'],
"return_url" => $data['return_url'],
"anti_phishing_key" => $config['anti_phishing_key'],
"exter_invoke_ip" => $config['exter_invoke_ip'],
"out_trade_no" => $data['out_trade_no'],
"subject" => $data['subject'],
"total_fee" => $data['total_fee'],
"body" => $data['body'],
"_input_charset" => $config['input_charset']
];
$alipaySubmit = new \AlipaySubmit($config);
$html_text = $alipaySubmit->buildRequestForm($parameter, 'get', '正在跳轉到支付頁面,請稍後..................');
echo $html_text;
}
public function notify_alipay()
{
$config = self::$alipay_config;
vendor('alipay.alipay');
$alipayNotify = new \AlipayNotify($config);
if($result = $alipayNotify->verifyNotify()){
if(input('trade_status') == 'TRADE_FINISHED' || input('trade_status') == 'TRADE_SUCCESS') {
// 處理支付成功後的邏輯業務
$data['content'] = serialize($_POST);
$data['create_time'] = time();
$res = Db::name('temp_test')->insert($data);
Log::init([
'type' => 'File',
'path' => LOG_PATH.'../paylog1/'
]);
Log::write($result,'log');
return 'success';
}
Log::init([
'type' => 'File',
'path' => LOG_PATH.'../paylog1/'
]);
Log::write('error','log');
return 'fail1';
}
return 'fail2';
}
} ?>
這個文件的存放位置 product_mall就是個人項目node
2.alipay.php文件,內容:json
<?php function createLinkstring($para) { $arg = ""; while (list ($key, $val) = each ($para)) { $arg.=$key."=".$val."&"; } $arg = substr($arg,0,count($arg)-2); if(get_magic_quotes_gpc()){$arg = stripslashes($arg);} return $arg; } function createLinkstringUrlencode($para) { $arg = ""; while (list ($key, $val) = each ($para)) { $arg.=$key."=".urlencode($val)."&"; } $arg = substr($arg,0,count($arg)-2); if(get_magic_quotes_gpc()){$arg = stripslashes($arg);} return $arg; } function paraFilter($para) { $para_filter = array(); while (list ($key, $val) = each ($para)) { if($key == "sign" || $key == "sign_type" || $val == "")continue; else $para_filter[$key] = $para[$key]; } return $para_filter; } function logResult($word='') { $fp = fopen("log.txt","a"); flock($fp, LOCK_EX) ; fwrite($fp,"執行日期:".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n"); flock($fp, LOCK_UN); fclose($fp); } function getHttpResponseGET($url,$cacert_url) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_HEADER, 0 ); // 過濾HTTP頭 curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 顯示輸出結果 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL證書認證 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//嚴格認證 curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//證書地址 $responseText = curl_exec($curl); curl_close($curl); return $responseText; } function charsetEncode($input,$_output_charset ,$_input_charset) { $output = ""; if(!isset($_output_charset) )$_output_charset = $_input_charset; if($_input_charset == $_output_charset || $input ==null ) { $output = $input; } elseif (function_exists("mb_convert_encoding")) { $output = mb_convert_encoding($input,$_output_charset,$_input_charset); } elseif(function_exists("iconv")) { $output = iconv($_input_charset,$_output_charset,$input); } else die("sorry, you have no libs support for charset change."); return $output; } function charsetDecode($input,$_input_charset ,$_output_charset) { $output = ""; if(!isset($_input_charset) )$_input_charset = $_input_charset ; if($_input_charset == $_output_charset || $input ==null ) { $output = $input; } elseif (function_exists("mb_convert_encoding")) { $output = mb_convert_encoding($input,$_output_charset,$_input_charset); } elseif(function_exists("iconv")) { $output = iconv($_input_charset,$_output_charset,$input); } else die("sorry, you have no libs support for charset changes."); return $output; } class AlipaySubmit { var $alipay_config; var $alipay_gateway_new = 'https://mapi.alipay.com/gateway.do?'; function __construct($alipay_config){ $this->alipay_config = $alipay_config; } function AlipaySubmit($alipay_config) { $this->__construct($alipay_config); } function buildRequestMysign($para_sort) { $prestr = createLinkstring($para_sort); $mysign = ""; switch (strtoupper(trim($this->alipay_config['sign_type']))) { case "MD5" : $mysign = md5($prestr.$this->alipay_config['key']); break; default : $mysign = ""; } return $mysign; } function buildRequestPara($para_temp) { $para_filter = paraFilter($para_temp); ksort($para_filter); reset($para_filter); $para_sort = $para_filter; $mysign = $this->buildRequestMysign($para_sort); $para_sort['sign'] = $mysign; $para_sort['sign_type'] = strtoupper(trim($this->alipay_config['sign_type'])); return $para_sort; } function buildRequestParaToString($para_temp) { $para = $this->buildRequestPara($para_temp); $request_data = createLinkstringUrlencode($para); return $request_data; } function buildRequestForm($para_temp, $method, $button_name) { $para = $this->buildRequestPara($para_temp); $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->alipay_gateway_new."_input_charset=".trim(strtolower($this->alipay_config['input_charset']))."' method='".$method."'>"; while (list ($key, $val) = each ($para)) { $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>"; } $sHtml .= "<input type='submit' value='".$button_name."' style='display:none;'></form>"; $sHtml .= "<script>document.forms['alipaysubmit'].submit();</script>"; return $sHtml; } function query_timestamp() { $url = $this->alipay_gateway_new."service=query_timestamp&partner=".trim(strtolower($this->alipay_config['partner']))."&_input_charset=".trim(strtolower($this->alipay_config['input_charset'])); $encrypt_key = ""; $doc = new DOMDocument(); $doc->load($url); $itemEncrypt_key = $doc->getElementsByTagName( "encrypt_key" ); $encrypt_key = $itemEncrypt_key->item(0)->nodeValue; return $encrypt_key; } } class AlipayNotify { var $https_verify_url = 'https://mapi.alipay.com/gateway.do?service=notify_verify&'; var $http_verify_url = 'http://notify.alipay.com/trade/notify_query.do?'; var $alipay_config; function __construct($alipay_config){ $this->alipay_config = $alipay_config; } function AlipayNotify($alipay_config) { $this->__construct($alipay_config); } function verifyNotify(){ if(empty($_POST)) {//判斷POST來的數組是否爲空 return false; }else{ $isSign = $this->getSignVeryfy($_POST, $_POST["sign"]); $responseTxt = 'false'; if (! empty($_POST["notify_id"])) {$responseTxt = $this->getResponse($_POST["notify_id"]);} if (preg_match("/true$/i",$responseTxt) && $isSign) { return true; } else { return false; } } } function verifyReturn(){ if(empty($_GET)) {//判斷GET來的數組是否爲空 return false; }else{ $isSign = $this->getSignVeryfy($_GET, $_GET["sign"]); $responseTxt = 'false'; if (! empty($_GET["notify_id"])) {$responseTxt = $this->getResponse($_GET["notify_id"]);} if (preg_match("/true$/i",$responseTxt) && $isSign) { return true; } else { return false; } } } function getSignVeryfy($para_temp, $sign) { $para_filter = paraFilter($para_temp); ksort($para_filter); reset($para_filter); $para_sort = $para_filter; $prestr = createLinkstring($para_sort); $isSgin = false; switch (strtoupper(trim($this->alipay_config['sign_type']))) { case "MD5" : $isSgin = md5($prestr.$this->alipay_config['key']) == $sign ? true : false; break; default : $isSgin = false; } return $isSgin; } function getResponse($notify_id) { $transport = strtolower(trim($this->alipay_config['transport'])); $partner = trim($this->alipay_config['partner']); $veryfy_url = ''; if($transport == 'https') { $veryfy_url = $this->https_verify_url; }else{ $veryfy_url = $this->http_verify_url; } $veryfy_url = $veryfy_url."partner=" . $partner . "¬ify_id=" . $notify_id; $responseTxt = getHttpResponseGET($veryfy_url, $this->alipay_config['cacert']); return $responseTxt; } }
把這個文件放在vendor下api
3.打開你的項目,就是controller文件夾支付的那一部數組
須要引用PayModel
use app\product_mall\model\PayModel;
//支付寶支付(wap)
public function alipay($data = null) {//發起支付寶支付 //$data的內容是訂單的信息 $Pay = new PayModel; $result = $Pay->alipay([ "out_trade_no" => $data['order_number'], //訂單號 "subject" => '現貨商城支付寶支付' ,//標題 "total_fee" => '0.01', //金額 "body" => '現貨商城支付寶支付',//商品簡介 "notify_url"=>http://md.3ddzy.com/product_mall/iphone/AlipayPayNotice_Succeed, //異步通知地址(選填)
"return_url"=>http://md.3ddzy.com/product_mall/iphone/AlipayPayReturn_Succeed//同步通知地址(選填) ]);
}
public function AlipayPayReturn_Succeed()
{
//同步通知代碼
$this->success("支付成功!", "product_mall/iphone/order");//這個地址是支付完成後返回的頁面
}
public function AlipayPayNotice_Succeed()
{
$Pay = new PayModel;
$config = $Pay::$alipay_config;
vendor('alipay.alipay');
$alipayNotify = new \AlipayNotify($config);
if($result = $alipayNotify->verifyNotify()){
if(input('trade_status') == 'TRADE_FINISHED' || input('trade_status') == 'TRADE_SUCCESS') {
// 處理支付成功後的邏輯業務
$datas = $_POST;
$res = $this->profit($datas); //這是跳轉支付成功後的操做
if($res){
echo "success";
}else{
echo "fail";
}
}else{
echo "fail";
}
}else{
echo "fail";
}
}
//充值成功後處理
public function profit($xml){
$order = [
"status" => 1,
"payment" => 2,
"notify" => json_encode($xml), //整個異步通知數據
"pay_time" => time(), //支付時間
"transaction_number" => $xml['trade_no'], //交易號
"out_trade_no" => $xml["out_trade_no"], //商戶訂單號
];
Db::name('spot_order')->where('order_number',$xml["out_trade_no"])->update($order);
//支付成功後改變庫存
$sales= Db::name('spot_order')
->where('order_number',$xml["out_trade_no"])
->field('total_number,total_account,transaction_number,notify,payment,id')
->find();
$spot_goods=Db::name('spot_goods')
->where('oid',$sales['id'])
->select()
->toArray();
foreach ($spot_goods as $k=>$v){
Db::name('commodity')
->where('id',$spot_goods[$k]['cid'])
->inc('sales',$spot_goods[$k]['total_number'])//自增
->dec('number',$spot_goods[$k]['total_number'])//自減
->update();
}
$user=cookie('ucenter_id');
$ucenter=Db::name('ucenter_mermber')
->where('id',$user)
->field('nickname,openid')
->find();
//添加支付記錄
$record=array();
$record['create_time']=time();
$record['roll_name']=$ucenter['nickname'];
$record['roll_user']=$ucenter['openid'];
$record['receive_name']='平臺';
$record['receive_user']='001';
$record['account']=$sales['total_account'];
$record['receive_account']=0;
$record['trade_no']=$sales['transaction_number'];
$record['notify_id']=$xml;
$record['notify']=$sales['notify'];
$record['type']=$sales['payment'];
$record['user']=$ucenter['nickname'];
$ok=Db::name('spot_record')
->insert($record);
// $arrdata['status'] = 1;
// $arrdata['roll_user']=$datas['buyer_email'];
// $arrdata['out_trade_no']=$datas['trade_no'];
// $arrdata['notify_id']=$datas['notify_id'];
// $data['content'] = serialize($datas);
// $arrdata['notify']=$data['content'];
// $arrdata['upatetime']= time();
// $data['create_time'] = time();
// $res = Db::name('temp_test')->insert($data);
return true;
}
原文出處:https://www.cnblogs.com/luojie-/p/11758170.html安全