>  기사  >  위챗 애플릿  >  WeChat 현금 빨간 봉투 인터페이스는 빨간 봉투 발행을 위한 샘플 코드 공유를 구현합니다.

WeChat 현금 빨간 봉투 인터페이스는 빨간 봉투 발행을 위한 샘플 코드 공유를 구현합니다.

黄舟
黄舟원래의
2017-04-13 10:30:164418검색

WeChat 현금 빨간 봉투 인터페이스는 빨간 봉투 발행을 구현합니다:

1: 프로세스: [

프로세스: WeChat 사용자는 빨간 봉투 활동 페이지에 액세스합니다.--"백엔드가 다음을 결정합니다. WeChat에서 액세스합니다.

[아니요: WeChat을 사용하여 연결을 열 것인지 묻는 메시지, 예: 사용자에게 권한을 부여하고 사용자 정보를 얻을 것인지 묻는 메시지 [openID 및 기타 정보]]--"

빨간 봉투 이벤트 페이지 입장--- 》사용자가 빨간 봉투 받기를 클릭합니다. [빨간 봉투 수신 여부 판단] 예: [빨간 봉투 수신 알림] 아니요

--"백엔드 프로그램이 인터페이스를 호출하여 빨간 봉투를 발행합니다

--"WeChat 사용자는 WeChat에서 빨간 봉투를 받습니다

-->빨간 봉투를 엽니다

-->지갑변경시 빨간봉투 금액이 추가됩니다

-->빨간봉투 배포를 완료하세요.

]

2: 빨간 봉투를 발행하기 위해 WeChat 현금 빨간 봉투 인터페이스를 구현하려면 먼저 다음 조건을 충족해야 합니다.

1. 빨간 봉투 발행은 서비스형이어야 합니다

2. 위챗 공식 플랫폼 공식 홈페이지에 로그인 후, 퍼블릭 플랫폼 백엔드 관리 페이지 - 개발자 센터 페이지

로 이동합니다. "구성 수정" 버튼을 클릭하고 서버 주소(URL), 토큰 및 인코딩AESKey를 입력합니다.

여기서 URL은 개발자가 WeChat 메시지 및 이벤트를 수신하는 데 사용하는 인터페이스 URL입니다. 토큰은 개발자가 임의로 채울 수 있으며,

을 사용하여 서명을 생성합니다(토큰은 인터페이스 URL에 포함된 토큰과 비교하여 보안을 확인합니다).

EncodingAESKey는 개발자가 수동으로 입력하거나 임의로 생성되며 메시지 본문 암호화 및 복호화 키로 사용됩니다.

3. access_token 얻기: 공식 계정은 AppID 및 AppSecret을 사용하여 이 인터페이스를 호출하여 access_token을 얻을 수 있습니다.

[AppID 및 AppSecret은 위챗 공개 플랫폼 공식 홈페이지 - 개발자 센터 페이지에서 받으실 수 있습니다. (개발자 등록이 되어 있어야 하며, 계정에 이상이 없어야 합니다.) 】

4. WeChat 공개 계정은 사용자가 기본 사용자 정보[특히 빨간 봉투를 보낼 때 사용되는 openID]를 얻을 수 있도록 "웹페이지 인증 인터페이스"를 열어야 합니다.

5. WeChat 공개 계정의 "WeChat Pay" ""의 "판매자 ID" WeChat 결제를 활성화하려면 [빨간 봉투 금액이 결제 계정에서 차감됩니다.] "현금 빨간 봉투" 인터페이스를 엽니다. [빨간 봉투를 발행하려면 이 인터페이스를 호출하세요. ].

6. "판매자 계정"[WeChat 공식 계정에서 할당한 판매자 계정]에 로그인합니다. 5장에 안내가 있습니다] "API 보안"에서 PHP 버전의 인증서를 다운로드하세요.

코드의 일부는 다음과 같습니다. [나머지는 첨부파일을 확인해주세요]:

