本文主要和大家詳細介紹了PHP微信支付開發過程,具有一定的參考價值,有興趣的小夥伴們可以參考一下,希望能幫助到大家。
1.開發環境
Thinkphp 3.2.3
微信:服務編號,已認證
開發網域:http://test.paywechat.com (自定義的域名,外網不可訪問)
2.需要相關文件和權限
微信支付需申請開通
微信公眾平台開發者文件:http:// mp.weixin.qq.com/wiki/home/index.html
微信支付開發者文件:https://pay.weixin.qq.com/wiki/doc/api/index.html
#微信支付SDK下載網址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1
3.開發
#下載好微信支付PHP版本的SDK,檔案目錄為下圖:
#
把微信支付SDK的Cert和Lib目錄放入Thinkphp,目錄為
現在介紹微信支付授權目錄問題,首先是微信支付開發配置裡面的支付授權目錄填寫,
然後填入js介面安全域。
最後設定網頁授權
這些設定完,基本上完成一半,注意設定的目錄和我thinkphp裡面的目錄。
4.微信支付配置
#[php] view plain copy
/**
* 設定帳號資訊
*/
#
class WxPayConfig
##{
# //=======【基本資訊設定】====================== =================
# //
/**
-
* TODO: 修改這裡設定為您自己申請的商家資訊
* 微信公號資訊設定
*
## * APPID :綁定付款的APPID(必須配置,開戶郵件中可檢視)
*
# * MCHID:商家號碼(必須配置,開戶郵件中可檢視)
*
# * KEY:商家支付金鑰,參考開戶郵件設定(必須配置,登入商家平台自行設定)
* 設定位址:https://pay.weixin.qq.com/index.php/account/api_cert
*
- ## * APPSECRET:公用帳號secert(只有JSAPI付款的時候需要配置, 登入公眾平台,進入開發者中心可設定),
#
* 取得網址:https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN
* @var string
*/
-
# const APPID = ''
; const MCHID = ##''
; const KEY = ''
; const# APPSECRET = ''
#; -
# //=======【憑證路徑設定】=====================================
- /**
- * TODO :設定商家憑證路徑
* API憑證下載位址:https://pay.weixin.qq.com/index.php/account/api_cert,下載前需安裝商家操作憑證)
* @var path
*/
# - const
SSLCERT_PATH =
#'. ./cert/apiclient_cert.pem' - ;
- SSLKEY_PATH =
const SSLKEY_PATH = #'../cert/apiclient_key.pem'
; -
# //=======【curl代理設定】========================= ============
-
#
/** -
-
* 本程式透過curl使用HTTP POST方法,此處可修改代理伺服器,
### ################## * 預設CURL_PROXY_HOST=0.0.0.0和CURL_PROXY_PORT=0,此時不開啟代理程式(若有需要才設定)### ##### ################ * @var unknown_type### ##################### */ ###### ######### const CURL_PROXY_HOST = "0.0.0.0";#// "10.152.18.220";
-
const# CURL_PROXY_PORT = 0;# CURL_PROXY_PORT = 0; //8080;
- //=======【回報資訊配置】================================= ====
# /**
* TODO:介面呼叫上報等級,預設緊錯誤上報(註:上報超時間為【1s】,上報無論成敗【永不拋出例外】,
# * 不會影響介面呼叫流程),開啟回報之後,方便微信監控請求調用的質量,建議至少
# * 開啟錯誤回報。
- * 回報等級,0.關閉回報; 1.僅錯誤回報; 2.全量回報
-
###### */###### ################################/#######################################################################################################。 ################### ###const####### REPORT_LEVENL = 1; ####################################################################### ####} #######
現在開始貼出程式碼:
#[php] view plain copy
namespace Wechat\ Controller;
#use Think\Controller;
/**
* 父類別控制器,需繼承
- # * @file ParentController.class.php
### ##################### * @date 2015年8月4日### ############### ####### * @todu### ###################### */####### ######### class ParentController extends Controller {
Controller { protected
#$options= array# ( ##array# (
- 'token'
# => '', // 填寫你設定的key
# - 'encodingaeskey'
=> '', #// 填入加密使用的EncodingAESKey
# - 'appid'
=> '', // 填寫高級呼叫功能的app id
#### ###'appsecret'###### => #### ###''######, ######// 填入進階呼叫功能的金鑰###### ######### '偵錯'# => false,
'logcallback'# => ''
);
##public#$errCode=40001;
#public#$errMsg==「無法存取」;
#/**
- ## * 取得access_token
- * @return mixed|boolean|unknown
- # */
- #公用
#函數
############################################################################################################################。 getToken(){ ########## ##$cache_token=S('exp_wechat_pay_token');
if(!空白##( $cache_token)){
- ##return
# $cache_token;
## } -
# = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s'; #$url=sprintf($url,
$this######->選項[######'appid'#######],######$this##### ->選項[######'appsecret'######]); ########## $結果 = $this->http_get($網址);
#$結果 = json_decode($結果,真的);
if(空##(## ) ##$結果)){
- #回傳
# false;
## } -
S(
'exp_wechat_pay_token' -
,$結果['access_token'],陣列 ( '類型'=>'檔案',##'過期'# => 3600)); #
#return #$結果['access_token' ];
}
## #########/**&# #民眾 函數 sendCustomMessage($data){
-
## #$token = $this->getToken();
##if(($token)) return false; #
$url = 'https://api.weixin.qq.com/cgi-bin/message/custom /send?access_token=%s';
#$url=sprintf($url, $令牌);
- ##
$結果# = $this-> http_post( $url,self::json_encode($data));
if($ {
-
#$json
- = json_decode (
$結果,true); #
#if (!$ ##($json['錯誤代碼'])) {
$this->errCode = $json[#'errcode ' ];
#$this->errMsg = $json
['errmsg'];
#return false; ################ $json; ################錯誤的;
}
-
########################################
#/**
* 傳送範本訊息
* @param unknown $data
* @return boolean|unknown
*/
##public function sendTemplateMessage($data){
# $token = $this->getToken();
##if(($token)) return false;
- ##
$url# = "https://api.weixin.qq. com /cgi-bin/message/template/send?access_token=%s"#; #
$url = sprintf($url,$token);
$result = $this->http_post($url,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
#if (!$ ##($json['錯誤代碼'])) {
$this->errCode = $json[#'errcode ' ];
#$this->errMsg = $json
['errmsg'];
#return false; ################ $json; ################錯誤的;
}
-
########################################
public function getFileCache($name){
return S($name);
}
## #########/**&# #靜止的 函數 json_encode($arr) {
-
- ##
#$零件 = 陣列 ();
#####################$is_list####### = false; ########################//判斷給定的陣列是否為數值陣列############## # #$keys = array_keys ( #$arr#);
##$max_length = count ( #$arr ) - 1;
#if(($keys##[0] == = 0) && ($keys [$max_length] === #$max_length )) { //檢視第一個鍵是否為0,最後一個鍵的長度是否為-1
- #$is_list
= true; #
#for($i= 0; $i count ( #$keys ); $i ++) { //檢視每個按鍵是否對應其位置
-
if ($i
!= - $keys
[
$i - ]) {
//某個按鍵在位置檢查時失敗。 ## $is_list
= false; -
//這是一個關聯陣列。 # #;
############ } ################## } #################################################################### # ######### } ######## #foreach ( $arr as
$key
=> $value ) {
## - #if
(is_array ( $value )) { #//陣列的自訂處理
-
if (
# ##$is_list######) ##########################$parts###### [ ] = self::json_encode (######$值######); ######/* :遞歸: */####### ##########################else#### ## ######### $零件 [] = '"' . $key . '":' . self::json_encode ($value); /* :遞迴: */
# } #else {
-
$str = ##''
##; -
if(!$is_list
) -
# $str# = '"' . $key . '":'
#; -
//多種資料類型的自訂處理
######### if (!is_string ( $value# ) && is_numeric ( $value ) && $value$value
-
## elseif ( $value
=== false) $str# . = ######'錯誤的'######; //布林值
elseif ( ##$value === true)
#$str。 ##'true'; #
#else
# $str .= '"' . 新增斜線## ( #$value ) . '"'; //所有其他事情
#//:TODO:還有嗎我們該留意的資料類型? (對象?)
$parts [] = $str;
}
}
-
## #$json = 內爆 ( ',', #$parts
### ); ########################if######(######$is_list######) ############################################# ###### return #'[' . $json . ']'##; //Return numerical JSON#
## return '{' . $json . '}'; //Return associative JSON
# }
- /**
- +------------------------------ ----------------------------
## +----------------------------------- -------------------------------------
# * @回傳字串
+-------- ---------------- ---------------------------------- -#
###### ##### ###靜止的##### $length= 5, $類型# = 2){
-
# # $arr = 陣列(1 =>
"0123456789" - , 2 =>
"abcdefghijklmnopqrstuvwxyz"##, 3 = > "ABCDEFGHIJKLMNOPQRSTUVWXYZ"#, 4 => " &*(){}[]|"); #if($type===0) { #
#array_pop($arr);
#$string#==內爆("", $arr);
} #elseif ($type == ##"-1") {
$string
# =內爆("",
$arr); ########### # # #$string = $arr[$type##];
} #
$count = strlen($string#) - 1;
$程式碼#= '';
for($i##=0;$i $長度#; $i++) {
#$code.=$string[rand(0 , $count)]; ################ $程式碼;
-
}
-
- ##
#####/******# ######
## * GET 請求#
* @param string $url
##*/
問題# # private
-
function# http_get($url
#function - # http_get(
$url){ ##$oCurl
=curl_init(); -
#########if######(######stripos#####(#### ) ##$url######,######"https://"######)!==FALSE){ ############# # ###### curl_setopt(###$oCurl######, CURLOPT_SSL_VERIFYPEER, FALSE); #####################curl_setopt(###$oCurl######, CURLOPT_SSL_VERIFYHOST, FALSE); #####################curl_setopt(###$oCurl######, CURLOPT_SSLVERSION, 1); ######//CURL_SSLVERSION_TLSv1###### ###################### } #######
curl_setopt($oCurl#, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
#$sContent#=curl_exec($oCurl) ;
#$aStatus#=curl_getinfo($oCurl) ;
## curl_close(- $oCurl
#);
- if
(intval##(# ) ##$aStatus["http_code"])==200){ #
#return -
$sContent; ################# # # #返回 假; #
}
# }
-
##/**
-
* POST 請求
# # * @param string $url * @param array $param
-
* @param boolean $post_file 是否檔案上傳
######### * @return string content# ## ###################### */##################### ## ###### ####private###### ######函數###### http_post(######$url#######,# ### ##$param######,######$post_file######=false){ ########################## #### ###$oCurl###### = curl_init(); ########## #if(#stripos#($url,"https://")!==FALSE){
curl_setopt( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
# }
-
# } ## #if (is_string($param) ||
$post_file - ) {
##$strPOST# =
$參數 - ; ###########
##$aPOST=陣列();
-
#foreach($param ## as $key=>#$val){
## $aPOST [] = $key##."= “ .urlencode($val); ## }
##$strPOST
# = join("&", #$aPOST
); -
## }
########## curl_setopt(###$oCurl### # ##,CURLOPT_URL,######$url######); #####################curl_setopt(###$oCurl######, CURLOPT_RETURNTRANSFER, 1); ########## curl_setopt($oCurl#, CURLOPT_POST,true);
curl_setopt($oCurl, CURLOPT_POSTFIELDS,#$strPOST #);
#$sContent#=curl_exec($oCurl) ;
#$aStatus#=curl_getinfo($oCurl) ;
- curl_close(
$oCurl);
-
if(intval##(# ) ##$aStatus["http_code"])==200){
# #return -
$sContent; ################# # # #返回 假;
# }
# }
## $str .= $value ; //數字
# }
[php]
[php]# # 看法 plain 複製
。空間微信\控制器;
使用 Wechat\Controller\ParentController;
-
/**
-
* 微信支付測試控制器
###################################################################################################### #### * @file TestController.class.php### ##################### * @author Gary## # ###################### * @date 2015年8月4日### ################ ##### * @todu### ###################### */###### ########## class TestController #extends ParentController {
-
-
#$_order_body = 'xxx';
#私人 #$_order_goods_tag=='xxx';
#public
#function__construct(){ 父::__construct();
-
require_once ROOT_PATH."Api/lib/WxPay.Api.php" ;
- #require_once
#ROOT_PATH.
"Api/lib/WxPay.JsApiPay.php" - ;
######### } ################## ###########################################################################################
public #function index(){
-
$tools =
new-
\JsApiPay();
$openId -
= $tools->GetOpenid();
# //②、統一訂單 -
-
= new \WxPayUnifiedOrder();
//商品說明 -
$input->SetAttach('xxx');
//商家訂單號碼#
$out_trade_no = \WxPayConfig::MCHID.date("YmdHis"#);
$input->SetOut_trade_no($out_trade_no #);
//總金額,訂單總金額,只能為整數,單位為分
## $input->SetTotal_fee(1);
# //交易起始時間
-
## $input
->SetTime_start( - date
#("YmdHis"));
############### ###//交易結束時間###### ######### $input->SetTime_expire(date(#"YmdHis ", time() + 600));
# //商品標記
$input->SetGoods_tag($this #->_order_goods_tag);
# //通知位址,接收微信支付非同步通知回呼位址 SITE_URL=http://test .paywechat.com/Charge
$notify_url# = SITE_URL. '/index.php/Test/notify.html';
# $input->SetNotify_url(##$notify_url);
/ /交易類型
# $input->SetTrade_type("JSAPI");
# $input##->SetOpenid( $openId); #
$order = \WxPayApi::unifiedOrder($input#);
$jsApiParameters
= $tools->GetJsApiParameters($order);
- #
//取得共享收貨位址js函數參數
$editAddress = $tools #->GetEditAddressParameters();
- #
$this->assign(
'openId' - ,
$openId); # $this->assign(
'jsApiParameters'######,## ####$jsApiParameters######); ##################### ###$this#######->assign (######'editAddress'######,######$editAddress######); ######### $this->display();
# }
/**
* 非同步通知回呼方法
*/
public #function# notify (){
require_once ROOT_PATH.#"Api/lib/notify.php ";
# $notify = #new \PayNotifyCallBack();
$notify->Handle(false);
//這裡的IsSuccess是我自訂的方法,後面我會貼出這個檔案的程式碼,供參考。
-
$is_success = #$notify#->IsSuccess();
# $bdata = $is_success['資料'];
## //付款成功#
- #
#if($is_success['程式碼'] == 1 ) {
- #
$新聞 = 陣列(
-
'touser'# => $bdata[ 'openid'],
-
'msgtype'# => '新聞',
- #
'新聞' = > 陣列 ( #
'articles'=> array (
# array(
#'title' => '訂單付款成功',
# # #'description' =>
"付款金額:{$bdata['total_fee']}\n"- ##.
#
"微信訂單編號:{$bdata['transaction_id']}\n" -
## 'picurl' =>
'' - ,
'url'
=> ''
-
//寄送微信付款通知
$this->sendCustomMessage($news);
# }else{//支付失敗#
# }
# }
##
-
/**
* 付款成功頁面 -
-
* 不可靠的回呼
####### */###### ########## ############ ###public###### #######function###### ajax_PaySuccess(){ ############ ########## ###//訂單號碼###### ##################### ###$out_trade_no# ##### = I(######'post.out_trade_no'#######); ########## //付款金額
## #$ total_fee = I('post.total_fee');
#/*相關邏輯處理*/
#
# }
[xhtml] view plain copy
html>
-
#
######################## ##head######>###### ########## #元#http-equiv##=「內容類型」 內容=#「text/html;charset=utf-8」 / >
meta 名稱="視窗" 內容=#"寬度=裝置寬度,初始比例=1“/>
標題>微信支付範例-支付#標題## > #
script# type=
"text/javascript"
>//呼叫微信JS api 支付
# function jsApiCall()
{
# {
-
WeixinJSBridge.invoke(
# 'getBrandWCPayRequest', -
############################################# # {$jsApiParameters}, ################### function(res){ ################### WeixinJSBridge.log( res.err_msg); ################### //取消付款 ################## if(### res.err_msg###### == 'get_brand_wcpay_request:cancel'){ ###################### //處理取消付款的事件邏輯 ############ //處理取消付款的事件邏輯 ############ //處理取消付款的事件邏輯 ### ############### }else if(###res.err_msg###### == "get_brand_wcpay_request:ok"){ ############ ########### /*使用上述方式判斷前端回傳,微信團隊鄭重提示: ################## res.err_msg將在用戶支付成功後返回 ok,但不保證它絕對可靠。方法。 ######### alert(res.err_code+res.err_desc+res.err_msg); ################## } ################### } ####### ########### ); ################## callpay()
-
{
-
## if (typeof
WeixinJSBridge -
== "未定義"){
## if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
}else if (document.attachEvent){
document.attachEvent(' WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall); ########### # ## jsApiCall();
}
# }
## //取得共享位址
#函數 editAddress()
#'editAddress', ## {$editAddress},
-
函數(res){ var value1 =
###res######.proviceFirstStageName; ############ # ######## var ###value2###### = ######res######.addressCitySecondStageName; ########## var value3 = res.addressCountiesThirdStageName;
## var value4# = res.addressDetailInfo;
var tel# = = res.telNumber;
- ##警報(值1+值2+值3+值4+「:」+電話);
- }
- #);
- }
#window.onload
= #function(){
-
# if (typeof
WeixinJSBridge -
# == 「未訂定」){
############# if ( document. addEventListener){ ################## document.addEventListener('WeixinJSBridgeReady', editAddress, false); ################## }else if (document.attachEvent){ ################## document.attachEvent(' WeixinJSBridgeReady', editAddress); ################## document.attachEvent('onWeixinJSBridgeReady', editAddress); ########### # ######## 編輯地址(); ###### }
# };
# >
head >
#body
br##/> ##
-
font# color= "#9ACD32">#b>該筆訂單支付金額為span style#="color:#f00;font-size:50px">1分#span>
###### ########b######>############font#####>######< ;######br######/>############ ################################################################################################################## ###### #p# 對齊=
## 「中心」> ## ## ##>
-
###########################################################################################按鈕# ##### ######樣式######=######"寬度:210 像素;高度:50 像素;邊框半徑:15 像素;背景顏色:#FE6714;邊框: 0px #FE6714 實心; 遊標:指標; 顏色:白色; 字體大小:16px;「###### ######類型##### # ######onclick######=######"callpay()"###### #####>######立即支付### #########按鈕######>###### ################## ### ######################################################## ######p######>####### #########
body#>
#html>
#。 ##notify.php檔案程式碼,這裡有在官方文件裡新加入的自訂方法。
-
[php] view plain copy
#################################require_once## #### ROOT_PATH.######"Api/lib/WxPay.Api.php"######; ##################### ####require_once###### ROOT_PATH.######'Api/lib/WxPay.Notify.php'######; ############## ###########require_once###### ROOT_PATH.######'Api/lib/log.php'######; ######### # //初始化日志
$logHandler= new \CLogFileHandler(ROOT_PATH. "/logs/".date('Y-m-d').'.紀錄');
$log# = \Log::Init($logHandler
#, 15);
-
##
##############class###### PayNotifyCallBack ######延伸###### WxPayNotify #####################{ ########################################################################################################################################################### #受保護$para=##陣列 ('代碼'=>0,'資料'##=>##''#);
- //查詢訂單
- #public
函數# Queryorder($transaction_id##)
# { -
#
$input - ## =
new \WxPayOrderQuery(); #$input
->SetTransaction_id( $transaction_id# #); #$結果= \WxPayApi::orderQuery(
$input-
); #
\Log::DEBUG("查詢:" . json_encode($結果#)) ;
if(array_key_exists(## ) ##"return_code", $結果#)
# &&array_key_exists("result_code", $result)
# && $結果["return_code"] == "成功"
&& $結果[#" result_code "] == "成功"#)
# {
- ##
return true;
- }
#
$this->para['code'##] = 0;
$this->para['data'] = '';
# return false;
}
//重寫回呼處理函數 #public
function NotifyProcess(
#$data-
, &$msg#)
{ -
# \Log::DEBUG(" call back:" . json_encode($data));
######################################################################################## # ###$notfiyOutput###### = ######array######(); ########################## # if(!array_key_exists("transaction_id", #$data)){
# $msg = "輸入參數不正確";
# $this->para['code'##] = 0;
$this->para['data'] = '';
# return false;
}
# //查詢訂單,判斷訂單真實性愛
if(!#$this->Queryorder(##$ data["transaction_id"])){
$msg = "訂單查詢失敗"#;
$this->para['code'#] = 0;
-
# $this->para[
'data' - ] =
''
; - return
false;
#################################################################################################################### ####### } ################### ################## ###$this# #####->para[######'code'######] = 1; ######### $this->para['data'##] =
# #$data
; # return
true; -
# }
#
# # /**
以上是PHP實作微信支付功能開發程式碼分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

tostartaphpsession,usesesses_start()attheScript'Sbeginning.1)placeitbeforeanyOutputtosetThesessionCookie.2)useSessionsforuserDatalikeloginstatusorshoppingcarts.3)regenerateSessiveIdStopreventFentfixationAttacks.s.4)考慮使用AttActAcks.s.s.4)

會話再生是指在用戶進行敏感操作時生成新會話ID並使舊ID失效,以防會話固定攻擊。實現步驟包括:1.檢測敏感操作,2.生成新會話ID,3.銷毀舊會話ID,4.更新用戶端會話信息。

PHP会话对应用性能有显著影响。优化方法包括:1.使用数据库存储会话数据,提升响应速度;2.减少会话数据使用,只存储必要信息;3.采用非阻塞会话处理器,提高并发能力;4.调整会话过期时间,平衡用户体验和服务器负担;5.使用持久会话,减少数据读写次数。

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

phpIdentifiesauser'ssessionSessionSessionCookiesAndSessionId.1)whiwsession_start()被稱為,phpgeneratesainiquesesesessionIdStoredInacookInAcookInAcienamedInAcienamedphpsessIdontheuser'sbrowser'sbrowser.2)thisIdallowSphptpptpptpptpptpptpptpptoretoreteretrieetrieetrieetrieetrieetrieetreetrieetrieetrieetrieetremthafromtheserver。

PHP會話的安全可以通過以下措施實現:1.使用session_regenerate_id()在用戶登錄或重要操作時重新生成會話ID。 2.通過HTTPS協議加密傳輸會話ID。 3.使用session_save_path()指定安全目錄存儲會話數據,並正確設置權限。

phpsessionFilesArestoredIntheDirectorySpecifiedBysession.save_path,通常是/tmponunix-likesystemsorc:\ windows \ windows \ temponwindows.tocustomizethis:tocustomizEthis:1)useession_save_save_save_path_path()


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

Atom編輯器mac版下載
最受歡迎的的開源編輯器