微信登录第三方平台

   1.前台请求后台获得相应的参数及回调地址,用户扫面后登录到回调的地址中,回调的地址中获得用户信息及返回信息,前台监控返回信息做相应的处理及登录注册

public class WeChatLoginAction extends AbstractRestBaseAction {

    @Autowired
    private MembersService memberService;

    @Autowired
    private MemLoginLogService memLoginLogService;
    
    @Autowired
    private MemSignInRecordService memSignInRecordService;

    // 应用唯一标识
    private String appid = "wx2ed73e3d972bf2ce"; 
    
    // 应用密钥AppSecret,在微信开放平台提交应用审核通过后获得
    private String secret = "3dceda9ff389dbcce576e4ea4ed9da20"; 
    
    // 应用授权作用域,拥有多个作用域用逗号(,)分隔,网页应用目前仅填写snsapi_login即
    private String scope = "snsapi_login";
    
    /**
     * 
     * @category 登录请求微信操作 (步骤1)
     * @author hjj
     * @date 2018年10月13日
     * @return void
     */
    public void _$indexBatchRequestWeChat(){
        String redirect_uri = queryCallbackUri();// 请使用urlEncode对链接进行处理 
        Resp result = initResult();
        result.dataMap("appid", appid);
        result.dataMap("scope", scope);
        try {
            result.dataMap("redirect_uri",URLEncoder.encode(redirect_uri, "UTF-8"));
        } catch (Exception e) { 
            e.printStackTrace();
            initResult(RespCode.ErrFailure, "操作失败");
        } 
    }
    
    /**
     * 
     * @category 登录获得请求微信回调地址(步骤1)
     * @author hjj
     * @date 2018年10月13日
     * @return
     * @return String
     */
    public String queryCallbackUri(){
        String path = request.getContextPath();
        String ServerName = request.getServerName();
        //String ServerName = "1608e55a.all123.net";//测试ip 不加ip
        String basePath = request.getScheme() + "://" + ServerName + path ; 
        basePath += "/we-chat-login";
        return basePath;
    }
    
}

页面

引入

<script type="text/javascript" src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>

步骤1 前台请求后台获得微信所需参数并监听用户扫码情况  及处理

index-login.tpl

App._$get('${ctxPath}/api/we-chat-login.json?_type=requestWeChat&_batch=true',null,null,null,null,
                    function(data){ 
                         _this.ewmDiv = true; 
                         setTimeout(function(){
                             var obj = new WxLogin({
                                 self_redirect:true,
                                id: "ewmDiv", 
                                appid: data.appid, 
                                scope: data.scope, 
                                redirect_uri: data.redirect_uri,
                                style : 'black'
                             }); 
                         },0); 
                        //监听返回参数 
                        _this.id_of_setinterval = setInterval(function(){ 
                            if(_this.ewmDiv == false){//关闭二维码窗口
                                clearInterval(id_of_setinterval) 
                            }
                            var weChatStatus = $("#weChatStatus",$('#ewmDiv iframe')[0].contentDocument).val();//$('#ewmDiv iframe')[0].contentDocument 在哪里获得
                            if(weChatStatus != null){ //只要监控到了就要停掉定时器
                                clearInterval(_this.id_of_setinterval) 
                                if(weChatStatus == 200){//成功登录
                                    var login_jwt = $("#login_jwt",$('#ewmDiv iframe')[0].contentDocument).val();
                                    var login_t = $("#login_t",$('#ewmDiv iframe')[0].contentDocument).val();
                                    window.localStorage['_authorization'] = login_jwt;
                                    window.localStorage['_t'] = login_t;
                                    setTimeout(function(){
                                        //登录成功,跳转到指定页面 
                                        window.location.href = '${ctxPath}/member/';
                                    },100)
                                }else if(weChatStatus == 201){//未注册 
                                    _this.ewmDiv = false;
                                    _this.registerDiv = true;//注册
                                }
                            }
                        },1000);  
                    },function(err){
                    
                });

we-chat-login.tpl

<div>
<input type="hidden" id="weChatStatus" value="${status}"/> 
<input type="hidden" id="login_jwt" value="${jwt!}"/> 
<input type="hidden" id="login_t" value="${_t!}"/> 
<div style="text-align: center;margin-top: 100px;">
    <div class="thirdParty_1">
        <span class="thirdParty_1_1" style="font-size: 18px;">${statusTitle}</span>
    </div> 
</div> 
</div> 

 

package com.seryo.kpy.web.action;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.JsonObject;
import com.seryo.common.Constants;
import com.seryo.kpy.web.AbstractTplAction;
import com.seryo.model.mem.MemOperateLog;
import com.seryo.model.mem.Members;
import com.seryo.service.mem.MemIntegralService;
import com.seryo.service.mem.MemOperateLogService;
import com.seryo.service.mem.MembersService;
import com.seryo.service.mem.SessionService;
import com.seryo.util.StringUtils;
import com.seryo.util.base.IpUtil;
import com.seryo.util.base.UrlUitl;
import com.seryo.util.json.JsonUtil;
import com.seryo.util.oauth.App;
import com.seryo.util.oauth.WebHelper;
import com.seryo.web.resp.Resp;

/**
 * 功能:微信登录操作
 * @Package com.seryo.kpy.web.restapi.member
 * @ClassName: WeChatLoginAction
 * @author hjj
 * @date 2018年10月13日 下午2:46:13
 */
public class WeChatLoginAction extends AbstractTplAction {

