Rumah > php教程 > php手册 > 2016封装的微信支付,太好用了

2016封装的微信支付,太好用了

WBOY
Lepaskan: 2016-08-04 08:56:20
asal
1533 orang telah melayarinya

一直在做微信,遇到过很多坑,今天写出来,让大家少走点弯路,第一次写文字,有点土,如果有不懂的童鞋,可以联系我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">&quot;;&lt;br&gt;         print_r($arr);&lt;br&gt;     }&lt;br&gt;     function curlget($url)&lt;br&gt;     {&lt;br&gt;         $ch = curl_init();&lt;br&gt;         curl_setopt($ch, CURLOPT_URL, $url);&lt;br&gt;         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);&lt;br&gt;         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);&lt;br&gt;         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);&lt;br&gt;         curl_setopt($ch, CURLOPT_HEADER, 0);&lt;br&gt;         $output = curl_exec($ch);&lt;br&gt;         curl_close($ch);&lt;br&gt;         return $output;&lt;br&gt;     }&lt;br&gt;     public function jingmo($url,$code,$state){&lt;br&gt;         if($code){&lt;br&gt;             $url = &quot;https://api.weixin.qq.com/sns/oauth2/access_token?appid=&quot;.$this-&gt;appid.&quot;&amp;secret=&quot;.$this-&gt;appsecret.&quot;&amp;code=&quot;.$code.&quot;&amp;grant_type=authorization_code&quot;;&lt;br&gt;             $arrtemp = json_decode($this-&gt;curlget($url),true);&lt;br&gt;             $ret = $this-&gt;getuserinfo($arrtemp['openid'],$arrtemp['access_token']);&lt;br&gt;             return  $ret;&lt;br&gt;         }else{&lt;br&gt;             $url = &quot;https://open.weixin.qq.com/connect/oauth2/authorize?appid=&quot;.$this-&gt;appid.&quot;&amp;redirect_uri=&quot;.$url.&quot;&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state=&quot;.$state.&quot;#wechat_redirect&quot;;&lt;br&gt;             header(&quot;Location: $url&quot;);&lt;br&gt;         }&lt;br&gt;     }&lt;br&gt;     public function getuserinfo($openid,$user_access_token){&lt;br&gt;         $userurl = &quot;https://api.weixin.qq.com/sns/userinfo?access_token=&quot;.$user_access_token.&quot;&amp;openid=&quot;.$openid.&quot;&amp;lang=zh_CN&quot;;&lt;br&gt;         $userinfo = json_decode($this-&gt;curlget($userurl),true);&lt;br&gt;         return $userinfo;&lt;br&gt;     }&lt;br&gt;     public function getjsapi_ticket(){&lt;br&gt;         $js_ticket = S(&quot;js_ticket&quot;);&lt;br&gt;         if(!empty($js_ticket)){&lt;br&gt;             return $js_ticket;&lt;br&gt;         }else{&lt;br&gt;             $access_token = $this-&gt;getaccesstoken();&lt;br&gt;             $url = &quot;https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=&quot;.$access_token.&quot;&amp;type=jsapi&quot;;&lt;br&gt;             $res = json_decode($this-&gt;curlget($url),true);&lt;br&gt;             S(&quot;js_ticket&quot;,$res['ticket'],7100);&lt;br&gt;             return $res['ticket'];&lt;br&gt;         }&lt;br&gt;     }&lt;br&gt;     public function getjssign(){&lt;br&gt;         echo &quot;&lt;meta&gt;&quot;;&lt;br&gt;         $js_ticket = $this-&gt;getjsapi_ticket();&lt;br&gt;         $time = time();&lt;br&gt;         $arr = array(&lt;br&gt;             'noncestr'=&gt;md5($time),&lt;br&gt;             'jsapi_ticket'=&gt;$js_ticket,&lt;br&gt;             'timestamp'=&gt;$time,&lt;br&gt;             'url'=&gt;'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],&lt;br&gt; &lt;br&gt;         );&lt;br&gt;         $this-&gt;p($arr);&lt;br&gt;         ksort($arr);&lt;br&gt;         $string=&quot;&quot;;&lt;br&gt;         $i=1;&lt;br&gt;         foreach($arr as $key=&gt;$val){&lt;br&gt;             if($i==1){&lt;br&gt;                 $string.=$key.&quot;=&quot;.$val;&lt;br&gt;             }else{&lt;br&gt;                 $string.=&quot;&amp;&quot;.$key.&quot;=&quot;.$val;&lt;br&gt;             }&lt;br&gt;             $i++;&lt;br&gt;             echo $i;&lt;br&gt;         }&lt;br&gt;         // echo $string;&lt;br&gt;         $signature =strtolower($string);&lt;br&gt;         $signature =  sha1($string);&lt;br&gt;         $jsconfig = array(&lt;br&gt;             'debug'=&gt;true,&lt;br&gt;             'appId'=&gt;$this-&gt;appid,&lt;br&gt;             'timestamp'=&gt;$time,&lt;br&gt;             'nonceStr'=&gt;md5($time),&lt;br&gt;             'signature'=&gt;$signature,&lt;br&gt;             ' jsApiList'=&gt;&quot;['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ']&quot;,&lt;br&gt;         );&lt;br&gt;         $json = json_encode($jsconfig);&lt;br&gt;         return $json;&lt;br&gt;     }&lt;br&gt;     //生成大写签名&lt;br&gt;     function createsign($arr,$biaozhi){&lt;br&gt;         ksort($arr);&lt;br&gt;         $string=&quot;&quot;;&lt;br&gt;         $i=1;&lt;br&gt;         foreach($arr as $key=&gt;$val){&lt;br&gt;             if($i==1){&lt;br&gt;                 $string.=$key.&quot;=&quot;.$val;&lt;br&gt;             }else{&lt;br&gt;                 $string.=&quot;&amp;&quot;.$key.&quot;=&quot;.$val;&lt;br&gt;             }&lt;br&gt;             $i++;&lt;br&gt;         }&lt;br&gt;         $signtemp = &quot;$string&amp;key=&quot; . $this-&gt;wechatkey;&lt;br&gt;         $sign = strtoupper(MD5($signtemp));&lt;br&gt;         $arr[$biaozhi] = $sign;&lt;br&gt;         //$json = json_encode($arr);&lt;br&gt;         return $arr;&lt;br&gt;     }&lt;br&gt;     //支付&lt;br&gt; &lt;br&gt;     //发起支付&lt;br&gt;     public function sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url)&lt;br&gt;     {&lt;br&gt;         $time = time();&lt;br&gt;         $arr = array(&lt;br&gt;             'appid' =&gt; $this-&gt;appid,&lt;br&gt;             'mch_id' =&gt; $this-&gt;mchid,&lt;br&gt;             'nonce_str' =&gt; md5($time),&lt;br&gt;             'body' =&gt; &quot;kjhk&quot;,&lt;br&gt;             'out_trade_no' =&gt; $out_trade_no,&lt;br&gt;             'total_fee' =&gt; $total_fee,&lt;br&gt;             'spbill_create_ip' =&gt; &quot;127.0.0.1&quot;,&lt;br&gt;             'notify_url' =&gt; $notify_url,&lt;br&gt;             'trade_type' =&gt; &quot;JSAPI&quot;,&lt;br&gt;             'openid' =&gt; $openid,&lt;br&gt;         );&lt;br&gt;         $biaozhi ='sign';&lt;br&gt;         $arr = $this-&gt;createsign($arr,$biaozhi);&lt;br&gt;         $xml = &quot;&lt;xml&gt;&quot;;&lt;br&gt;         foreach ($arr as $key=&gt;$val) {&lt;br&gt;             $xml.=&quot;&quot;.$val.&quot;&quot;.$key.&quot;&gt;&quot;;&lt;br&gt;         }&lt;br&gt;         $xml.=&quot;&lt;/xml&gt;&quot;;&lt;br&gt;         $url = &quot;https://api.mch.weixin.qq.com/pay/unifiedorder&quot;;&lt;br&gt;         $resxml =  $this-&gt;postCurlTransfer($url,$xml);&lt;br&gt;         $res = simplexml_load_string($resxml);&lt;br&gt;         $cutime = time();&lt;br&gt;         $jsapiarr=array(&lt;br&gt;             'appId'=&gt;$this-&gt;appid,&lt;br&gt;             'timeStamp'=&gt;&quot;$cutime&quot;,&lt;br&gt;             'nonceStr'=&gt;md5($cutime),&lt;br&gt;             'package'=&gt;&quot;prepay_id=&quot;.$res-&gt;prepay_id,&lt;br&gt;             'signType'=&gt;&quot;MD5&quot;,&lt;br&gt;         );&lt;br&gt;         $biaozhi = 'paySign';&lt;br&gt;         $jsapi = $this-&gt;createsign($jsapiarr,$biaozhi);&lt;br&gt;        // $jsapijson = json_encode($jsapi);&lt;br&gt;         return $jsapi;&lt;br&gt;     }&lt;br&gt;     public function getpaysign(){&lt;br&gt;         $time = time();&lt;br&gt;         $arr = array(&lt;br&gt;             'appid'=&gt;$this-&gt;appid,&lt;br&gt;             'mch_id'=&gt;$this-&gt;mchid,&lt;br&gt;             'nonce_str'=&gt;md5($time),&lt;br&gt;             'body'=&gt;&quot;sdf&quot;,&lt;br&gt;             'out_trade_no'=&gt;&quot;2016&quot;.$time,&lt;br&gt;             'total_fee'=&gt;1,&lt;br&gt;             'spbill_create_ip'=&gt;&quot;127.0.0.1&quot;,&lt;br&gt;             'notify_url'=&gt;&quot;http://www.baidu.com&quot;,&lt;br&gt;             'trade_type'=&gt;&quot;JSAPI&quot;,&lt;br&gt;         );&lt;br&gt;         ksort($arr);&lt;br&gt;         $string=&quot;&quot;;&lt;br&gt;         $i=1;&lt;br&gt;         foreach($arr as $key=&gt;$val){&lt;br&gt;             if($i==1){&lt;br&gt;                 $string.=$key.&quot;=&quot;.$val;&lt;br&gt;             }else{&lt;br&gt;                 $string.=&quot;&amp;&quot;.$key.&quot;=&quot;.$val;&lt;br&gt;             }&lt;br&gt;             $i++;&lt;br&gt;         }&lt;br&gt;         $string.=&quot;&amp;key=&quot;.$this-&gt;wechatkey;&lt;br&gt;         $sign = strtoupper(md5($string));&lt;br&gt;         $arr['sign'] = $sign;&lt;br&gt;         return $arr;&lt;br&gt;     }&lt;br&gt;     function Post($curlPost,$url){&lt;br&gt;         $curl = curl_init();&lt;br&gt;         curl_setopt($curl, CURLOPT_URL, $url);&lt;br&gt;         curl_setopt($curl, CURLOPT_HEADER, false);&lt;br&gt;         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);&lt;br&gt;         curl_setopt($curl, CURLOPT_NOBODY, true);&lt;br&gt;         curl_setopt($curl, CURLOPT_POST, true);&lt;br&gt;         curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);&lt;br&gt;         $return_str = curl_exec($curl);&lt;br&gt;         curl_close($curl);&lt;br&gt;         return $return_str;&lt;br&gt;     }&lt;br&gt;     private function postCurlTransfer($url, $data)&lt;br&gt;     {&lt;br&gt;         $curl = curl_init();&lt;br&gt;         curl_setopt($curl, CURLOPT_URL, $url);&lt;br&gt;         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);&lt;br&gt;         curl_setopt($curl, CURLOPT_POST, 1);&lt;br&gt;         curl_setopt($curl, CURLOPT_POSTFIELDS, $data);&lt;br&gt;         $str = curl_exec($curl);&lt;br&gt;         curl_close($curl);&lt;br&gt; &lt;br&gt;         return $str;&lt;br&gt;     }&lt;br&gt;     //发送模板消息&lt;br&gt;     public function sendtpl($openid, $url, $template_id, $content, $topcolor=&quot;#FF0000&quot;)&lt;br&gt;     {&lt;br&gt;         $arr = array(&lt;br&gt;             'touser' =&gt; $openid,&lt;br&gt;             'template_id' =&gt; $template_id,&lt;br&gt;             'url' =&gt; $url,&lt;br&gt;             'topcolor' =&gt; $topcolor,&lt;br&gt;             'data' =&gt; $content,&lt;br&gt;         );&lt;br&gt;         $arrjson = json_encode($arr);&lt;br&gt;         $accesstoken = $this-&gt;getAccessToken();&lt;br&gt;         $sendurl = &quot;https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=&quot;.$accesstoken;&lt;br&gt;         return $this-&gt;postCurlTransfer($sendurl, $arrjson);&lt;br&gt;     }&lt;br&gt; }</pre><div class="contentsignin">Salin selepas log masuk</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> }

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Cadangan popular
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan