thinkphp5接入公众号获取用户信息

最近看挺多人问这个接入流程的,大部分不是很完整,我给大家写一下,大家可以看下。
一.首先把自己设为开发者在这里插入图片描述
二.配置公众号
1.开发者密码一定要保存,之后是看不到的
2.白名单一定要把自己服务的ip放里面
3.服务器地址要和下面文件ping通,不然通过不了
在这里插入图片描述

<?php

define("TOKEN", "写上面自己填的token");//自己定义的token 就是个通信的私钥

$wechatObj = new wechatCallbackapiTest();

$wechatObj->valid();

//$wechatObj->responseMsg();

class wechatCallbackapiTest

{

    public function valid()

    {

        $echoStr = $_GET["echostr"];

        if($this->checkSignature()){

            echo $echoStr;

            exit;

        }

    }

    public function responseMsg()

    {

        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)){

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            $fromUsername = $postObj->FromUserName;

            $toUsername = $postObj->ToUserName;

            $keyword = trim($postObj->Content);

            $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 = '你好啊';

                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);

                echo $resultStr;

            }else{

                echo '说说话吧';

            }

        }else {

            echo '说说话吧';

            exit;

        }

    }

    private function checkSignature()

    {

        $signature = $_GET["signature"];

        $timestamp = $_GET["timestamp"];

        $nonce = $_GET["nonce"];

        $token =TOKEN;

        $tmpArr = array($token, $timestamp, $nonce);

        sort($tmpArr);

        $tmpStr = implode( $tmpArr );

        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){

            return true;

        }else{

            return false;

        }

    }

}

?>

晚上把登入和微信获取openid绑定再一起写了,大家可以参考一下

<?php
namespace app\index\controller;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Session;

class Userlogin extends controller
{

	// 登录页面
    public function index()
    {

        if(Session::has('admin') == false) {
            if($this->request->isPost()) {
                //是登录操作
                $post = $this->request->post();
                //验证  唯一规则: 表名,字段名,排除主键值,主键名
                $validate = new \think\Validate([
                    ['username', 'require|alphaDash', '用户名不能为空|用户名格式只能是字母、数字、——或_'],
                    ['password', 'require', '密码不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                   return  $this->bejson('500','提交失败:' . $validate->getError());

                }
                $name = Db::name('admin')->where('name',$post['username'])->find();
                if(empty($name)) {
                    //不存在该用户名
                    return $this->bejson('500','用户名不存在');
                } else {
                    //验证密码
                    $post['password'] = $this->password($post['password']);
                    if($name['password'] != $post['password']) {
                        return $this->bejson('500','密码错误');
                    } else {
                        Session::set("admin",$name['id']); //保存新的
                        Session::set("admin_cate_id",$name['admin_cate_id']); //保存新的
                        //记录登录时间和ip
                        Db::name('admin')->where('id',$name['id'])->update(['login_ip' =>  $this->request->ip(),'login_time' => time()]);
                        if($name['open_id']){
                            return $this->bejson('200','登录成功,正在跳转...');
                        }else{
                            return $this->bejson('201','登录成功,未绑定Openid');
                        }
                    }
                }
            } else {
                return $this->fetch();
            }
        }else {
            $this->redirect('member/index');
       }
    }

    //获取微信授权
    public function authorize(){

        header("Content-type: text/html; charset=utf-8");

        if(Session::has('admin')) {
            $user_member = Session::get('admin');
            if(!isset($_GET['code'])){
                $REDIRECT_URI= 'http://'.$_SERVER['HTTP_HOST'].'/index/userlogin/authorize';
                $scope='snsapi_base';
                $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('appid').'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state=wx'.'#wechat_redirect';
				//获取code
                $this->redirect($url);
                exit;
            }else{
                $code = $_GET["code"];
                $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('appid').'&secret='.config('appsecret').'&code='.$code.'&grant_type=authorization_code';
                $ch = curl_init();
                curl_setopt($ch,CURLOPT_URL,$get_token_url);
                curl_setopt($ch,CURLOPT_HEADER,0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                $res = curl_exec($ch);
                curl_close($ch);
                $json_obj = json_decode($res,true);
                //根据openid和access_token查询用户信息
                $access_token = $json_obj['access_token'];
                $openid = $json_obj['openid'];
                if($openid){
                    $name = Db::name('admin')->where('id',$user_member)->find();
                    if($name){
						//更新管理员openid
                        $update = Db::name('admin')->where('id',$name['id'])->update(['open_id'=>$openid]);
                    }
                }
                $this->redirect('/index/userlogin');
            }
        }else{
            $this->redirect('/index/userlogin');
        }
    }


    /**
     * 管理员密码加密方式
     * @param $password  密码
     * @param $password_code 密码额外加密字符
     * @return string
     */
    function password($password, $password_code='lshi4AsSUrUOwWV')
    {
        return md5(md5($password) . md5($password_code));
    }

    //返回json
    public function bejson($status, $msg){
        $re_back['status'] = $status;
        $re_back['msg'] = $msg;
        return json_encode($re_back);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值