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