<?php
namespace RedClient\Controller;
use Think\Controller;
use RedClient\Redpack\WeiXinInfo;
use RedClient\Redpack\Oauth;
use RedClient\Redpack\SendRedPack;
use RedClient\Redpack\CreateRedPack;
class IndexController extends Controller 
    {
        public function index()
            {
                $this->isWeixin();//是否是微信打开
                if($this->access)
                    {
                        $this->display();
                         
                    }
                    else
                        {
                            $class=new Oauth();
                            $class->index(&#39;http://www.myweb.com/index.php/Index/oauth&#39;);
                        }
            }
         
        //获取用户信息 openID
        public function oauth()
            {
                $code=isset($_GET[&#39;code&#39;])?strip_tags(trim($_GET[&#39;code&#39;])):&#39;&#39;;
                $state=isset($_GET[&#39;state&#39;])?strip_tags(trim($_GET[&#39;state&#39;])):&#39;&#39;;
                 
                $class=new Oauth();
                $userInfo=$class->getCode($code,$state);//获取用户信息
                if(!empty($userInfo[&#39;data&#39;]))
                    {
                        //$model=M(&#39;wxuser&#39;);
                        //$result=$model->where(&#39;openid = "&#39;.$userInfo[&#39;data&#39;]->openid.&#39;"&#39;)->field(&#39;openid&#39;)->select();
                        if(empty($result))
                            {
                                $userInfo[&#39;data&#39;]=$this->object2array($userInfo[&#39;data&#39;]);
                                $model->data($userInfo[&#39;data&#39;])->add();
                                 
                            }
                    }
                $userInfo[&#39;data&#39;]=$this->object2array($userInfo[&#39;data&#39;]);
                 
                //创建红包
                $class=new CreateRedPack();
                $red=$class->redval();
                 
                //发红包
                $class=new SendRedPack();
                $configs=array(
                        &#39;send_name&#39;=>&#39;红包发送者名称&#39;,//红包发送者名称
                        &#39;re_openid&#39;=>$userInfo[&#39;data&#39;][&#39;openid&#39;],//接受红包的用户,用户在wxappid下的openid
                        &#39;total_amount&#39;=>$red,//付款金额,单位分
                        &#39;total_num&#39;=>&#39;1&#39;,//红包发放总人数
                        &#39;wishing&#39;=>&#39;红包祝福语&#39;,//红包祝福语
                        &#39;client_ip&#39;=>$_SERVER[&#39;SERVER_ADDR&#39;],//调用接口的机器Ip地址
                        &#39;act_name&#39;=>&#39;活动名称&#39;,//活动名称
                        &#39;remark&#39;=>&#39;备注信息&#39;,//  备注信息
                    );
                $class->setFields($configs);
                $result=$class->requestXml();
                 
                //微信返回信息处理
                if(strtoupper($result[&#39;return_code&#39;])==&#39;SUCCESS&#39;)
                    {
                        if(strtoupper($result[&#39;result_code&#39;])==&#39;SUCCESS&#39;)
                            {
                                //红包发送成功!
                                                         
                                $datas[&#39;flag&#39;]=1;
                                echo $result[&#39;err_code_des&#39;];
                            }
                            else
                                {
                                    //红包发送失败
                                    $datas[&#39;flag&#39;]=0;
                                    $datas[&#39;msg&#39;]=$result[&#39;err_code_des&#39;];
                                    echo $result[&#39;err_code_des&#39;];
                                }
                    }
                    else
                        {
                            //红包发送失败
                            $datas[&#39;flag&#39;]=0;
                            $datas[&#39;msg&#39;]=$result[&#39;err_code_des&#39;];
                            echo $result[&#39;err_code_des&#39;];
                        }
            }
         
        public function isWeixin()
            {
                if (strpos($_SERVER[&#39;HTTP_USER_AGENT&#39;], &#39;MicroMessenger&#39;) !== false) 
                    { 
                        $this->access=true; 
                    } 
                return false; 
            }
         
        //类转换成数组
        public function object2array($object) 
            {
              if (is_object($object)) 
                  {
                    foreach ($object as $key => $value) 
                        {
                          $array[$key] = $value;
                        }
                  }
                  else 
                      {
                        $array = $object;
                      }
              return $array;
            }
             
    }
    ?>
<?php
namespace RedClient\Redpack;
/**
    简单红包算法类
**/
class CreateRedPack
    {
        private $rid=0;//当前红包随机数
        private $rand_arr=array();//35%是1.0到1.1 红包随机数
        private $rand_arr1=array();//35%是1.1到1.2 红包随机数
        private $rand_arr2=array();//30%是1.2到1.95 红包随机数
        private $red=0;//红包金额
        private $simplered=0;
        private $red_config=array(
                                array(&#39;min&#39;=>1.0,&#39;max&#39;=>1.1),
                                array(&#39;min&#39;=>1.1,&#39;max&#39;=>1.2),
                                array(&#39;min&#39;=>1.2,&#39;max&#39;=>1.95)
                            );
                             
        public function __construct()
            {
                $this->rid=mt_rand(1,10000);//当前红包随机数
                $this->rand_arr=range(1,3500);//35%是1.0到1.1
                $this->rand_arr1=range(3501,7000);//35%是1.1到1.2
                $this->rand_arr2=range(7001,10000);//30%是1.2到1.95
                $this->simplered=666;
            }
             
        public function redval()
            {
                $maxrp=$this->maxred();//随机最大红包金额
                if($maxrp!=$this->simplered)
                    {
                        if(in_array($this->rid,$this->rand_arr))
                            {
                                $red_val=$this->red_config[0];
                                $min=$red_val[&#39;min&#39;]*100;
                                $max=$red_val[&#39;max&#39;]*100;
                                $this->red=mt_rand($min,$max);
                                $this->red=$this->red/100;
                            }
                            elseif(in_array($this->rid,$this->rand_arr1))
                                {
                                    $red_val=$this->red_config[1];
                                    $min=$red_val[&#39;min&#39;]*100;
                                    $max=$red_val[&#39;max&#39;]*100;
                                    $red=mt_rand($min,$max);
                                    $this->red=$this->red/100;
                                }
                                elseif(in_array($this->rid,$this->rand_arr2))
                                    {
                                        $red_val=$this->red_config[2];
                                        $min=$red_val[&#39;min&#39;]*100;
                                        $max=$red_val[&#39;max&#39;]*100;
                                        $this->red=mt_rand($min,$max);
                                        $this->red=$this->red/100;
                                    }
                    }
                    else
                        {
                            $this->red=$maxrp;
                        }
                return $this->red?$this->red:1;
            }
                 
        protected function maxred()
            {
                $rid=mt_rand(1,100000);
                $rid1=mt_rand(1,100000);
                $red=0;
                $dff=$rid-$rid1;
                 
                if($dff > 0)
                    {
                        if(($rid1%$rid1)==$this->simplered)
                            {
                                $red=$this->simplered;
                            }
                    }
                    else
                        {
                            if(($rid1%$rid)==$this->simplered)
                                {
                                    $red=$this->simplered;
                                }
                        }
                         
                return $red;
            }
    }
 
?>
<?php
namespace RedClient\Redpack;
/*********
 
    先在公共平台配置授权的域名;
    然后才能通过,
    网页授权方式获取微信用户基本信息
     
    网页授权流程分为四步: 
 
    1.引导用户进入授权页面同意授权,获取code 
    2.通过code换取网页授权access_token(与基础支持中的access_token不同) 
    3.如果需要,开发者可以刷新网页授权access_token,避免过期 
    4.通过网页授权access_token和openid获取用户基本信息 
 
**********/
class Oauth
    {
        protected $appid=&#39;&#39;;
        protected $redirect_uri=&#39;&#39;;
        protected $state=&#39;&#39;;//mt_rand(100,999);
        protected $appsecret=&#39;&#39;;
        protected $data=array(&#39;flag&#39;=>0,&#39;msg&#39;=>&#39;&#39;,&#39;data&#39;=>&#39;&#39;);
         
         
        public function __construct()
            {
                $this->appid=&#39;appid&#39;;//
                $this->appsecret=&#39;secret&#39;;//;
                $this->state=mt_rand(100,999);
            }
             
        //引导用户访问链接处理函数 
        public function index($redirect_uri)
            {
                $this->redirect_uri=urlencode($redirect_uri);//微信自动跳转到$redirect_uri
                header(&#39;location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=&#39;.$this->appid.&#39;&redirect_uri=&#39;.$this->redirect_uri.&#39;/oauth.php&response_type=code&scope=snsapi_userinfo&state=&#39;.$this->state.&#39;&connect_redirect=1#wechat_redirect&#39;);
            }
             
        public function getCode($code=&#39;&#39;,$state=&#39;&#39;,$token=&#39;&#39;,$webToken=&#39;&#39;)
            {
                $data=array(
                    &#39;errorno&#39;=>&#39;&#39;,
                    &#39;errormsg&#39;=>&#39;&#39;,
                    &#39;data&#39;=>&#39;&#39;
                );
                 
                if(empty($code))
                    {
                        $this->data[&#39;flag&#39;]=0;
                        $this->data[&#39;msg&#39;]=&#39;授权失败!&#39;;
                    }
                    else
                        {   /* 
                                 
                                1获取webtoken
                                2获取reflash_token
                                3获取用户信息 
                            */
  $token_url = &#39;https://api.weixin.qq.com/sns/oauth2/access_token?appid=&#39;.$this->appid.&#39;&secret=&#39;.$this->appsecret.&#39;&code=&#39;.$code.&#39;&grant_type=authorization_code&#39;;
                         $token = json_decode(file_get_contents($token_url));
                             
                            if (isset($token->errcode)) 
                                {
                                    $data[&#39;errorno&#39;]=$token->errcode;
                                    $data[&#39;errormsg&#39;]=$token->errmsg;
                                }
                                else
                                    {
  $access_token_url = &#39;https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=&#39;.$this->appid.&#39;&grant_type=refresh_token&refresh_token=&#39;.$token->refresh_token;
                                        //转成对象
                                        $accessToken = json_decode(file_get_contents($access_token_url));
                                         
                                        if (isset($accessToken->errcode)) 
                                            {
                                                $data[&#39;errorno&#39;]=$token->errcode;
                                                $data[&#39;errormsg&#39;]=$token->errmsg;
                                            }
                                            else
                                                {
     $user_info_url = &#39;https://api.weixin.qq.com/sns/userinfo?access_token=&#39;.$accessToken->access_token.&#39;&openid=&#39;.$accessToken->openid.&#39;&lang=zh_CN&#39;;
                                                    //转成对象
                                                    $userInfo = json_decode(file_get_contents($user_info_url));
                                                     
                                                    if (isset($userInfo->errcode)) 
                                                        {
                                                            $data[&#39;errorno&#39;]=$token->errcode;
                                                            $data[&#39;errormsg&#39;]=$token->errmsg;
                                                        }
                                                        else
                                                            {
                                                                $data[&#39;data&#39;]=$userInfo;
                                                            }
                                                }
                                    }
                        }
                return $data;
            }
             
    }
 
?>
<?php
/******
 
    用于企业向微信用户个人发现金红包
    目前支持向指定微信用户的openid发放指定金额红包。
    (获取openid参见微信公众平台开发者文档:
    网页授权获取用户基本信息)
     
****/
namespace RedClient\Redpack;
 
class SendRedPack
    {
        private $config=array(
            &#39;nonce_str&#39;=>&#39;&#39;,//随机字符串,不长于32位
            &#39;sign&#39;=>&#39;&#39;,//签名
            &#39;mch_billno&#39;=>&#39;&#39;,//商户订单号
            &#39;mch_id&#39;=>&#39;1111sdfsafsaddf&#39;,//微信支付分配的商户号
            &#39;wxappid&#39;=>&#39;sddafdsadfdsafdsdd&#39;,//微信分配的公众账号ID
            &#39;send_name&#39;=>&#39;&#39;,//红包发送者名称
            &#39;re_openid&#39;=>&#39;&#39;,//接受红包的用户,用户在wxappid下的openid
            &#39;total_amount&#39;=>&#39;&#39;,//付款金额,单位分
            &#39;total_num&#39;=>&#39;&#39;,//红包发放总人数
            &#39;wishing&#39;=>&#39;&#39;,//红包祝福语
            &#39;client_ip&#39;=>&#39;&#39;,//调用接口的机器Ip地址
            &#39;act_name&#39;=>&#39;&#39;,//活动名称
            &#39;remark&#39;=>&#39;&#39;,//  备注信息
        );
         
        protected $key=&#39;&#39;;
        protected $url=&#39;https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack&#39;;
        protected $requestXml=&#39;&#39;;
         
        //设置必要参数
        public function setFields($conf=array())
            {
                foreach($conf as $k=>$v)
                    {
                        if(isset($this->config[$k]) && !empty($v))
                            {
                                $this->config[$k]=$v;
                            }
                    }
                $this->config[&#39;mch_billno&#39;]=$this->billno();
                $this->config[&#39;nonce_str&#39;]=$this->createNonceStr();
                $this->createSign($conf);
                $this->createXml();
                //echo $this->requestXml;
            }
         
        protected function billno()
            {
                return $this->config[&#39;mch_id&#39;].time().md5(mt_rand(1000,9999));
            }
         
        /* //检查必要参数是否为空!
        public function checkConfig()
            {
                $flag=true;
                foreach($this->config as $k=>$v)
                    {
                        if(empty($v))
                            {
                                $flag=false;
                                break;
                            }
                    }
            } */
         
        //随机字符串,不长于32位
        public function createNonceStr( $len=32 )
            {
                $strs = "abcdefghijklmnopqrstuvwxyz0123456789";
                $str ="";
                $len=$len<=32?$len:32;
                for ( $i = 0; $i < $len; $i++ )
                    {
                      $str.= substr($strs, mt_rand(0, strlen($strs)-1), 1);
                    }
                return $str;
            }
             
        //格式化参数
        public function formatParam($config=array(),$flag=1)
            {
                $format=&#39;&#39;;
                if(!empty($config))
                    {
                        ksort($config);
                        foreach($config as $k=>$v)
                            {
                                if($flag)
                                    {
                                        $v=urlencode($v);
                                    }
                                     
                                    if($flag==0 && strtolower($k)==&#39;sign&#39;)
                                        {
                                            continue;
                                        }
                                $format.=$k.&#39;=&#39;.$v.&#39;&&#39;;
                            }
                        $format=trim($format,&#39;&&#39;);
                    }
                return $format;
            }
             
        //创建SIGNATURE  
        protected function createSign($config)
            {
                $format=$this->formatParam($config,0);
                $format.=&#39;&key=&#39;.$this->key;
                $signature=strtoupper(md5($format));
                $this->config[&#39;sign&#39;]=$signature;
                return true;//$signature;
            }
             
        //创建xml格式数据
        protected function createXml()
            {
                $xml=&#39;<xml>&#39;;
                foreach($this->config as $k=>$v)
                    {
                        if(!empty($v))
                            {
                                $xml.=&#39;<&#39;.$k.&#39;><![CDATA[&#39;.$v.&#39;]]></&#39;.$k.&#39;>&#39;;
                            }
                    }
                $xml.=&#39;</xml>&#39;;
                $this->requestXml=$xml;
            }
         
        //XML格式数据转换为数组
        public function createArray($xml=&#39;&#39;)
            {
                $arr = json_decode(json_encode(simplexml_load_string($xml, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA)), true);
                return $arr;
            }
         
        //发送红包
        public function requestXml($timeout=30,$header=array())
            {
                $ch = curl_init();
                //超时时间
                curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch,CURLOPT_URL,$this->url);
                curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
                curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
                //默认格式为PEM,可以注释
                curl_setopt($ch,CURLOPT_SSLCERTTYPE,&#39;PEM&#39;);
                curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).&#39;/apiclient_cert.pem&#39;);//pem证书地址
                //默认格式为PEM,可以注释
                curl_setopt($ch,CURLOPT_SSLKEYTYPE,&#39;PEM&#39;);
                curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).&#39;/apiclient_key.pem&#39;);//key证书地址
                curl_setopt($ch,CURLOPT_CAINFO,&#39;PEM&#39;);
                curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).&#39;/rootca.pem&#39;);//CA证书地址
                //两个文件合成一个.pem文件
                //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().&#39;/all.pem&#39;);
                if( count($header) >= 1 )
                    {
                        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                    }
                curl_setopt($ch,CURLOPT_POST, 1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,$this->requestXml);
                $data = curl_exec($ch);
                var_dump($data);
                if($data)
                    {
                        curl_close($ch);
                        var_dump($data);
                        return $data;
                    }
                    else 
                        {
                            $error = curl_errno($ch);
                            echo &#39;ERROR:&#39;.$error;
                            curl_close($ch);
                            return false;
                        }
            }
         
        //返回非空值,非NULL
        public function notEmpty($val=&#39;&#39;)
            {
                $return=&#39;&#39;;
                if(null !=$val && strlen($val) != 0)
                    {
                        $return=$val;
                    }
                return $return?$return:false;
            }
         
    }
 
 
?>
<?php
namespace RedClient\Redpack;
class WeiXinInfo
    {
        private $AppID=&#39;appid&#39;;
        private $AppSecret=&#39;secret&#39;;
        private $grant_type=&#39;client_credential&#39;;
         
        private $url=&#39;https://api.weixin.qq.com/cgi-bin/token&#39;;
         
        public function __construct()
            {
                //$arr=array(&#39;access_token&#39;=>&#39;1&#39;,&#39;expires&#39;=>&#39;7200&#39;);
                 
            }
             
        //设置获取ACCESSTOKEN 的URL
        public function setUrl()
            {
                return $this->url=$this->url.&#39;?grant_type=&#39;.$this->grant_type.&#39;&appid=&#39;.$this->AppID.&#39;&secret=&#39;.$this->AppSecret;
            }
         
        //获取APPID,SECRET
        public function getAppid()
            {
                $sql=&#39;select appid,secret from ly_appid where flag=1&#39;;
                $model=M();
                $result=$model->query($sql);
                if(!empty($result))
                    {
                        $this->AppID=$result[0][&#39;appid&#39;];
                        $this->AppSecret=$result[0][&#39;secret&#39;];
                        return $result[0];
                    }
            }
             
        public function object2array($object) 
            {
              if (is_object($object)) 
                  {
                    foreach ($object as $key => $value) 
                        {
                          $array[$key] = $value;
                        }
                  }
                  else 
                      {
                        $array = $object;
                      }
              return $array;
            }
             
        //检验URL有效
        public function checkUrl()
            {
                $signature=isset($_GET[&#39;signature&#39;])?strip_tags(trim($_GET[&#39;signature&#39;])):&#39;&#39;;
                $timestamp=isset($_GET[&#39;timestamp&#39;])?strip_tags(trim($_GET[&#39;timestamp&#39;])):&#39;&#39;;
                $nonce=isset($_GET[&#39;nonce&#39;])?strip_tags(trim($_GET[&#39;nonce&#39;])):&#39;&#39;;
                $echostr=isset($_GET[&#39;echostr&#39;])?$_GET[&#39;echostr&#39;]:&#39;&#39;;
                if(!empty($signature) && !empty($timestamp) && !empty($nonce))
                    {
                        if($this->checkSign($signature,$timestamp,$nonce))
                            {
                                echo $echostr;
                                return true;
                            }
                            else
                                {
                                    return false;
                                }
                    }
            }  
             
        //验证SIGNATURE是否有效
        private function checkSign($sign,$timestamp,$nonce)
            {
                $token=$this->getAccessToken();
                //$token=$this->object2array($token);
                $sign_arr=array($token,$timstamp,$nonce);
                sort($sign_arr,SORT_STRING);
                $signStr=implode($sign_arr);
                $signStr=sha1($signStr);
                if(strtoupper($signStr)==strtoupper($sign))
                    {
                        return true;
                    }
                return false;
            }
             
        //通过微信接口获取微信Access_Token   
        public function getAccessToken()
            {
                $token=&#39;&#39;;
                $this->setUrl();
                $check=$this->checkToken();
                 
                if(session(&#39;?&#39;.md5(&#39;getaccesstoken&#39;)) && $check)
                    {
                        $tokens=session(md5(&#39;getaccesstoken&#39;));
                        $token=$tokens->access_token;
                    }
                    else
                        {
                            $result=file_get_contents($this->url);
                            $result=json_decode($result);
                            $token=$result->access_token;
                            $result->expires_in=$result->expires_in+time();
                            session(md5(&#39;getaccesstoken&#39;),$result);
                        }
                         
                return $token;
            }
         
        //检查微信ACCESS_TOKEN是否有效
        public function checkToken()
            {
                if(session(&#39;?&#39;.md5(&#39;getaccesstoken&#39;)) && session(md5(&#39;getaccesstoken&#39;)))
                    {
                        $time=time();
                        $token=session(md5(&#39;getaccesstoken&#39;));
                         
                        if($token->expires_in-$time > 30)
                            {
                                return true;
                            }
                            else
                                {
                                    session(md5(&#39;getaccesstoken&#39;),null);
                                }
                    }
                return false;
            }
             
        //保存微信ACCESSTOKEN到数据库  
        public function saveAccessToken()
            {
                $token=$this->getAccessToken();
                $sql=&#39;select `id`,`rate`,token,ex_time,createtime from ly_token where token="&#39;.$token.&#39;" where appid="&#39;.$this->AppID.&#39;" AND secret="&#39;.$this->AppSecret.&#39;"&#39;;
                $model=M();
                $result=$model->query($sql);
                if(!empty($result))
                    {
                        $time=time();
                        $expires=$time-$result[0][&#39;createtime&#39;];
                        if($result[0][&#39;ex_time&#39;]-$expires > 0)
                            {
                                return $result[0][&#39;token&#39;];                       
                            }
                            else
                                {
                                    $token=$this->getAccessToken();
                                    if(!empty($token))
                                        {
                                            $token=json_decode($token);
                                            if(!isset($token[&#39;errcode&#39;]) or !$token[&#39;errcode&#39;])
                                                {
                                                    if(isset($token[&#39;access_token&#39;]) && $token[&#39;access_token&#39;])
                                                        {
                                                            $data[&#39;access_token&#39;]=$token[&#39;access_token&#39;];
                                                            $data[&#39;createtime&#39;]=$time;
                                                            $data[&#39;ex_time&#39;]=$token[&#39;expires_in&#39;];
                                                            $data[&#39;rate&#39;]=$result[0][&#39;rate&#39;]+1;
                                                            //$sql=&#39;update ly_token set token="&#39;.$token[&#39;access_token&#39;].&#39;" ,createtime=&#39;.$time.&#39;,ex_time=&#39;.$token[&#39;expires_in&#39;].&#39; where `id`=&#39;.$result[0][&#39;id&#39;];
                                                            $model=M(&#39;token&#39;);
                                                            $update=$model->where(&#39;`id`=&#39;.$result[0][&#39;id&#39;])->save($data);
                                                            if($update)
                                                            {
                                                                return $token[&#39;access_token&#39;];
                                                            }
                                                        }
                                                }
                                                else
                                                    {//微信返回的错误信息
                                                                $data[&#39;errcode&#39;]=$token[&#39;errcode&#39;];
                                                                $data[&#39;errmsg&#39;]=$token[&#39;errmsg&#39;];
                                                                $data[&#39;appid&#39;]=$this->AppID;
                                                                $data[&#39;secret&#39;]=$this->AppSecret;
                                                                $data[&#39;createtime&#39;]=time();
                                                                $data[&#39;rate&#39;]=$result[0][&#39;rate&#39;]+1;
                                                                $ein=$model->where(&#39;`id`=&#39;.$result[0][&#39;id&#39;])->save($data);
                                                                if($ein)
                                                                    {
                                                                        return false;
                                                                    }
                                                    }
                                        }
                                }
                    }
                    else
                        {//新插入数据库保存
                            $token=$this->getAccessToken();
                            $model=M(&#39;token&#39;);
                            if(!empty($token))
                                        {
                                            $data=array();
                                            $token=json_decode($token);
                                            if(!isset($token[&#39;errcode&#39;]) or !$token[&#39;errcode&#39;])
                                                {
                                                    if(isset($token[&#39;access_token&#39;]) && $token[&#39;access_token&#39;])
                                                        {
                                                            $data[&#39;access_token&#39;]=$token[&#39;access_token&#39;];
                                                            $data[&#39;createtime&#39;]=$time;
                                                            $data[&#39;ex_time&#39;]=$token[&#39;expires_in&#39;];
                                                            //$sql=&#39;insert into ly_token() vlaues()&#39;;
                                                            $data[&#39;rate&#39;]=1;
                                                            $in=$model->data($data)->add();
                                                            if($ein)
                                                            {
                                                                $token[&#39;access_token&#39;];
                                                            }
                                                        }
                                                }
                                                else
                                                    {//微信返回的错误信息
                                                        $data[&#39;errcode&#39;]=$token[&#39;errcode&#39;];
                                                        $data[&#39;errmsg&#39;]=$token[&#39;errmsg&#39;];
                                                        $data[&#39;appid&#39;]=$this->AppID;
                                                        $data[&#39;secret&#39;]=$this->AppSecret;
                                                        $data[&#39;createtime&#39;]=time();
                                                        $data[&#39;rate&#39;]=1;
                                                        $ein=$model->data($data)->add();
                                                        if($ein)
                                                            {
                                                                return false;
                                                            }
                                                    }
                                        }
                        }
                return false;
            }  
             
             
             
             
             
    }
 
?>

위 내용은 WeChat 현금 빨간 봉투 인터페이스는 빨간 봉투 발행을 위한 샘플 코드 공유를 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.