微信公众号获取openid

方式一:通过网页授权的方式获取,前提是公众号已获得网页授权

公众号获得网页授权后,配置回调域名:

当用户点击某个菜单事件时,调用项目中的xxx.jsp或xxx.html文件(http://www.xxx.com/web/wx1.jsp),内容如下:

appid:公众号的:appid
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ include file="/commViews/taglib.jsp"%>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />
</head>
<script type="text/javascript">
    window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx59f756xxxxxxx    &redirect_uri=http%3a%2f%2fwww.xxxx.com%2fweb%2fwx2.jsp  /*(http://www.xxxx.com/web/wx2.jsp)*/    &response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
</script>
<body>
</body>
</html>
http://www.xxxx.com/web/wx2.jsp 获取到code后调用后台接口,通过code获取openid
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ include file="/commViews/taglib.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes"/>
    <%@ include file="/commViews/head.jsp"%>
</head>
<script type="text/javascript">
    var is_weixin = (function () {
        return navigator.userAgent.toLowerCase().indexOf(‘micromessenger‘) !== -1
    })();
    var code = getUrlParam("code");
    console.log("code:" + code);
    $(function () {
        if (code != null) {

            $.ajax({
                url: "${ctx}appsite/wx/getOpenid",
                type: "get",
                dataType: ‘text‘,
                data: {code: code},
                success: function (openid) {
                    // alert(openid)
                },
                error: function (msg) {
                    console.log(msg);
                }
            });

        }

    });
</script>
<body>

</body>
</html>

后台获取openid的接口:

import com.alibaba.fastjson.JSONObject;
import com.xxx.xxx.wechat.util.HttpRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/xxxx/wx")
public class AppWxController {

    @Autowired
    StxcContestUserService<StxcContestUser> stxcContestUserService;

    /**
     * 1 第一步:用户同意授权,获取code
     *
     * 2 第二步:通过code换取网页授权access_token
     *
     * 3 第三步:刷新access_token(如果需要)
     *
     * 4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
     *
     * 5 附:检验授权凭证(access_token)是否有效
     *
     * code=CODE&state=STATE
     * https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
     */

    /**
     * 通过code换取网页授权access_token
     * @param request
     * @param response
     * @return  access_token    网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
     *          expires_in    access_token接口调用凭证超时时间,单位(秒)
     *          refresh_token    用户刷新access_token
     *          openid    用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
     *          scope    用户授权的作用域,使用逗号(,)分隔
     */
    @RequestMapping(value = "/getOpenid",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getAccess_token(HttpServletRequest request, HttpServletResponse response,Map map){
        String code = request.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        Map<String,String> params = new HashMap<String, String>();
        params.put("appid","wx59f75xxxxxxxxxx");  // 此处图方便直接将 appid,secret写在这里
        params.put("secret","a0ff75cf900489xxxxxxxxxxx");
        params.put("code",code);
        params.put("grant_type","authorization_code");
        String result = HttpRequestUtil.getInfoByNet(url,params,"POST","https",null);

        JSONObject json = JSONObject.parseObject(result);
        String openid = json.getString("openid");

        return openid;
    }

}
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpRequestUtil {

    //请求地址,请求参数,请求方式,请求协议,携带参数
    public static String getInfoByNet(String url, Map<String,String> params,String requestMethod,String requestProtocol,String outputStr){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(url+"?");
        String result="";
        for (Map.Entry<String,String> arg:params.entrySet()){
            stringBuffer.append(arg.getKey()+"="+arg.getValue()+"&");
        }

        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        //System.out.println(stringBuffer);
        if(requestProtocol.equals("https")){
            result = httpsRequest(stringBuffer.toString(), requestMethod, outputStr);
            //System.out.println(result);
            return result;
        }else {
            result = httpRequest(stringBuffer.toString(), requestMethod, outputStr);
            //System.out.println(result);
            return result;
        }

    }
}

方式二:公众号未获得网页授权

登录公众号后配置如下:(可参考开发文档的 “入门指南”) https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Getting_Started_Guide.html

上面填写的Url 是自己项目中的接口,填写好后提交时公众号会发送一个GET请求到接口进行token验证。

注意:验证的时候接口必须是GET请求方式,接口是POST请求token会验证失败;等token验证成功后想把接口改为post请求也可以,

刚开始没注接口用的是post请求,token验证一直失败package com.cen.appsite.KpzsContest.controllerimport com.alibaba.fastjson.JSONObject;

import com.cen.appsite.wechat.util.HttpRequestUtil;
import org.aspectj.bridge.MessageUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/xxxxx/wx")
public class KpzsWxController {

    /*     踩坑一:用post请求,token验证一直失败    */
    //@RequestMapping(value = "/checkSignature", method = RequestMethod.POST)   @RequestMapping(value = "/checkSignature", meghod = RequestMethod.GET)

    /*      踩坑二:请求参数用这个,验证一直不通过
        public void checkSignature(@RequestParam("signature") String signature,
                              @RequestParam("timestamp") String timestamp,
                              @RequestParam("nonce") String nonce,
                              @RequestParam("echostr") String echostr,
                              HttpServletResponse response) {    */
        public void checkSignature(HttpServletRequest request, HttpServletResponse response) {

        // xml请求解析
        Map<String, String> requestMap = null;
        try {
            requestMap = parseXml(request);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 发送方帐号(open_id),formUserName 即为想要获取的用户的openid
        String fromUserName = requestMap.get("FromUserName");
        // 公众帐号
        String toUserName = requestMap.get("ToUserName");
        // 消息类型
        String msgType = requestMap.get("MsgType");
        String Event = requestMap.get("Event");
        String EventKey = requestMap.get("EventKey");

    //回复用户消息 --图文消息
        String img = "<xml>\n" +
                "<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "<CreateTime>"+new Date().getTime()+"</CreateTime>\n" +
                "<MsgType><![CDATA[news]]></MsgType>\n" +
                "<ArticleCount>1</ArticleCount>\n" +
                "<Articles>\n" +
                "<item>\n" +
                "<Title><![CDATA[2019“倡导绿色环保生活”科普知识挑战赛]]></Title>\n" +
                "<Description><![CDATA[快来参与吧!]]></Description>\n" +
                "<PicUrl><![CDATA[http://www.xxxx.com/resource/images/kpzs.png]]></PicUrl>\n" +  //图片路径
                "<Url><![CDATA[http://www.xxxx.com/web/kpzs_index.jsp?openid="+fromUserName+"]]></Url>\n" +  // 当用户点击图文消息时想要跳转的链接
                "</item>\n" +
                "</Articles>\n" +
                "</xml>\n";

     //回复用户消息 --纯文本
        String text = "<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>"+new Date().getTime()+"</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[你好啊]]></Content>\n" +
                "  <MsgId>1234567890123456</MsgId>\n" +
                "</xml>";

        try {
            PrintWriter out = response.getWriter();
            // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
            if (SignUtil.checkSignature(request.getParameter("signature"), request.getParameter("timestamp"), request.getParameter("nonce"))) {          //用户的所有消息都必须响应,否则用户会收到 “公众号服务存在故障”提示
                if(Event != null && Event.equals("CLICK")){ //用户点击(菜单)事件
                    out.print(img);
                }else{
                    out.print(text);
                }
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();

        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());

        // 释放资源
        inputStream.close();
        inputStream = null;
        return map;
    }

}
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpRequestUtil {

    //请求地址,请求参数,请求方式,请求协议,携带参数
    public static String getInfoByNet(String url, Map<String,String> params,String requestMethod,String requestProtocol,String outputStr){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(url+"?");
        String result="";
        for (Map.Entry<String,String> arg:params.entrySet()){
            stringBuffer.append(arg.getKey()+"="+arg.getValue()+"&");
        }

        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        //System.out.println(stringBuffer);
        if(requestProtocol.equals("https")){
            result = httpsRequest(stringBuffer.toString(), requestMethod, outputStr);
            //System.out.println(result);
            return result;
        }else {
            result = httpRequest(stringBuffer.toString(), requestMethod, outputStr);
            //System.out.println(result);
            return result;
        }

    }
}

原文地址:https://www.cnblogs.com/L237/p/12348268.html

时间: 2024-07-31 22:12:30

微信公众号获取openid的相关文章

微信公众号获取粉丝openid系统

做为一名开发人员,在测试当中也经常需要用到openid,但是微信公众号获取openid的方法也是特别麻烦!网页授权是最常见的方式, 但是网页授权的流程太复杂,不仅要开发,还要在公众号后台设置回调域名(必须备案域名,还要上传txt验证文件),个人认为微信在获取openid方面未免太过繁琐了! 一直在想怎么获取粉丝的openid最方便,傻瓜式操作,避免复杂的流程,于是用下面的方法来获取全部粉丝的openid:同步公众号粉丝列表 操作流程: 1.无需设置任何东西,只需要填写公众号的appid和apps

微信公众号菜单openid 点击菜单即可打开并登录微站

现在大部分微站都通过用户的微信openid来实现自动登录.在我之前的开发中,用户通过点击一个菜单,公众号返回一个图文,用户点击这个图文才可以自动登录微站.但是如果你拥有高级接口,就可以实现点击菜单,打开网页就能获取这个openid,实现自动登录. 这里已经提到,必须要拥有高级接口的权限(服务号.企业号),开启了开发者模式. 1.设置回调地址 在微信公众平台后台“开发者中心”中找到“高级接口”下的“OAuth2.0网页授权”,后面有一个“修改”,点击之后就会弹出填写回调地址的对话框.具体如何授权,

微信公众号--获取用户列表

之前其实写过一次微信号的简单开发,包括菜单自动回复拉取用户信息等简单的微信公众号的开发,今天又用到了,然后发现自己还是忘记了,看来记录下来是真的有必要的.我今天主要是写了拉取用户信息,所以我这比写的也就是拉取用户信息. 这里使用的还是TP的框架写的php代码进行开发的. 1.对使用的公众号进行基本配置 代码: //微信验证 public function checkWechat(){ // $weixin=M("maiclub_weixin"); // $res=$weixin->

使用Django实现微信公众号用户openid登录认证

最近在用Django做一个小项目,需要将微信的用户与网站的用户进行关联,由于是微信的订阅号,没有oauth网页授权的权限,只能退而求其次,在响应中获取用户的openid,来唯一的标识用户. Django中用户的模型继承和扩展于AbstractUser,在用户模型中添加openid字段: models.py class Users(AbstractUser): openid = models.CharField(max_length=100,blank=True,null=True,verbose

JAVA微信公众号通过openid发送模板消息~

1,问题产生 在微信公众号开发过程中,我们有时候做不同权限的时候,比如在注册的时候,需要审核,然后我们要想办法让对方知道审核的结果.这时候我们可以通过模板消息来通知. 2,第一步,首先在微信公众号上获取模板消息 首先,登录微信公众平台,看有没有模板消息这一块,没有的话点击添加功能插件,去添加,这里就省略不说了,这个主要就是选择你公众号的行业对应的模板消息,然后通过审核之后就可以使用了,说是几个工作日 但是一般很快就审核通过的. 有模板消息之后点进来,对应自己所需要的模板消息进行添加,比如,我添加

微信公众号获取的图片不能正常显示的问题

目前已经获取微信公众号发布的图片,但不能正常显示 提示:此图片来自微信公众平台 未经允许不得引用查看了一下他的地址是这样的:(http://mmbiz.qpic.cn/mmbiz/qqz4WKmibGPptReVk5OPKp0hfPYx2s4BGDZZZHyOBs2drnsxxdYwdm99KykNKf8WddhFA0ObjO04VSyocrNKvww/640?tp=webp&wxfrom=5) http://mmbiz.qpic.cn/mmbiz/qqz4WKmibGPptReVk5OPKp0

微信公众号获取用户地理位置

很久没搞微信的js-sdk了, 搞了一下午, 刷新页面老是失败, 没想到结合经验给大家展示下获取用户地理位置 第一步:登录微信公众号https://mp.weixin.qq.com 首先先设置最基本的配置(这一步大家应该都会) 第二步:点击公众平台右上角展开点击功能设置 配置网页授权域名 填写项目所使用的的域名并将文件下载放到项目根目录 然后在配置js安全域名同样将要下载的txt文件放到项目目录也可以是二级目录, 如果放到二级目录域名后面要就目录路径哦 保存之后: 第三步: 公众号左边栏,开发-

H5页面获取微信公众号的openid

1.H5页面是运行在微信浏览器的 2.需要与公众号关联(即需要openid) 3.判断需求是否需要弹窗告知用户授权操作 4.获取到的openid做本地存储,判断没有openid进行获取openid操作 5.这边的操作是不需要弹出授权框,且code不能重复使用,所以做了关注二维码弹窗且不能关闭弹唱操作 // 强制关注公众号,获取openid getCode = function () { if (sessionStorage.getItem("openid")&&sess

微信公众号获取用户信息致跳过的坑

有一段时间没有搞微信开发了 ,今天突然要改一下程序! 回头一看 微信的帮助文档太tm的稀烂的,太难懂了,这做个笔记以后看着方便 微信有2个ACCESS_TOKEN, 1,基础接口的token 获取接口是 https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET 2,用户网页授权access_token 获取接口地址是 https://api.weixin