微信公众号登陆、模板发送、access_token获取 PHP代码

版权声明:希望不要抄袭,可以借鉴。 https://blog.csdn.net/weixin_37616043/article/details/80930422

微信公众号登陆、模板发送、access_token获取等PHP代码分享

      我现在在项目中遇到要将公众号和小程序联系起来,我们知道,微信公众和小程序在微信开放平台下绑定就可以获得unionid,unionid是否相同就可以 确定用户是否是同一个人,微信小程序开发文档写的很清晰,要想了解详情就点这里(点击打开链接);小程序模板消息我们知道,发送需要formid或者prepay_id,但是formid或者prepay_id是有时间限制,7天,为了弥补这个缺陷,我就想用微信公众号来发送模板消息,因此我就写了这些功能代码,我主要分享一下,公众号登陆,和模板消息TP3.2代码;

代码如下:

public function _initialize(){
     if(!isset($_SESSION["user_id"])||empty($_SESSION["user_id"])){
         //没有登录
         // 去登录;
         $this->login();
     }
 }
 //用户登录
 public function login(){
     $shop_id=18;//店铺id
     $roe=M('wx_gzh_config')->field('appid,appsecret')->where('shop_id='.$shop_id)->find();
     $kf_appid=$roe['appid'];
     $kf_secret=$roe['appsecret'];
     //网页授权
     $code=$_GET['code']?$_GET['code']:"";
     if(empty($code)){
         $urlt="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$kf_appid."&redirect_uri=".urlEncode('http://gw.kxsp.net/Home/GZHao/login')."&response_type=code&scope=snsapi_userinfo&state=12345#wechat_redirect";
         header("location:".$urlt);return;
         // break;
     }else{
         $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$kf_appid."&secret=".$kf_secret."&code=".$code."&grant_type=authorization_code";
         $temXML=$this->CURLSend($url,"get");
         $objd=json_decode($temXML);
         $access_token =$objd->access_token;
         //$access_refresh_token=$objd->refresh_token;
         $openid=$objd->openid;
         //$access_refresh_token_time=date("Y-m-d H:i:s",strtotime("+30 day"));
         $unionid=$objd->unionid;  ///请先到 微信开放平台绑定公众号 后才可以获取 unionid ;
         //检验授权凭证(access_token)是否有效
         $urlu="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
         $temtXML=$this->CURLSend($urlu,"get");
         $objy=json_decode($temtXML);
         $infoList=M('user')->field('gzh_openid,id,unionid')->where(array('unionid'=>$unionid))->find();
         if(!empty($infoList['id'])){
             $timed=date("Y-m-d H:i:s");
             if(!empty($infoList['gzh_openid'])){
                 M('user')->where(array('unionid'=>$unionid))->save(array('time'=>$timed));
             }else{
                 M('user')->where(array('unionid'=>$unionid))->save(array('time'=>$timed,"gzh_openid"=>$openid));
             }
             $user_id=$infoList['id'];
         }else{
             $data['gzh_openid']   = $openid;
             $data['username'] = $objy->nickname;
             $data['sex']      = $objy->sex;
             $data['avater']   = $objy->headimgurl;
             $data['country']  = $objy->country;
             $data['province'] = $objy->province;
             $data['city']     = $objy->city;
             $data['unionid'] = $unionid;
             $data['shop_id'] = 18;
             $data['ctime'] = date("Y-m-d H:i:s");
             $ids=M('user')->add($data);
             $user_id=$ids;
         }
         //echo json_encode($objy);exit;
        }
     $_SESSION["user_id"]=$user_id;
     if($_SESSION["user_id"]){
         $this->redirect("Home/GZHao/index");
     }
    }
 public function index()
 {
         if($_SESSION["user_id"]){
             //unset($_SESSION["user_id"]);
             $info = M("user")->field('gzh_openid')->where('id='.$_SESSION["user_id"])->find();
             $user_name = "舞步天行者";
             $openid = $info["gzh_openid"];
             $time = date("Y-m-d H:i:s");
             $name = "温斯顿";
             $phone = "13926560746";
             if($info["gzh_openid"]){
                 //存在发送消息
                 $myjson=$this->wx_moban($openid,$user_name,$time,$name,$phone);
                 $url_fstzv="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->getAccessToken();
                 $this->CURLSend($url_fstzv,"post",$myjson);
             }
         }

     $this->display();
 }
 public function CURLSend($url, $method = 'get', $data = ''){
     $ch = curl_init();//初始化
     $headers = array('Accept-Charset: utf-8');
     //设置URL和相应的选项
     curl_setopt($ch, CURLOPT_URL, $url);//指定请求的URL
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));//提交方式
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//不验证SSL
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//不验证SSL
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//设置HTTP头字段的数组
     curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible;MSIE5.01;Windows NT 5.0)');//头的字符串

     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     curl_setopt($ch, CURLOPT_AUTOREFERER, 1);//自动设置header中的Referer:信息
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//提交数值
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//是否输出到屏幕上,true不直接输出
     $temp = curl_exec($ch);//执行并获取结果
     curl_close($ch);
     return $temp;//return 返回值
 }
 //微信模板发送
 public function wx_moban($openid,$user_name,$l_name,$url_name,$end_time){
     $wx_mo='{"touser":"'.$openid.'","template_id": "****************","url":"https://zs.kxsp.net/paimai/Api/Shop/","data": {"first": {"value": "尊敬的'.$user_name.'先生,您好!","color":"#173177"},"keyword1": {"value":"'.$l_name.'","color": "#173177"},"keyword2": {"value": "'.$url_name.'","color": "#173177"},"keyword3": {"value": "'.$end_time.'","color": "#173177"},"remark": {"value": "您的预约单已提交成功,我们将于24小时内与您联络并确认预约件的相关内容,请您保持手机畅通,祝您本次消费愉快!。","color": "#173177"}}}';
     return $wx_mo;
 }
//获取access_token,微信调用接口凭据(使用接口需要用到)
//access_token获取频次2000/天,2小时内有效
 public function getAccessToken(){
     $shop_id=18;//店铺id
     $re=M('wx_gzh_config')->where('shop_id='.$shop_id)->find();
     $kf_appid=$re['appid'];
     $kf_secret=$re['appsecret'];
     if($re['expires_in']<time()){
         $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$kf_appid."&secret=".$kf_secret;
         $tmp=$this->CURLSend($url,'get');
         $obj=json_decode($tmp);
         $dty=(time()+$obj->expires_in);
         $data['access_token']=$obj->access_token;
         $data['expires_in']=$dty;
         M('wx_gzh_config')->where('shop_id='.$shop_id)->save($data);
         return $obj->access_token;
     }else {
         return  $re['access_token'];
     }
 }
店铺id是我自己的,查询数据库要按照自己的情况来改我的代码,不要直接复制,template_id是你公众号自己申请的,
有不好地方可以留言,谢谢

猜你喜欢

转载自blog.csdn.net/weixin_37616043/article/details/80930422