目录

通过 PHP 获取用户微信 openid

目录
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// 基于 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';
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 微信回调地址,请求当前微信用户资料

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;
    }
}