微信公众号开发获取用户openid和用户信息的步骤

<?php

define("APPID", 'wxe127d5e246s9e343');
define("APP_SECRET", 'e35ba07f2e64we7uc5f0533cd1a63732');

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

if (!isset($_GET['code'])) {
    // 回跳地址需要在微信公众号后台绑定,域名需要先备案
    $REDIRECT_URI = 'http://wx.myshop.com/wx_gzh_userinfo.php';
    $scope = 'snsapi_base'; //snsapi_base 或 snsapi_userinfo
    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . APPID . '&redirect_uri=' . urlencode($REDIRECT_URI) . '&response_type=code&scope=' . $scope . '&state=wx' . '#wechat_redirect';
    header("Location:" . $url);
} else {
  // 这个接口没有返回微信用户的基本信息,适合用做微信用户在公众号的普通登录
    // 获取网页授权access_token接口,该接口的访问频率不受限制,获得的access_token可以用来获取用户信息
    /**
    注意:不要跟获取基础access_token的接口混起来。
    基础access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒,重复获取将导致上次获取的access_token失效。
    获取基础access_token的接口每天限制访问2000次,地址是https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APP_SECRET
    成功返回结果{"access_token":"ACCESS_TOKEN","expires_in":7200}
    通过该接口获取的access_token结果要缓存起来,access_token 的存储空间至少要保留 512 个字符,
    方案1:后台安排定时任务调用该接口并刷新缓存,
    方案2:access_token在redis中设置过期时间为7000秒,先从redis缓存读取access_token,如果不存在就调用这个接口重新获取基础access_token并刷新缓存,
    方案2适合用在网站的并发不是特别大的情况,如果并发经常达到1万以上,应该采用方案1
    确保调用其他接口(例如创建微信公众号自定义菜单接口、发送模板消息)的时候不会过期
    */

    $code = $_GET["code"];
    $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . APPID . '&secret=' . APP_SECRET . '&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);
    echo 'res=';
    print_r($res);
    $json_obj = json_decode($res, true);

    //根据openid和access_token查询用户信息,一般来说当openid在本网站数据库中不存在的时候才需要这样做,比如微信用户第一次登录系统
    $access_token = $json_obj['access_token'];
    $openid = $json_obj['openid'];
    $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $get_user_info_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res2 = curl_exec($ch);
    curl_close($ch);
    echo 'res2=';
    print_r($res2);
    //解析json
    $user_obj = json_decode($res2, true);
    $_SESSION['user'] = $user_obj;
    //print_r($user_obj);
    // print_r($user_obj);
    print_r("<br><br>");
    // print_r($get_user_info_url);
    // print_r("<br><br>");
    // print_r($openid);
    // return json_decode($openid);
    print_r($openid);
    // 最终结果
    /**
    res=
    {
        "access_token": "71_ilcxFIDf1zVpfOxABW_zEoJzxNO023S9UOQBfURQfZ5I6AgizJec8FQ5B86xJBb-1K135D1YfMyO6bgAmCp90OHGlYw_nuikqfulO9uIHxg",
        "expires_in": 7200,
        "refresh_token": "71_6HC0VxhT2LoOWUWUCc2-vG5z-6JZNR14ZULpMReqwwCpNOdRwdzvIGqpjFfbzpYtNl13t0QtIDG9onoLTiVI-a-SgFGoQbNhDFuYuBmA3dM",
        "openid": "oNglrtwW9aQQQJ4kLaIsqOPZm39g",
        "scope": "snsapi_userinfo",
        "unionid": "oXn8b1Advze2dIzcdY0_Efko25rs"
    }
    res2=
    {
        "openid": "oNglrtwW9aQQQJ4kLaIsqOPZm39g",
        "nickname": "闪电",
        "sex": 0,
        "language": "",
        "city": "",
        "province": "",
        "country": "",
        "headimgurl": "https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/Q0j4TwGTfTJWVUzX3FnFxMcP8mqXrJZJ3bRG2OyauTr845kfR7q2bW1CLibiauuPAyV8QkqH8dyKP1l50ib2gyzvA\/132",
        "privilege": [],
        "unionid": "oXn8b1Advze2dIzcdY0_Efko25rs"
    }
    oNglrtwW9aQQQJ4kLaIsqOPZm39g
    */
}

 

posted @ 2023-08-18 10:36  tochenwei  阅读(597)  评论(0编辑  收藏  举报