【WeChat】JFinal_qyweixin 配置微信第三方登录OAuth (使用测试账号)

更新:

测试号,请使用JFinal_weixin,因为微信提供API不同(导致我不能使用snsapi_userinfo)。
详细可以看 : https://www.jianshu.com/p/01b04bdf9645

拓展:

  1. openid 只和你的微信号和服务号(订阅号)有关,即在同一个订阅号下是唯一的
  2. openid 是不会过期
  3. UnionID,由于同一公司下多个公众号之间需要用户帐号互通,微信开放平台提供了UnionID机制。(即有些公众号绑定在同一个微信开发平台账号下,其中不同公众号下会openid不同,但unionID却是相同的。) 【用于用户去重

下面坑点案例请适当学习


平台

  1. JFinal_qyweixin 配置
  2. 测试账号
  3. 内网穿透(natapp)


    微信授权登录官方资料https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842


(1)重定向微信授权,获得用户code


① 初始化

  1. 微信 appID和 appsecret 获取
    网页访问: 微信公众平台 –》 开发(开发者工具) –》 公众平台测试账号
    这里写图片描述

  2. JFinal 微信配置
    这里写图片描述
    这里写图片描述

  3. JFinal 路由配置
    这里写图片描述

  4. 内网穿透(natapp)
    参考:https://natapp.cn/article/natapp_newbiehttps://natapp.cn/article/config_ini
    进行配置。
    这里写图片描述


② 编写重定向地址

  1. 根据https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
  2. 直接调用 JFinal_qyweixin OAuthAPi
    这里写图片描述
  3. 回调url
    String backUrl = "http://qyf9az.natappfree.cc/Jingying/wechatOAuth/callBack";


③ 配置微信接口

  1. 根据natapp 获取 域名,并填写域名
    在测试号管理网页向下查找,网页获取用户基本信息
    这里写图片描述
    这里写图片描述


③ 验证

需要在微信客户端中访问




(2)获取用户信息


① 访问获取用户openid

主要参考官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

  1. 通过微信返回的 code ,模拟访问,并获取json(用户的 openid 和 access_token)
    这里写图片描述

  2. 通过openid 获取用户详细信息
    这里并不能实现,会报错,应为我们使用的是 snsapi_base
    这里写图片描述


② 完整代码和执行结果

public class LoginController extends Controller{

    public void index() {
        String backUrl = "http://qyf9az.natappfree.cc/Jingying/wechatOAuth/callBack";
        // TODO: 企业认证后,才能使用把false改true(snsapi_base 改为了 snsapi_userinfo)
        String url = OAuthApi.getCodeUrl(backUrl, "STATE", false);
        redirect(url);
    }

    public void callBack() {
        String code = getPara("code");

        // TODO: 企业认证后,可尝试使用OAuthApi.getUserInfoByCode();  
        ApiConfig kit = ApiConfigKit.getApiConfig();
        String getUserInfoUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + kit.getCorpId() +
            "&secret=" + kit.getCorpSecret() +
            "&code=" + code +
            "&grant_type=authorization_code";
        String jsonResult = HttpUtils.get(getUserInfoUrl);
        ApiResult apiResult = new ApiResult(jsonResult);
        System.out.println("openid: " + apiResult.get("openid"));

        String getInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + apiResult.get("access_token") +
            "&openid=" + apiResult.get("openid") + 
            "&lang=zh_CN";
        String _jsonResult = HttpUtils.get(getInfoUrl);
        System.out.println(_jsonResult);

        render("wechat.html");
    }

}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/fanfan4569/article/details/79498409