PHP获取微信openid和unionid完整流程

<?php
namespace Mobile\Controller;
use Common\Model\MemberModel;
use Think\Controller;
class BaseController extends Controller {
    protected $UID = 0;
    protected $userInfo = [];

    public function _initialize(){
        header('Content-Type:text/html;charset=utf-8');

        //用户ID  用来判断用户是否登录
        $member_model = new MemberModel();
        $this->UID = intval($member_model->getAuthInfo('id'));

        //用户信息
        $userInfo = M('Member')->where(['id'=>$this->UID])->find();
        $this->userInfo = $userInfo;

        //获取微信openid 和 unionid
        $wx_info = session('wx_info');
        if(is_WeChat() && CONTROLLER_NAME != 'Login' && !$wx_info['openid']){
            session('wx_openid',null);
            $wx_openid = $this->get_openid();

            //根据access_token 和 openid 获取unionid
            $access_token = $this->get_access_token();
            $user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$wx_openid;
            $wx_info = json_decode(curl_get($user_info_url),true);
            session('wx_info',$wx_info);

            //如果系统存在该微信账户 则使其登录
            $member_model->wx_login(['wx_unionId'=>$wx_info['unionid']]);
        }
    }

    /**
     * 获取微信用户openid
     */
    public function get_openid(){
        $openid = null;
        $wx_openid = I('param.openid');
        if($wx_openid){session('wx_openid',$wx_openid);}
        $openid = session('wx_openid');
        if(empty($openid)){
            $openid = get_openid();
        }
        return $openid;
    }

    /**
     * 获取access_token  公众号的全局唯一接口调用凭据
     */
    private function get_access_token(){
        $info = M('we_chat')->find();
        $access_token = $info['access_token'];
        $over_time = $info['over_time'];
        if(!$access_token || $over_time < time()){
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$info['app_id'].'&secret='.$info['app_secret'];
            $json = curl_get($url);
            $arr = json_decode($json,true);
            $access_token = $arr['access_token'];
            $data['id'] = $info['id'];
            $data['access_token'] = $arr['access_token'];
            $data['over_time'] = time() + 7100;//access_token的有效期目前为2个小时
            M('we_chat')->save($data);
        }
        return $access_token;
    }

}
<?php

/**
 * 是否为微信端
 */
function is_WeChat(){
    if (strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

/**
 * 获取微信用户openid
 */
function get_openid() {
    if(!empty($_REQUEST['openid'])){
        $openid = $_REQUEST['openid'];
        session('wx_openid',$openid);
        return $openid;
    }else{
        $callback = C('ROOT_URL').'?m=mobile&c=Index&a=index';
        OAuthWX($callback);
    }
}

/**
 * 获取微信用户openid
 * @param string $callback
 */
function OAuthWX($callback){
    $wx_chat = M('we_chat')->where(['id'=>1])->find();
    $param['appid'] = $wx_chat['app_id'];
    if (!isset($_GET['getOpenId'])){
        $param['redirect_uri'] = $callback.'&getOpenId=1';
        $param['response_type'] = 'code';
        $param['scope'] = 'snsapi_base';//snsapi_base  snsapi_userinfo
        $param['state'] = 'wx_login';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?'.http_build_query($param).'#wechat_redirect';
        redirect($url);
    } elseif ($_GET['state']){
        $param['secret'] = $wx_chat['app_secret'];
        $param['code'] = I('code');
        $param['grant_type'] = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?'.http_build_query($param);
        $content = curl_get($url);
        $content = json_decode($content,true);
        $openid = $content['openid'] ? $content['openid'] : -1;
        redirect($callback.'&openid='.$openid);
    }
}

/**
 * Curl GET 请求
 * @param string $url
 * @return string
 */
function curl_get($url) {
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过ssl检查项
    $output = curl_exec($ch);
    if($output === FALSE ){
        echo "CURL Error:".curl_error($ch);
    }
    curl_close($ch);
    return $output;
}
发布了21 篇原创文章 · 获赞 6 · 访问量 1499

猜你喜欢

转载自blog.csdn.net/weixin_42047371/article/details/101110008