通过php获取用户微信openid

// 基于CI框架
// 访问开始页面

public function url()
{
    // wxAction/oauth2 微信回调地址;微信传入code值,通过该code在wxAction/oauth2请求当前用户微信资料
    // account/bind 用户账号与微信号进行绑定
    $current_url = site_url('wxAction/oauth2').'?returl=account/bind'; 
    echo  'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.W_APPID.'&redirect_uri='.urlencode($current_url).'&response_type=code&scope=snsapi_base&state=123#wechat_redirect';
}
// 微信回调地址,请求当前微信用户资料

public function oauth2()
{
    $url     = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".W_APPID."&secret=".W_APPSECRET."&code=".$_GET['code']."&grant_type=authorization_code";
    $content = file_get_contents($url);
    $ret     = json_decode($content, true);

    if (isset($ret['openid'])) {
        $this->session->set_userdata('OPENID', $ret['openid']);

        //跳转回之前的页面
        if ($return_url = $this->input->get('returl')) {
            redirect($return_url);
        } else {
            redirect('welcome');
        }
        exit;
    } else {
        echo '网络请求繁忙,获取用户信息失败,请稍后再试!';
        exit;
    }
}
-----------------------------------------------------
说明:
  a).代码仅供学习交流
  b).本文根据自身经验及网络总结所作,如有错误,谢谢指教
  c).转载请注明出处。
-----------------------------------------------------
原文地址:https://www.cnblogs.com/xqbumu/p/5226646.html