2016-12-23 13:45:56 u011072139 阅读数 19949

前端:

wx.login({
      success: function (res) {
        res.code
    })

获取到code后,传到后台,

然后请求微信接口

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
把参数替换为自己的参数,这个接口就直接返回openId了

2018-07-26 11:24:15 qq_41381202 阅读数 1784

大家对openid都或多或少有些了解,在小程序里openid是,通过前端获取code传给后端,而在公众号里,前端没有传code的接口,这就导致了,code必须后端自己取出来,我让前端循环访问的的wucode的接口,如果没有code就继续执行微信的而链接去换取code,如果有code就把code换取openid,头像和昵称;如果有code就执行youcode接口,这是后端判断的

 public function wucode($user_token = '',$yq_openid =''){
        if(!empty($yq_openid)){
            Session::set('yq_openid',$yq_openid);
        }
        if(empty($user_token)){
            $user_token = Session::get('user_token');
            if(empty($user_token)){
                $user_token=time().rand(100000,999999);
            }
        }
        $user_data = Db::table('xc_member')->where(['user_token'=>$user_token])->find();
        //$yq_openid = Session::get('yq_openid');
        if(!empty($user_data) && empty($yq_openid)){
            return  json(['code'=>1000,'data'=>$user_data['uid'],'msg'=>'openid获取成功']);
        }elseif(!empty($user_data) && !empty($yq_openid)){
            $this->redirect('http://yfj.sharexwd.top/dist'); 
        }else{
            Session::set('user_token',$user_token);
            $wechat = Config::get('wechat');
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
                $url .= '?appid=' . $wechat['appid'];
                $url .= '&redirect_uri=' . urlencode('http://yfj.sharexwd.top/index/login/youcode');
                $url .= '&response_type=code';
                $url .= '&scope=snsapi_userinfo';
                $url .= '&state=' . rand(10,99);
                $url .= '#wechat_redirect';
            $this->redirect($url);
        }
    }

    public function youcode($code = ''){
        $wechat = Config::get('wechat');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $url .= '?appid=' . $wechat['appid'];
        $url .= '&secret=' . $wechat['appsecret'];
        $url .= '&code=' . $code;
        $url .= '&grant_type=authorization_code';
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        if (isset($result['errcode'])) {
            $this->error('失效的参数,请重新授权');
        }
        //通过access_token和openid获取用户信息
        $url = 'https://api.weixin.qq.com/sns/userinfo';
        $url .= '?access_token=' . $result['access_token'];
        $url .= '&openid=' . $result['openid'];
        $url .= '&lang=zh_CN';
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        if (isset($result['errcode'])) {
            $this->error('失效的参数,请重新授权');
        }
        $data = [
            'openid'=>$result['openid'],
            'username'=>$result['nickname'],
            'headimage'=>$result['headimgurl']
        ];
        $user_token = Session::get('user_token');
        //查询对应的openid是否已经有了
        $user_data = Db::table('xc_member')->where(['uid'=>$result['openid']])->find();
        if($user_data){
            Db::table('xc_member')->where(['uid'=>$result['openid']])->update(['user_token'=>$user_token]);
            $this->redirect('http://yfj.sharexwd.top/dist');  
        }else{
            $dbi=db('xc_member');
            $list=$dbi->insert([
                'uid'=>$result['openid'],
                'nicheng'=>$result['nickname'],
                'touxiang'=>$result['headimgurl'],
                'user_token'=>$user_token
            ]);
            //绑定上级
            $yq_openid = Session::get('yq_openid');
            Session::set('yq_openid',null);
            if(!empty($yq_openid)){
          //这里写自己的操作
            $this->redirect('http://yfj.sharexwd.top/dist');  
        }  
    }

前端无限循环访问wucode接口就可以获取所有信息

2016-09-11 21:54:14 qq_19541441 阅读数 1774

1、主动获得:通过网页授权获得openid 在拦截器中获取存放到session中
2、被动获得:通过用户的动作微信会向程序发送xml,通过解析xml获得个人信息 流程如下:
点击公众号的按钮—->微信向程序发送xml—解析出用户信息

一、主动获取
设置拦截器

//这个是网页授权的地址
public static  String Auth_Url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";





package com.team.weixin.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.team.weixin.model.Code_ge_user_info;
import com.team.weixin.model.WeixinContext;
import com.team.weixin.model.WinxinFinalValue;
import com.team.weixin.util.WeixinUtil;


public class WeixinFilter implements Filter{
    private static final Logger log = Logger.getLogger(WeixinFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hRequest = (HttpServletRequest) request;
        HttpServletResponse hResponse = (HttpServletResponse) response;
        String agent = hRequest.getHeader("User-Agent");
        if (agent != null && agent.toLowerCase().indexOf("micromessenger") >= 0) {
            String code = request.getParameter("code");
            String state = request.getParameter("state");
            log.info("code:" + code + " state:" + state);
            String path = hRequest.getRequestURL().toString();
            String query = hRequest.getQueryString();
            if (query != null) {
                path = path + "?" + query;
            }
            log.info("path:"+path);
            /**
             * TODO域名修改         
             */
            if(!path.contains("toindex")){//拦截
                chain.doFilter(hRequest, hResponse);
                return;
            }

            if (code != null && state != null && state.equals("1")) {//授权过
                // 通过Code获取openid来进行授权
                String openid = null;
                try {
                    openid = WeixinUtil.ge_openid_by_code(code);
                    log.info("[doFilter] openid:"+ openid);
                    if (StringUtils.isNotEmpty(openid)) {
                        hRequest.getSession().setAttribute("openid", openid);
                    }
                } catch (Exception e1) {

                    log.info("catch exception :"+e1.getMessage());
                    if(!path.contains("toindex")){
                        hResponse.sendRedirect(path);
                    }
                }
            } else {//没授权过
                String uri = WinxinFinalValue.Auth_Url;
                uri = uri.replace("APPID", WinxinFinalValue.AppID)
                         .replace("REDIRECT_URI",URLEncoder.encode(path, "UTF-8"))
                         .replace("SCOPE", "snsapi_userinfo")
                         .replace("STATE", "1");
                log.info("[没授权过]"+uri);


                System.out.println();
                hResponse.sendRedirect(uri);
                return;
            }
        }
        chain.doFilter(hRequest, hResponse);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

}

二、被动获取 在初始化微信的servlet里边获得 post方法下是微信返回的xml 解析xml就得到了用户信息

package com.team.weixin.init;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.client.ClientProtocolException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.JsonObject;
import com.team.exception.CustomException;
import com.team.model.SysUser;
import com.team.service.SysUserService;
import com.team.weixin.model.ReceiveXmlEntity;
import com.team.weixin.model.WeixinContext;
import com.team.weixin.model.WinxinFinalValue;
import com.team.weixin.util.Jackson;
import com.team.weixin.util.SecurtiyKit;
import com.team.weixin.util.WeixinUtil;

import net.sf.json.JSONObject;

@Controller
public class IntiWexin {

    @Resource
    private SysUserService sysUserService;

    @RequestMapping(value = "/wget", method = RequestMethod.GET)
    public void init_weixin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");

        String[] arrs = { WinxinFinalValue.Token, timestamp, nonce };
        Arrays.sort(arrs);
        StringBuffer sbf = new StringBuffer();
        for (String a : arrs) {
            sbf.append(a);
        }
        String sha1 = SecurtiyKit.sha1(sbf.toString());
        System.out.println(sha1.equals(signature));
        if (sha1.equals(signature)) {
            resp.getWriter().write(echostr);
        }
    }

    @RequestMapping(value = "/wget", method = RequestMethod.POST)
    public void geInfo(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String str = null;
        StringBuilder strxml = new StringBuilder();
        while ((str = br.readLine()) != null) {
            System.out.println(str);
            strxml.append(str);
        }

        ReceiveXmlEntity rxe = WeixinUtil.getMsgEntity(strxml.toString());

        WinxinFinalValue.OpenId=rxe.getFromUserName();


        session.setAttribute("p", 444);


    //  init_user(rxe);
    }

    // 初始化用户 //获取用户的 基本信息 放到数据库里
    /*public void init_user(ReceiveXmlEntity rxe) {
        String urls = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + WeixinContext.getAccess_token()
                + "&openid=" + rxe.getFromUserName() + "&lang=zh_CN";
        try {
            String s_user = WeixinUtil.to_get(urls);
            //ge_user_info
            SysUser user = WeixinUtil.ge_user_info(Jackson.json_to_map(s_user)); 
            try {
                //对接自己的程序
                SysUser sysUser=new SysUser();
                sysUser.setOpenid(user.getOpenid());
                List<SysUser> list=sysUserService.list(sysUser);
                //判断用户是否关注
                if(list.size()>0&&list!=null){
                    //不做处理
                }else{
                    sysUserService.add(user);
                }
            } catch (CustomException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }*/




}
2017-04-25 18:58:27 aSuncat 阅读数 2703

一、思路:
1、获取企业code.
2、利用后台传过来的access_token,结合code,获取openId.
二、代码

//获取openId
$(function(){
  //获取location.href中的code
  var code = location.href.split('?')[1].split('&')[0].split('=')[1];
  console.log(code);
  //后台获取access_token

//后台还没有给我,给我之后我再写一下
  // var access_token=access_token;


  //根据code获取openId
  function changeCode(){
    $.ajax({
      type:'GET',
      url:'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='+access_token+'&code='+code,
      dataType:'json',
      success:function(data){
        if(data.success){
          var openId;
          //如果是企业成员授权,返回userId,转为openId,
          //如果是非企业成员授权,返回openId
          if(data.UserId){
            var userId=data.UserId;
            //userId装换为openId
            $.ajax({
              type:'POST',
              url:'https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token='+access_token,
              dataType:'json',
              data:{
                userid:userId
              },
              success:function(data){
                if(data.success){
                  openId=data.openid
                }
              }
            });
          }else{
            openId=data.OpenId;
          }
        }else{
          console.log('获取接口失败');
        }
      },
      error:function(jqXHR){
        console.log('发生错误:'+jqXHR.status);
      }
    });
  }
});

三、微信接口文档
地址:http://qydev.weixin.qq.com/wiki/index.php?title=OAuth验证接口
四、关键点
这里写图片描述
标红的地方就是location.href获取到的值。
五、参考文档:http://blog.csdn.net/wenxuechaozhe/article/details/52104285

2018-09-18 16:02:41 wobuaizhi 阅读数 302

最近解决一个微信公众号页面获取用户openid的问题。下面是自己的整理

1,微信平台对回调域名的说法如下,意思就是说,如果你想通过回调获取授权信息,必须先设置回调域名,就是你要获取openid的页面的url所在的域名。参考下面的说明

关于网页授权回调域名的说明

1、在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;

2、授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com无法进行OAuth2.0鉴权

2,配置完成后,在后台拼接回调的url

https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxx&redirect_uri=########&response_type=code&scope=snsapi_base&state=redict&connect_redirect=1#wechat_redirect

其中的redirect_uri后面的###是经过加密的需要跳转的url,

例如:对于http://www.baidu.com这样一个地址配置oauth跳转步骤如下:

         a、将结果值填充到redirect_uri参数:redirect_uri=http://www.baidu.com

3,最后在前端页面打开这个url就会跳转到对应界面,微信平台会在url后面会自动拼接

http://www.baidu.com?openid=XXX;

自己截取就可以了。通过这个openid可以获取更加详细的信息。

参考文章:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

没有更多推荐了,返回首页