    @Autowired
    private MembersService memberService; 
    
    @Autowired
    private SessionService sessionService; 
    
    @Autowired
    private MembersService membersService;
    
    @Autowired
    private MemIntegralService memIntegralService;

    @Autowired
    private MemOperateLogService memOperateLogService;

    // 应用唯一标识
    private String appid = "wx2ed73e3d972bf2ce"; 
    
    // 应用密钥AppSecret,在微信开放平台提交应用审核通过后获得
    private String secret = "3dceda9ff389dbcce576e4ea4ed9da20";  
    
  
    
    /**
     * 
     * @category (步骤1)回调地址
     * @author hjj
     * @date 2018年10月13日
     * @return void
     */
    @Override
    public String execute(){
        String code = param("code"); 
        Resp result = initResult();
        Integer status = null;
        String statusTitle = "";
        String weChatOpenId = "";
        String access_token = "";
        if(!StringUtils.isBlank(code)){//不为空则是  用户允许授权 否则不做处理
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
            try {
                String fhz = UrlUitl.sendGet(url); 
                 JsonObject json = JsonUtil.fromJson(fhz);
                 if(json.get("errcode") != null){
                     status = -1;
                     statusTitle = "操作异常";
                 }else{
                     access_token = json.get("access_token").getAsString(); 
                     weChatOpenId = json.get("openid").getAsString(); 
                     Members members = memberService.queryWeChat(weChatOpenId);
                     if(members != null){//0 正常 1不正常 2为注册  
                         App app = WebHelper.getApp(request);
                         if(Constants.USER_STATUS_NORMAL.equals(members.getStatus())){//用户转态正常
                             JsonObject userJson = sessionService.thirdPartyLogin(members, null, response, request, app);
                             attr("jwt",userJson.get("jwt").getAsString());
                             attr("_t",userJson.get("_t").getAsString());
                             status = 200;
                             statusTitle = "登录成功";
                         }else{//状态异常
                             status = -2;
                             statusTitle = "用户状态异常";
                         }
                     }else{//未绑定账号
                         JsonObject json2 = queryUserData(access_token, weChatOpenId);
                         if(json2.get("errcode") != null){//获得用户信息
                             status = -3;
                             statusTitle = "用户授权失败";
                         }else{
                             HttpSession session = request.getSession();
                             session.setAttribute("sessionUserData", json2);//设置到Session中
                             status = 201;
                             statusTitle = "未绑定账号";
                         }
                     }
                 }
            } catch (Exception e) {
                e.printStackTrace();
                status = -4;
                statusTitle = "系统异常";
            }
        } 
        attr("status",status);
        attr("statusTitle",statusTitle);
        return SUCCESS;
    } 
    
    /**
     * 
     * @category 获得微信用户信息
     * @author hjj
     * @date 2018年10月17日
     * @param ACCESS_TOKEN 调用凭证
     * @param openid 普通用户的标识,对当前开发者帐号唯一
     * @return void
     */
    public JsonObject queryUserData(String ACCESS_TOKEN, String openid){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+ACCESS_TOKEN+"&openid="+openid;
        String fhz = UrlUitl.sendGet(url);  
        return JsonUtil.fromJson(fhz);
    }
    
    @Override
    public String detail(){
        String code = param("code"); 
        Resp result = initResult();
        Integer status = null;
        String statusTitle = ""; 
        if(!StringUtils.isBlank(code)){//不为空则是  用户允许授权 否则不做处理
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
            try {
                String fhz = UrlUitl.sendGet(url); 
                 JsonObject json = JsonUtil.fromJson(fhz);
                 if(json.get("errcode") != null){
                     status = -1;
                     statusTitle = "操作异常";
                 }else{
                     String openid = json.get("openid").getAsString();
                     Members members = getMembers();// 获取当前登录用户
                     if(members != null){
                         Members members2 = membersService.getById(members.getId());
                         members2.setWeChatId(openid);
                         MemOperateLog memOperateLog = new MemOperateLog();
                         String content = "用户绑定微信";
                         if(!Constants.IS_TRUE.equals(members2.getIsWeChat())){//未绑定过微信
                             members2.setIsWeChat(Constants.IS_TRUE);
                             Integer integral =    members2.getIntegral() == null ? 0 : members2.getIntegral();
                             Integer integral2 = memIntegralService.saveMemIntegral(members2, "绑定微信", Constants.IS_TRUE, Constants.SYS_INTEGRAL_CODE_BINDING_WE_CHAT);
                             integral += integral2;
                             members2.setIntegral(integral);
                             content += ",并获得绑定微信积分"+integral2;
                         }
                         membersService.saveOrUpdate(members2);
                         WebHelper.updateUserInfoUflag(request, response, members2);// 重新注入对象
                         
                         memOperateLog.setContent(content);
                         memOperateLog.setModule("个人中心");
                         memOperateLog.setResult(Constants.IS_TRUE);
                         App app = WebHelper.getApp(request);
                         memOperateLog.setIp(IpUtil.getIpAddr(request));// ip
                         memOperateLogService.addMemOperateLog(members2, app, memOperateLog);
                         status = 200;
                         statusTitle = "绑定成功";
                     }else{
                         status = 0;
                         statusTitle = "未登录,请重新登录!";
                     }
                 }
            } catch (Exception e) {
                e.printStackTrace();
                status = -2;
                statusTitle = "系统异常";
            }
        } 
        attr("status",status);
        attr("statusTitle",statusTitle);
        return SUCCESS;
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值