一直在做微信,遇到过很多坑,今天写出来,让大家少走点弯路,第一次写文字,有点土,如果有不懂的童鞋,可以联系我QQ1034100429,或者发私信。
getaccesstoken 获取access_token
//发起支付
public function sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url)
sendtpl 发送模板消息<?php <br />
/**<br>
* Created by PhpStorm.<br>
* User: Administrator<br>
* Date: 2016/4/11<br>
* Time: 22:43<br>
*/<br>
namespace Org;<br>
class Weixin<br>
{<br>
private $appid; //微信公众号的appid<br>
private $appsecret; //微信公众号的appsecret<br>
private $mchid; //微信公众号的商户号<br>
private $wechatkey; //微信公众号的支付密钥<br>
private $token;<br>
public function __construct()<br>
{<br>
$this->appid = C('WEIXIN_APPID');<br>
$this->appsecret = C("WEIXIN_APP_SECRET");<br>
$this->mchid = C("WEIXIN_MCHID");<br>
$this->wechatkey = C("WEIXIN_KEY");<br>
$this->token = C('WEIXIN_APP_TOKEN');<br>
<br>
}<br>
public function chushi()<br>
{<br>
echo $this->getaccesstoken();<br>
}<br>
public function checkSignature()<br>
{<br>
$signature = $_GET['signature'];<br>
$timestamp = $_GET['timestamp'];<br>
$nonce = $_GET['nonce'];<br>
$token = $this->token;<br>
$arrtemp = array($token, $timestamp, $nonce);<br>
sort($arrtemp, SORT_STRING);<br>
$arrtemp = implode($arrtemp);<br>
$arrtemp = sha1($arrtemp);<br>
if ($arrtemp == $signature) {<br>
return true;<br>
} else {<br>
return false;<br>
}<br>
}<br>
public function valid()<br>
{<br>
$echoStr = $_GET['echostr'];<br>
if ($this->checkSignature()) {<br>
echo $echoStr;<br>
exit;<br>
}<br>
}<br>
////根据返回的信息,做出相应的处理<br>
// public function responseMsg()<br>
// {<br>
// $postStr = file_get_contents('php://input');<br>
// if (!empty($postStr)){<br>
// /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,<br>
// the best way is to check the validity of xml by yourself */<br>
// libxml_disable_entity_loader(true);<br>
// $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);<br>
// $fromUsername = $postObj->FromUserName;<br>
// $toUsername = $postObj->ToUserName;<br>
// $keyword = trim($postObj->Content);<br>
// $msgType = $postObj->MsgType;<br>
// $Event=$postObj->Event;<br>
// $time = time();<br>
// $textTpl = "<xml><br>
// <tousername></tousername><br>
// <fromusername></fromusername><br>
// <createtime>%s</createtime><br>
// <msgtype></msgtype><br>
// <content></content><br>
// <funcflag>0</funcflag><br>
// </xml>";<br>
// if(!empty( $keyword ))<br>
// {<br>
// $msgType = "text";<br>
// $contentStr = "Welcome to wechat world!";<br>
// $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);<br>
// echo $resultStr;<br>
// }else{<br>
// echo "Input something...";<br>
// }<br>
//<br>
// }else {<br>
// echo "";<br>
// exit;<br>
// }<br>
// }<br>
public function getaccesstoken()<br>
{<br>
$access_token = S('access_token');<br>
if(!empty($access_token)){<br>
<br>
return $access_token;<br>
}else{<br>
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;;<br>
$ret = $this->curlget($url);<br>
$ret = json_decode($ret,true);<br>
S('access_token',$ret['access_token'],7100);<br>
<br>
return $ret['access_token'];<br>
}<br>
}<br>
//根据openid拉取用户信息<br>
public function userinfo($openid){<br>
$access_token = $this->getaccesstoken();<br>
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";<br>
$userinfo = json_decode($this->curlget($url),true);<br>
return $userinfo;<br>
}<br>
function p($arr){<br>
echo "<meta>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">";<br>
print_r($arr);<br>
}<br>
function curlget($url)<br>
{<br>
$ch = curl_init();<br>
curl_setopt($ch, CURLOPT_URL, $url);<br>
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);<br>
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);<br>
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br>
curl_setopt($ch, CURLOPT_HEADER, 0);<br>
$output = curl_exec($ch);<br>
curl_close($ch);<br>
return $output;<br>
}<br>
public function jingmo($url,$code,$state){<br>
if($code){<br>
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";<br>
$arrtemp = json_decode($this->curlget($url),true);<br>
$ret = $this->getuserinfo($arrtemp['openid'],$arrtemp['access_token']);<br>
return $ret;<br>
}else{<br>
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$url."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";<br>
header("Location: $url");<br>
}<br>
}<br>
public function getuserinfo($openid,$user_access_token){<br>
$userurl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$user_access_token."&openid=".$openid."&lang=zh_CN";<br>
$userinfo = json_decode($this->curlget($userurl),true);<br>
return $userinfo;<br>
}<br>
public function getjsapi_ticket(){<br>
$js_ticket = S("js_ticket");<br>
if(!empty($js_ticket)){<br>
return $js_ticket;<br>
}else{<br>
$access_token = $this->getaccesstoken();<br>
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";<br>
$res = json_decode($this->curlget($url),true);<br>
S("js_ticket",$res['ticket'],7100);<br>
return $res['ticket'];<br>
}<br>
}<br>
public function getjssign(){<br>
echo "<meta>";<br>
$js_ticket = $this->getjsapi_ticket();<br>
$time = time();<br>
$arr = array(<br>
'noncestr'=>md5($time),<br>
'jsapi_ticket'=>$js_ticket,<br>
'timestamp'=>$time,<br>
'url'=>'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],<br>
<br>
);<br>
$this->p($arr);<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br>
$string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
echo $i;<br>
}<br>
// echo $string;<br>
$signature =strtolower($string);<br>
$signature = sha1($string);<br>
$jsconfig = array(<br>
'debug'=>true,<br>
'appId'=>$this->appid,<br>
'timestamp'=>$time,<br>
'nonceStr'=>md5($time),<br>
'signature'=>$signature,<br>
' jsApiList'=>"['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ']",<br>
);<br>
$json = json_encode($jsconfig);<br>
return $json;<br>
}<br>
//生成大写签名<br>
function createsign($arr,$biaozhi){<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br>
$string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
}<br>
$signtemp = "$string&key=" . $this->wechatkey;<br>
$sign = strtoupper(MD5($signtemp));<br>
$arr[$biaozhi] = $sign;<br>
//$json = json_encode($arr);<br>
return $arr;<br>
}<br>
//支付<br>
<br>
//发起支付<br>
public function sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url)<br>
{<br>
$time = time();<br>
$arr = array(<br>
'appid' => $this->appid,<br>
'mch_id' => $this->mchid,<br>
'nonce_str' => md5($time),<br>
'body' => "kjhk",<br>
'out_trade_no' => $out_trade_no,<br>
'total_fee' => $total_fee,<br>
'spbill_create_ip' => "127.0.0.1",<br>
'notify_url' => $notify_url,<br>
'trade_type' => "JSAPI",<br>
'openid' => $openid,<br>
);<br>
$biaozhi ='sign';<br>
$arr = $this->createsign($arr,$biaozhi);<br>
$xml = "<xml>";<br>
foreach ($arr as $key=>$val) {<br>
$xml.="".$val."".$key.">";<br>
}<br>
$xml.="</xml>";<br>
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";<br>
$resxml = $this->postCurlTransfer($url,$xml);<br>
$res = simplexml_load_string($resxml);<br>
$cutime = time();<br>
$jsapiarr=array(<br>
'appId'=>$this->appid,<br>
'timeStamp'=>"$cutime",<br>
'nonceStr'=>md5($cutime),<br>
'package'=>"prepay_id=".$res->prepay_id,<br>
'signType'=>"MD5",<br>
);<br>
$biaozhi = 'paySign';<br>
$jsapi = $this->createsign($jsapiarr,$biaozhi);<br>
// $jsapijson = json_encode($jsapi);<br>
return $jsapi;<br>
}<br>
public function getpaysign(){<br>
$time = time();<br>
$arr = array(<br>
'appid'=>$this->appid,<br>
'mch_id'=>$this->mchid,<br>
'nonce_str'=>md5($time),<br>
'body'=>"sdf",<br>
'out_trade_no'=>"2016".$time,<br>
'total_fee'=>1,<br>
'spbill_create_ip'=>"127.0.0.1",<br>
'notify_url'=>"http://www.baidu.com",<br>
'trade_type'=>"JSAPI",<br>
);<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br>
$string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
}<br>
$string.="&key=".$this->wechatkey;<br>
$sign = strtoupper(md5($string));<br>
$arr['sign'] = $sign;<br>
return $arr;<br>
}<br>
function Post($curlPost,$url){<br>
$curl = curl_init();<br>
curl_setopt($curl, CURLOPT_URL, $url);<br>
curl_setopt($curl, CURLOPT_HEADER, false);<br>
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br>
curl_setopt($curl, CURLOPT_NOBODY, true);<br>
curl_setopt($curl, CURLOPT_POST, true);<br>
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);<br>
$return_str = curl_exec($curl);<br>
curl_close($curl);<br>
return $return_str;<br>
}<br>
private function postCurlTransfer($url, $data)<br>
{<br>
$curl = curl_init();<br>
curl_setopt($curl, CURLOPT_URL, $url);<br>
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);<br>
curl_setopt($curl, CURLOPT_POST, 1);<br>
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);<br>
$str = curl_exec($curl);<br>
curl_close($curl);<br>
<br>
return $str;<br>
}<br>
//发送模板消息<br>
public function sendtpl($openid, $url, $template_id, $content, $topcolor="#FF0000")<br>
{<br>
$arr = array(<br>
'touser' => $openid,<br>
'template_id' => $template_id,<br>
'url' => $url,<br>
'topcolor' => $topcolor,<br>
'data' => $content,<br>
);<br>
$arrjson = json_encode($arr);<br>
$accesstoken = $this->getAccessToken();<br>
$sendurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accesstoken;<br>
return $this->postCurlTransfer($sendurl, $arrjson);<br>
}<br>
}</pre><div class="contentsignin">Copier après la connexion</div></div>
上面的是微信支付简单封装
如果发起支付,请先对应好微信公众号的资料。
包括微信支付目录
我这里是
http://域名//index.php/Home/Index/
好像是这个
获取access_token的过程<?php <br />
/**<br>
* Created by PhpStorm.<br>
* User: sks<br>
* Date: 16/7/8<br>
* Time: 下午3:54<br>
*/<br>
namespace Home\Controller;<br>
use Common\Controller\HomebaseController;<br>
Class WeixinController extends HomebaseController{<br>
public function zhanshi(){<br>
$weixin = new \Org\Weixin;<br>
$code = $_GET['code'];<br>
$state = $_GET['state'];<br>
$url="";<br>
$userinfo = $weixin->jingmo($url, $code, $state);<br>
session('userinfo',$userinfo);<br>
if($code) {<br>
header("Location: $state");<br>
}else{<br>
}<br>
}<br>
}
公共函数
function.phpfunction getuserinfo(){ //获取用户信息<br>
import("weixin");<br>
$weixin = new \Org\Weixin;<br>
$info = session('userinfo');<br>
if($info){<br>
return $info;<br>
die;<br>
}else {<br>
$state = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];<br>
$code = '';<br>
$url = 'http://' . $_SERVER['HTTP_HOST'] . U('Home/Weixin/zhanshi');<br>
$url = urlencode($url);<br>
$weixin->jingmo($url, $code, $state);<br>
}<br>
}
测试支付<?php <br />
/**<br>
* Created by PhpStorm.<br>
* User: sks<br>
* Date: 16/7/8<br>
* Time: 下午3:29<br>
*/<br>
namespace Home\Controller;<br>
use Common\Controller\HomebaseController;<br>
use Think\Page;<br>
Class IndexController extends HomebaseController{<br>
<br>
//测试支付<br>
public function zhifu()<br>
{<br>
$userinfo = getuserinfo(); //获取微信用户信息调用公共函数<br>
$openid = $userinfo['openid'];<br>
$time = time();<br>
$title = "我要支付";<br>
$out_trade_no = date('Y',time()).$time.rand(1000,2000);<br>
$total_fee = 1;<br>
$notify_url = "http://域名/index.php/Home/Index/paynotify";//回调网址<br>
$weixin = new \Org\Weixin;<br>
$result = $weixin->sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url);<br>
$this->assign('result',$result);<br>
$this->display();<br>
}<br>
//这里是支付结果通知<br>
public function paynotify(){<br>
$weixin = new \Org\Weixin;<br>
$xml = file_get_contents("php://input");<br>
$p = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);<br>
$arr = $this->object_array($p);<br>
$out_trade_no = $arr['out_trade_no'];<br>
$transaction_id= $arr['transaction_id'];<br>
$openid = $arr['openid'];<br>
$sign = $arr['sign'];<br>
//处理支付结果<br>
unset($arr['sign']);<br>
$biaozhi = "sign";<br>
$ret = $weixin->createsign($arr, $biaozhi);<br>
if($ret['sign'] === $sign) {<br>
$aa = "成功";<br>
} else {<br>
$aa = "失败";<br>
}<br>
$file = './logweixin.txt';//要写入文件的文件名(可以是任意文件名),如果文件不存在,将会创建一个<br>
$content = $out_trade_no."***".$transaction_id."第一次写入的内容\n";<br>
if($f = file_put_contents($file, $content,FILE_APPEND)){// 这个函数支持版本(PHP 5)<br>
echo "写入成功。<br>";<br>
}<br>
//这里处理支付结果的过程<br>
echo "success";<br>
}<br>
<br>
public function getaccesstoken(){<br>
$weixin = new \Org\Weixin;<br>
echo $weixin->getaccesstoken();<br>
<br>
}<br>
}