<?php
//判斷是不是微信客戶端--該代碼只適用於手機微信端--使用方法請看最後面註釋
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
define('IS_WXY', true);
}else{
define('IS_WXY', false);
}javascript
// 本類由系統自動生成,僅供測試用途
class WpayAction extends CommonAction {
private $wxpayConfig;
private $wxpay;
private $parameters;
private $returnParameters;
public function _initialize(){
$this->wxpayConfig = array('CURL_TIMEOUT' => 30);
$this->wxpayConfig['appid'] = "1233423432342"; // 微信公衆號身份的惟一標識appid
$this->wxpayConfig['appsecret'] = "qwewqeqweqwewq"; // APP密鑰
$this->wxpayConfig['mchid'] = "1235423123433"; // 微信支付商戶號
$this->wxpayConfig['key'] = "afdsdgdfhreegrdgr"; // 商戶支付密鑰Key
$this->wxpayConfig['notifyurl'] = "http://www.baidu.com"; //異步通知地址
$this->wxpayConfig['returnurl'] = "http://www.baidu.com"; //同步通知地址
$this->wxpayConfig['url'] = "http://www.baidu.com";
}
public function index() {
}
/**
* 支付
*/
public function pay() {
$orderid = date('Ymdhsi') . rand(0, 999);//商戶訂單號
$payprice = "0.01";//訂單金額
if(empty($orderid) || empty($payprice)) {
die('訂單參數不完整!');
}
$openid = $this->get_openid();
// 設置統一支付接口參數
// 設置必填參數
// appid已填,商戶無需重複填寫
// mch_id已填,商戶無需重複填寫
// noncestr已填,商戶無需重複填寫
// spbill_create_ip已填,商戶無需重複填寫
// sign已填,商戶無需重複填寫
$this->setParameter("openid", $openid);
$this->setParameter("body", "購買商品"); // 商品描述
// 自定義訂單號,此處僅做舉例
//$timeStamp = time();
//$out_trade_no = \WxPayConf_pub::$APPID . $timeStamp;
$out_trade_no = $orderid;
//$out_trade_no = time();
$this->setParameter("out_trade_no", $out_trade_no); // 商戶訂單號
$this->setParameter("total_fee", $payprice * 100); // 總金額
$this->setParameter("notify_url", $this->wxpayConfig['notifyurl']); // 通知地址
$this->setParameter("trade_type", "JSAPI"); // 交易類型
// 非必填參數,商戶可根據實際狀況選填
//$unifiedOrder->setParameter("sub_mch_id", "XXXX"); // 子商戶號
//$unifiedOrder->setParameter("device_info", "XXXX"); // 設備號
//$unifiedOrder->setParameter("attach", "XXXX"); // 附加數據
//$unifiedOrder->setParameter("time_start", "XXXX"); // 交易起始時間
//$unifiedOrder->setParameter("time_expire", "XXXX"); // 交易結束時間
//$unifiedOrder->setParameter("goods_tag", "XXXX"); // 商品標記
//$unifiedOrder->setParameter("openid", "XXXX"); // 用戶標識
//$unifiedOrder->setParameter("product_id", "XXXX"); // 商品ID
$prepay_id = $this->getPrepayId();
if(empty($prepay_id)) {
die('參數出錯,請重試!');
}
$this->getParameters($prepay_id);
$this->parameters;
$returnurl = $this->wxpayConfig['returnurl'];
$parameters = $this->parameters;
$return_url = "";
$res = $this->getbutton($parameters, $return_url);
echo $res;die;
}
public function getbutton($code, $returnrul)
{
$button = <<<EOT
<script type="text/javascript">
//調用微信JS api 支付
function jsApiCall(){
WeixinJSBridge.invoke('getBrandWCPayRequest',{$code},function(res){
//window.location.href='{$returnrul}';
alert(res.err_msg);
});
}
function callpay()
{
console.log(typeof WeixinJSBridge);
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
}else{
alert(123);
jsApiCall();
}
}
callpay();
</script>
EOT;
return $button;
}
/**
* 服務器異步通知頁面路徑
*/
public function Paynotify() {
/**
* 通用通知接口demo
* ====================================================
* 支付完成後,微信會把相關支付和用戶信息發送到商戶設定的通知URL,
* 商戶接收回調信息後,根據須要設定相應的處理流程。
*
* 這裏舉例使用log文件形式記錄回調信息。
*/
// 存儲微信的回調
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
$data = $this->xmlToArray($xml);
// 驗證簽名,並回應微信。
// 對後臺通知交互時,若是微信收到商戶的應答不是成功或超時,微信認爲通知失敗,
// 微信會經過必定的策略(如30分鐘共8次)按期從新發起通知
// 儘量提升通知的成功率,但微信不保證通知最終能成功。
if($this->checkSign($data) == FALSE){
$this->setReturnParameter("return_code", "FAIL"); // 返回狀態碼
$this->setReturnParameter("return_msg", "簽名失敗"); // 返回信息
} else {
$this->setReturnParameter("return_code", "SUCCESS"); // 設置返回碼
}
$returnXml = $this->returnXml();
echo $returnXml;
//==商戶根據實際狀況設置相應的處理流程,此處僅做舉例=======
// 以log文件形式記錄回調信息
// $log_ = new \Log_();
// $log_name = THINK_PATH . "Library/Vendor/Wxpay/jssdk/notify_url.log"; // log文件路徑
// $log_->log_result($log_name, "【接收到的notify通知】:\n" . $xml . "\n");
if($this->checkSign($data) == TRUE) {
if ($data["return_code"] == "FAIL") {
// 此處應該更新一下訂單狀態,商戶自行增刪操做
die('【通訊出錯】'.$xml);
// $log_->log_result($log_name, "【通訊出錯】:\n" . $xml . "\n");
} elseif ($data["result_code"] == "FAIL"){
// 此處應該更新一下訂單狀態,商戶自行增刪操做
// $log_->log_result($log_name, "【業務出錯】:\n" . $xml . "\n");
die('【業務出錯】'.$xml);
} else {
// 此處應該更新一下訂單狀態,商戶自行增刪操做
$d['text'] = $data['out_trade_no'];
M('Demo')->add($d);
}
//商戶自行增長處理流程,
//例如:更新訂單狀態
//例如:數據庫操做
//例如:推送支付完成信息
}
}
public function ReturnNotify() {
/**
* 通用通知接口demo
* ====================================================
* 支付完成後,微信會把相關支付和用戶信息發送到商戶設定的通知URL,
* 商戶接收回調信息後,根據須要設定相應的處理流程。
*
* 這裏舉例使用log文件形式記錄回調信息。
*/
// 存儲微信的回調
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
$data = $this->xmlToArray($xml);
// 驗證簽名,並回應微信。
// 對後臺通知交互時,若是微信收到商戶的應答不是成功或超時,微信認爲通知失敗,
// 微信會經過必定的策略(如30分鐘共8次)按期從新發起通知
// 儘量提升通知的成功率,但微信不保證通知最終能成功。
if($this->checkSign($data) == FALSE){
$this->setReturnParameter("return_code", "FAIL"); // 返回狀態碼
$this->setReturnParameter("return_msg", "簽名失敗"); // 返回信息
} else {
$this->setReturnParameter("return_code", "SUCCESS"); // 設置返回碼
}
$returnXml = $this->returnXml();
//echo $returnXml;
//==商戶根據實際狀況設置相應的處理流程,此處僅做舉例=======
// 以log文件形式記錄回調信息
// $log_ = new \Log_();
// $log_name = THINK_PATH . "Library/Vendor/Wxpay/jssdk/notify_url.log"; // log文件路徑
// $log_->log_result($log_name, "【接收到的notify通知】:\n" . $xml . "\n");
if($this->checkSign($data) == TRUE) {
if ($data["return_code"] == "FAIL") {
// 此處應該更新一下訂單狀態,商戶自行增刪操做
die('【通訊出錯】'.$xml);
// $log_->log_result($log_name, "【通訊出錯】:\n" . $xml . "\n");
} elseif ($data["result_code"] == "FAIL"){
// 此處應該更新一下訂單狀態,商戶自行增刪操做
// $log_->log_result($log_name, "【業務出錯】:\n" . $xml . "\n");
die('【業務出錯】'.$xml);
} else {
// 此處應該更新一下訂單狀態,商戶自行增刪操做
}
//商戶自行增長處理流程,
//例如:更新訂單狀態
//例如:數據庫操做
//例如:推送支付完成信息
}else $this->redirect('Mobile/Orders/orderNoReceive');
}
/**
* 獲取openid
*/
private function get_openid() {
$openid = $_COOKIE['apiopenid'];
if(empty($openid)) {
// 經過code得到openid
if (!isset($_GET['code'])) {
// 觸發微信返回code碼
$url = $this->createOauthUrlForCode($this->get_url());
Header("Location: " . $url);
} else {
// 獲取code碼,以獲取openid
$code = $_GET['code'];
$openid = $this->getOpenId($code);
setcookie('apiopenid', $openid, time() + 86400);
}
}
return $openid;
}
/**
* 獲取當前頁面完整URL地址
*/
private function get_url() {
$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}
/**
* 做用:生成能夠得到code的url
*/
private function createOauthUrlForCode($redirectUrl) {
$urlObj["appid"] = $this->wxpayConfig['appid'];
$urlObj["redirect_uri"] = "$redirectUrl";
$urlObj["response_type"] = "code";
$urlObj["scope"] = "snsapi_base";
$urlObj["state"] = "STATE"."#wechat_redirect";
$bizString = $this->formatBizQueryParaMap($urlObj, false);
return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
}
/**
* 做用:經過curl向微信提交code,以獲取openid
*/
private function getOpenid($code) {
$url = $this->createOauthUrlForOpenid($code);
//初始化curl
$ch = curl_init();
//設置超時
curl_setopt($ch, CURLOPT_TIMEOUT, $this->wxpayConfig['CURL_TIMEOUT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//運行curl,結果以jason形式返回
$res = curl_exec($ch);
curl_close($ch);
//取出openid
$data = json_decode($res,true);
$this->openid = $data['openid'];
return $this->openid;
}
/**
* 做用:生成能夠得到openid的url
*/
private function createOauthUrlForOpenid($code) {
$urlObj["appid"] = $this->wxpayConfig['appid'];
$urlObj["secret"] = $this->wxpayConfig['appsecret'];
$urlObj["code"] = $code;
$urlObj["grant_type"] = "authorization_code";
$bizString = $this->formatBizQueryParaMap($urlObj, false);
return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
}
/**
* 做用:格式化參數,簽名過程須要使用
*/
private function formatBizQueryParaMap($paraMap, $urlencode) {
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v)
{
if($urlencode)
{
$v = urlencode($v);
}
//$buff .= strtolower($k) . "=" . $v . "&";
$buff .= $k . "=" . $v . "&";
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff)-1);
}
return $reqPar;
}
/**
* 做用:設置請求參數
*/
private function setParameter($parameter, $parameterValue) {
$this->parameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
}
private function trimString($value) {
$ret = null;
if (null != $value) {
$ret = $value;
if (strlen($ret) == 0) {
$ret = null;
}
}
return $ret;
}
/**
* 獲取prepay_id
*/
private function getPrepayId() {
$response = $this->postXml();
$result = $this->xmlToArray($response);
$prepay_id = $result["prepay_id"];
return $prepay_id;
}
/**
* 做用:post請求xml
*/
private function postXml() {
$xml = $this->createXml();
$response = $this->postXmlCurl($xml,$this->wxpayConfig['url'],$this->wxpayConfig['CURL_TIMEOUT']);
return $response;
}
/**
* 生成接口參數xml
*/
private function createXml() {
try {
// 檢測必填參數
if($this->parameters["out_trade_no"] == null) {
throw new \Exception("缺乏統一支付接口必填參數out_trade_no!"."<br>");
}elseif($this->parameters["body"] == null){
throw new \Exception("缺乏統一支付接口必填參數body!"."<br>");
}elseif ($this->parameters["total_fee"] == null ) {
throw new \Exception("缺乏統一支付接口必填參數total_fee!"."<br>");
}elseif ($this->parameters["notify_url"] == null) {
throw new \Exception("缺乏統一支付接口必填參數notify_url!"."<br>");
}elseif ($this->parameters["trade_type"] == null) {
throw new \Exception("缺乏統一支付接口必填參數trade_type!"."<br>");
}elseif ($this->parameters["trade_type"] == "JSAPI" &&
$this->parameters["openid"] == NULL){
throw new \Exception("統一支付接口中,缺乏必填參數openid!trade_type爲JSAPI時,openid爲必填參數!"."<br>");
}
$this->parameters["appid"] = $this->wxpayConfig['appid']; // 公衆帳號ID
$this->parameters["mch_id"] = $this->wxpayConfig['mchid']; // 商戶號
$this->parameters["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];// 終端ip
$this->parameters["nonce_str"] = $this->createNoncestr(); // 隨機字符串
$this->parameters["sign"] = $this->getSign($this->parameters); // 簽名
return $this->arrayToXml($this->parameters);
} catch (\Exception $e) {
die($e->errorMessage());
}
}
/**
* 做用:產生隨機字符串,不長於32位
*/
private function createNoncestr( $length = 32 ) {
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for ( $i = 0; $i < $length; $i++ ) {
$str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
}
return $str;
}
/**
* 做用:生成簽名
*/
private function getSign($Obj) {
foreach ($Obj as $k => $v) {
$Parameters[$k] = $v;
}
//簽名步驟一:按字典序排序參數
ksort($Parameters);
$String = $this->formatBizQueryParaMap($Parameters, false);
//echo '【string1】'.$String.'</br>';
//簽名步驟二:在string後加入KEY
$String = $String."&key=".$this->wxpayConfig['key'];
//echo "【string2】".$String."</br>";
//簽名步驟三:MD5加密
$String = md5($String);
//echo "【string3】 ".$String."</br>";
//簽名步驟四:全部字符轉爲大寫
$result_ = strtoupper($String);
//echo "【result】 ".$result_."</br>";
return $result_;
}
/**
* 做用:array轉xml
*/
private function arrayToXml($arr) {
$xml = "<xml>";
foreach ($arr as $key=>$val) {
if (is_numeric($val)) {
$xml.="<".$key.">".$val."</".$key.">";
} else {
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
/**
* 做用:以post方式提交xml到對應的接口url
*/
private function postXmlCurl($xml,$url,$second = 30) {
//初始化curl
$ch = curl_init();
//設置超時
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//這裏設置代理,若是有的話
//curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
//設置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求結果爲字符串且輸出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//運行curl
$data = curl_exec($ch);
curl_close($ch);
//返回結果
if($data)
{
//curl_close($ch);
return $data;
}
else
{
$error = curl_errno($ch);
echo "curl出錯,錯誤碼:$error"."<br>";
echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>錯誤緣由查詢</a></br>";
curl_close($ch);
return false;
}
}
/**
* 做用:將xml轉爲array
*/
private function xmlToArray($xml) {
//將XML轉爲array
$array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $array_data;
}
/**
* 做用:設置jsapi的參數
*/
private function getParameters($prepay_id) {
$jsApiObj["appId"] = $this->wxpayConfig['appid'];
$timeStamp = time();
$jsApiObj["timeStamp"] = "$timeStamp";
$jsApiObj["nonceStr"] = $this->createNoncestr();
$jsApiObj["package"] = "prepay_id=$prepay_id";
$jsApiObj["signType"] = "MD5";
$jsApiObj["paySign"] = $this->getSign($jsApiObj);
$this->parameters = json_encode($jsApiObj);
}
private function checkSign($data) {
$tmpData = $data;
unset($tmpData['sign']);
$sign = $this->getSign($tmpData);//本地簽名
if ($data['sign'] == $sign) {
return TRUE;
}
return FALSE;
}
/**
* 設置返回微信的xml數據
*/
private function setReturnParameter($parameter, $parameterValue) {
$this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
}
/**
* 將xml數據返回微信
*/
private function returnXml() {
$returnXml = $this->arrayToXml($this->returnParameters);
return $returnXml;
}
/*----如下是JSSDK的文件----*/
private function getSignPackage() {
$jsapiTicket = $this->getJsApiTicket();
// 注意 URL 必定要動態獲取,不能 hardcode.
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = $this->createNonceStr2();
// 這裏參數的順序要按照 key 值 ASCII 碼升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
$signature = sha1($string);
$signPackage = array(
"appId" => $this->wxpayConfig['appid'],
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string
);
return $signPackage;
}
private function createNonceStr2($length = 16) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
private function getJsApiTicket() {
// jsapi_ticket 應該全局存儲與更新,如下代碼以寫入到文件中作示例
// $data = json_decode(file_get_contents("jsapi_ticket.json"));
$data = json_decode($_COOKIE['jsapi_ticket_json']);
if ($data->expire_time < time()) {
$accessToken = $this->getAccessToken();
// 若是是企業號用如下 URL 獲取 ticket
// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
$ticket = $res->ticket;
if ($ticket) {
//$data->expire_time = time() + 7000;
//$data->jsapi_ticket = $ticket;
//$fp = fopen("jsapi_ticket.json", "w");
//fwrite($fp, json_encode($data));
//fclose($fp);
$tempArr = array('jsapi_ticket' => $ticket, 'expire_time' => time() + 7000);
setcookie('jsapi_ticket_json', json_encode($tempArr), $tempArr['expire_time']);
}
} else {
$ticket = $data->jsapi_ticket;
}
return $ticket;
}
private function getAccessToken() {
// access_token 應該全局存儲與更新,如下代碼以寫入到文件中作示例
// $data = json_decode(file_get_contents("access_token.json"));
$data = json_decode($_COOKIE["access_token_json"]);
if ($data->expire_time < time()) {
// 若是是企業號用如下URL獲取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->wxpayConfig['appid'] . "&secret=" . $this->wxpayConfig['appsecret'];
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
//$data->expire_time = time() + 7000;
//$data->access_token = $access_token;
//$fp = fopen("access_token.json", "w");
//fwrite($fp, json_encode($data));
//fclose($fp);
$tempArr = array('access_token' => $access_token, 'expire_time' => time() + 7000);
setcookie('access_token_json', json_encode($tempArr), $tempArr['expire_time']);
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
private function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;;
}
} php
/*********************狀況操做流程****************************/html
/***java
直接把代碼放到你的一個控制器方法裏面就可使用數據庫
*/json