微信公众号获取access_token ,openid 和unionid

 1: 一般我们在进行微信公众号开发的时候,都需要用到access_token,但是具体的获取及其使用方式如何呢?下面展示一种获取的方式(具体的微信公众号申请和配置,请参考开放文档,具体在这里就不详细说明了),首先,可以参考微信官方文档,详细了解具体的文档,以便更好的理解和使用:微信公众号开放文档https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

public ActionResult GetAccessToken(string appId, string appSecret)

       {

           var key = "appidAccesstoken";

           //首先查询是否已经存在session中  存储到session中是因为token的获取每天是有次数限制的,而且每次重新获取之后,都会导致之前获取的信息失效

           var token = CacheHelper.GetCache(key);

           var accesstoken = "";

           if (token == null)

           {

               var gettokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret);

               

               var httpClient = new HttpClient();

               var result = httpClient.GetStringAsync(gettokenUrl).Result;

               if (string.IsNullOrEmpty(result))

               {

                   return 查询失败;

               }

               token = JsonConvert.DeserializeObject(result);

               var timespan = new TimeSpan(0, token.expires_in - 10, 0);

               CacheHelper.SetCache(key, token, timespan);

           }

           accesstoken = token.access_token;

           return 查询成功;

       }

2:如何获取openid

微信地址:

获取code后,请求以下链接获取access_token: 
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

代码段


@SuppressWarnings("null")
    @RequestMapping("/getOAuth")
    public String getOAuth(){       
        String code = request.getParameter("code");//获取微信服务器授权返回的code值
        String state = request.getParameter("state");//验证是否来自微信重定向的请求
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            if(Constant.STATE.equals(state)){
                /**
                 * 构造请求链接
                 * https://api.weixin.qq.com/sns/oauth2/access_token?
                 * appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
                 */
                String url = Constant.ACCESS_TOKEN_URL+Constant.APP_ID+"&secret="+Constant.APP_SECRET+"&code="+code+"&grant_type=authorization_code";                   
                String jsonStr = HttpUtil.httpRequest(url);
                String openid = JSONObject.parseObject(jsonStr).getString("openid");
                System.out.println(openid+"==========================");
                session = request.getSession();
                session.setAttribute("openid", openid);
                return "login/wx_login";//登录页面
            }else{
                response.setContentType("text/html;charset=utf-8");
                pw.write("<script>alert('授权失败!');</script>");
                pw.flush();
                pw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=utf-8");
            pw.write("<script>alert('发生后台异常!');</script>");
            pw.flush();
            pw.close();
        }
        return null;
    }

3:如何获取 unionid

微信地址:https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html#UinonId

开发者可通过OpenID来获取用户基本信息。特别需要注意的是,如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号,用户的unionid是唯一的。换句话说,同一用户,对同一个微信开放平台下的不同应用,unionid是相同的。 

获取用户基本信息(包括UnionID机制)

开发者可通过OpenID来获取用户基本信息。请使用https协议。

接口调用请求说明

http请求方式: GET https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN 

参数说明

参数 是否必须 说明
access_token 调用接口凭证
openid 普通用户的标识,对当前公众号唯一
lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语

返回说明

正常情况下,微信会返回下述JSON数据包给公众号:

{
   "subscribe": 1, 
   "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", 
   "nickname": "Band", 
   "sex": 1, 
   "language": "zh_CN", 
   "city": "广州", 
   "province": "广东", 
   "country": "中国", 

   "headimgurl":  "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4

eMsv84eavHiaiceqxibJxCfHe/0",

  "subscribe_time": 1382694957,
  "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
  "remark": "",

  "groupid": 0,

  "tagid_list":[128,2]

}

参数说明

参数 说明
subscribe 用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。
openid 用户的标识,对当前公众号唯一
nickname 用户的昵称
sex 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
city 用户所在城市
country 用户所在国家
province 用户所在省份
language 用户的语言,简体中文为zh_CN
headimgurl 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
subscribe_time 用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
unionid 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
remark 公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注
groupid 用户所在的分组ID(兼容旧的用户分组接口)
tagid_list 用户被打上的标签ID列表

错误时微信会返回错误码等信息,JSON数据包示例如下(该示例为AppID无效错误):

{"errcode":40013,"errmsg":"invalid appid"}

流程图:

猜你喜欢

转载自blog.csdn.net/xulong5000/article/details/112983798