微信授权(静默授权,非静默授权)

一、前言

微信授权分为静默授权非静默授权,两者的区别在于,前者不需要微信用户点击授权按钮,但只能获取微信openid,后者需点击授权按钮,但能获取微信用户基本信息(openid、微信昵称、性别、头像地址、国籍、省、市),为什么获取不到手机号码?答案在这里。

二、准备

1、花6块钱在花生壳买个域名,将域名映射到本地项目80端口上。

2、申请测试号   测试号申请入口。(测试号申请成功后可以看见  appID和appsecret),自己手机微信扫一下,将自己二维码加进去。

微信授权(静默授权,非静默授权)_第1张图片

 

三、配置

将在花生壳里买的域名填到这里

微信授权(静默授权,非静默授权)_第2张图片

微信授权(静默授权,非静默授权)_第3张图片

 

四、上代码

import com.aem.project.system.giftmall.member.service.IPointsMemberService;
import com.aem.project.system.wx.profession.domain.ReturnCode;
import com.aem.project.system.wx.profession.util.AuthUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Controller
@RequestMapping("/wx/authorization")
public class WxAuthorizationController {
    private static final Logger logger = Logger.getLogger(String.valueOf(WxAuthorizationController.class));

    @Autowired
    private IPointsMemberService memberService;

    /**
      * 公众号微信登录授权
     第一步:
     return  code    本地自测(注意:需要申请域名)    重定向去找授权方法
     */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    public String wxLogin(HttpServletRequest request, HttpServletResponse response)
            throws ParseException {
        //这个url的域名必须要进行在公众号中进行注册验证,这个地址是成功后的回调地址
        String backUrl="http://aem315.natapp1.cc/traceability/wx/authorization/callBack";
        // 第一步:用户同意授权,获取code
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ AuthUtil.APPID + "&redirect_uri="+ URLEncoder.encode(backUrl) + "&response_type=code"
                + "&scope=snsapi_userinfo" + "&state=STATE#wechat_redirect";
        logger.info("forward重定向地址{" + url + "}");
        return "redirect:"+url;//必须重定向,否则不能成功
    }

    /**
      * 公众号微信登录授权回调函数
     第一种授权方式:非静默授权(需微信用户点击授权按钮,获取微信用户全部信息)
     */
    @RequestMapping(value = "/callBack", method = RequestMethod.GET)
    public void callBack(ModelMap modelMap, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                         /*
                     * start 获取微信用户基本信息
                     */
        String code =req.getParameter("code");
        //第二步:通过code换取网页授权access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APPID + "&secret="+ AuthUtil.APPSECRET + "&code="+code
                + "&grant_type=authorization_code";
        System.out.println("url:"+url);
        JSONObject jsonObject = AuthUtil.doGetJson(url);
                         /*
                                 { "access_token":"ACCESS_TOKEN",
                                    "expires_in":7200,
                                    "refresh_token":"REFRESH_TOKEN",
                                    "openid":"OPENID",
                                    "scope":"SCOPE" 
                                   }
                                 */
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        String refresh_token = jsonObject.getString("refresh_token");
        //第五步验证access_token是否失效;展示都不需要
        String chickUrl="https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;

        JSONObject chickuserInfo = AuthUtil.doGetJson(chickUrl);
        System.out.println(chickuserInfo.toString());
        if(!"0".equals(chickuserInfo.getString("errcode"))){
            // 第三步:刷新access_token(如果需要)-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki,
            String refreshTokenUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+openid+"&grant_type=refresh_token&refresh_token="+refresh_token;

            JSONObject refreshInfo = AuthUtil.doGetJson(chickUrl);
                                         /*
                                           { "access_token":"ACCESS_TOKEN",
                                        "expires_in":7200,
                                        "refresh_token":"REFRESH_TOKEN",
                                        "openid":"OPENID",
                                        "scope":"SCOPE" }
                                     */
            access_token=refreshInfo.getString("access_token");
        }

        // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token + "&openid="+openid + "&lang=zh_CN";
        System.out.println("infoUrl:"+infoUrl);
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
                         /*
                     {    "openid":" OPENID",
                        " nickname": NICKNAME,
                        "sex":"1",
                        "province":"PROVINCE"
                        "city":"CITY",
                        "country":"COUNTRY",
                        "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
                        "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
                        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
                        }
                      */
        System.out.println("JSON-----"+userInfo.toString());
        System.out.println("名字-----"+userInfo.getString("nickname"));
        System.out.println("头像-----"+userInfo.getString("headimgurl"));
                     /*
                             * end 获取微信用户基本信息
                             */
        //获取到用户信息后就可以进行重定向,走自己的业务逻辑了。。。。。。
        //接来的逻辑就是你系统逻辑了,请自由发挥
        //(为什么获取不到手机号?)https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

        //判断会员表中有没有该微信会员信息
        String openId=userInfo.getString("openid");
        List list= memberService.selectMemberByOpenid(openId);
        if(list.size()<=0){
            //会员表中没有该微信会员
            //openID  nickName  sex  headimgurl(头像地址)    province(省) city(市)       language(语言)
            PointsMember pointsMember=new PointsMember();
            pointsMember.setOpenid(openId);
            pointsMember.setNickname(userInfo.getString("nickname"));
            pointsMember.setSex(userInfo.getString("sex"));
            pointsMember.setHeadimgurl(userInfo.getString("headimgurl"));
            pointsMember.setMemberAreacode(userInfo.getString("province")+userInfo.getString("city"));
            pointsMember.setCreateDate(new Date());
            pointsMember.setCreateTime(new Date());
            memberService.insertMember(pointsMember);
        }
        //else  有

    }


    /**
      * 公众号微信登录授权回调函数
     第二种授权方式:静默授权(无需微信用户点击授权按钮,但是只能获取微信用户openId)
     */
    @RequestMapping("/getOpenid")
    public void authorize(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Map map = new HashMap();
        String str = null;
        String code = request.getParameter("code");
        ReturnCode returnCode = null;
        InputStreamReader reader = null;
        BufferedReader breader = null;
        try {
            //通过获取access_token获得openid和access_token
            URL url = new URL("https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                    + AuthUtil.APPID+"&secret="+ AuthUtil.APPSECRET+"&code="+code+
                    "&grant_type=authorization_code");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            reader = new InputStreamReader(connection.getInputStream());
            breader = new BufferedReader(reader);
            StringBuffer strb = new StringBuffer();
            while (null != (str = breader.readLine())) {
                strb.append(str);
            }
            Gson gson = new Gson();
            returnCode = gson.fromJson(strb.toString(), ReturnCode.class);
            //根据用户Access_token和openid获取用户信息
            System.out.println("打印用户openId=================="+returnCode.getOpenid());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            breader.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //                return  new ModelAndView(new RedirectView(Wx_Util.sendPage+"/wxdraw/productscan?qrcode="+qrcode+"" +
        //                        "&openid="+returnCode.getOpenid()));
    }

}

 

五、测试

http://你的域名/项目后缀/wx/authorization/wxLogin

用谷歌浏览器打开,它会提示你去微信里去。在地址栏中会生成一大串罗里吧嗦的链接地址,复制下来,在微信里随便找个人发过去,打开链接。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(微信开发)