微信小程序授权认证标准实现

940 阅读1分钟

  在微信小程序开发过程中,获取用户微信认证并且按照微信调用流程实现的一套标准化的代码,实现了微信登录获取用户信息等一系列的调用过程。

  userLogin() {
    var that = this;
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: app.globalData.BASE_REQUEST_URL + '/wx/api/login',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              console.log(res);
              var userinfo = {};
              userinfo['openid'] = res.data.data.openid;
              userinfo['session_key'] = res.data.data.session_key;
              userinfo['unionid'] = res.data.unionid;
              wx.setStorageSync('userinfo', userinfo);

              var opid = res.data.data.openid;
              var unid = res.data.data.unionid;
              // An highlighted block
              wx.showModal({
                title: '温馨提示',
                content: '正在请求您的个人信息',
                success(res) {
                  if (res.confirm) {
                    wx.getUserProfile({
                      desc: "获取你的昵称、头像、地区及性别",
                      success: res => {
                        var wxUserInfo = res.userInfo;
                        wxUserInfo.openid=opid;
                        wxUserInfo.unionid=unid;
                        wxUserInfo.idCard = "622102199501083817"
                        wxUserInfo.ltRealName = "倪辉"
                        wxUserInfo.phone = "186020643707"
                        wx.request({
                          url: app.globalData.BASE_REQUEST_URL + '/wx/api/register',
                          method:"POST",
                          data: wxUserInfo,
                          header: {
                            'content-type': 'application/json' // 默认值
                          },
                          success:function(res){
                            console.log("注册成功")
                            that.setData({
                              userInfo:res.data.data,
                              hasUserInfo: true
                            })
                            wx.setStorageSync("AppUsers",res.data.data)
                          }
                        })

                      },
                      fail: res => {
                        //拒绝授权
                        // wx.showErrorModal('您拒绝了请求');
                        wx.showToast({
                          title: '您拒绝了请求',
                          icon: "none"
                        })
                        return;
                      }
                    })
                  } else if (res.cancel) {
                    //拒绝授权 showErrorModal是自定义的提示
                    wx.showToast({
                      title: '您拒绝了请求',
                      icon: "none"
                    })
                    return;
                  }
                }
              })
            }
          })
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    })

  },

后端实现

@Service
public class WeiXinService {

    @Autowired
    private WeiXinProperties weiXinProperties;

    public WxRespObject login(String code){
        String param = "appid="+weiXinProperties.getAppid()+"&secret="+weiXinProperties.getSecret()+"&js_code="+code+"&grant_type=authorization_code";
        String s = HttpUtils.sendSSLPost("https://api.weixin.qq.com/sns/jscode2session", param);
        WxRespObject wxRespObject = JsonUtil.toObject(s,WxRespObject.class);
        return wxRespObject;
    }

}

    public static String sendSSLPost(String url, String param)
    {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try
        {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL realUrl= new URL(null, urlNameString, new sun.net.www.protocol.https.Handler());
//            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection)realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null)
            {
                if (ret != null && !"".equals(ret.trim()))
                {
                    result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();