위 챗 애플 릿 침묵 로그 인 실현 코드

1.wx.login 을 통 해 로그 인 증명(code)가 져 오기

wx.login({ success: function (res) { console.log(res.code); } })
2.여기에서 획득
appid 와 secret:https://developers.weixin.qq.com/sandbox

그림 과 같다
3.애플 릿 엔 드
http://127.0.0.1:8080/jeecg-boot이 부분 은 자신의 방문 경로 입 니 다.

 //app.js
App({
 globalData: {
 appid: '',
 appsecret: '',//
 openid: ''
 }
 onLaunch: function () {
 var that =this;
 //   
 wx.login({
  success: function (res) {
  console.log(res.code)
  wx.request({
   url: 'http://127.0.0.1:8080/jeecg-boot/hwork/hworkLog/GetOpenIdServlet',
   data: {
   appid: that.globalData.appid,
   secret: that.globalData.appsecret,
   js_code: res.code,
   grant_type: 'authorization_code'
   },
   method: 'POST',
   header: {
   'Content-Type': 'application/x-www-form-urlencoded'
   },
   success: function (res) {
   console.log(res)
   // json
   var j= JSON.parse(res.data.result)
   //   openid
   that.globalData.openid = j.openid;
   }
  })
  }
 })
  }
})
4.배경 코드
도구 클래스

package org.jeecg.modules.hworkorder.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeChatService {
 /**
  *         
  * @param path            
  * @param data             ,           JSON       
  */
 public static String interfaceUtil(String path,String data) {
  String openId="";
  try {
   URL url = new URL(path);
   //   url     
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   PrintWriter out = null;
   //    
//   conn.setRequestMethod("POST");
//   //         
   conn.setRequestProperty("accept", "*/*");
   conn.setRequestProperty("connection", "Keep-Alive");
   conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
   //     httpUrlConnection  ,     httpUrlConnection  ,    post         
   //    Http     get post,get          ,        URL    ,   servlet,
   //post get        post       URL    ,    http      。
   conn.setDoOutput(true);
   conn.setDoInput(true);
   //  URLConnection        
   out = new PrintWriter(conn.getOutputStream());
   //         
   out.print(data);
   //    
   out.flush();
   //  URLConnection        
   InputStream is = conn.getInputStream();
   //         
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
   String str = "";
   while ((str = br.readLine()) != null) {
    openId=str;
    System.out.println(str);
   }
   //   
   is.close();
   //    ,    ,disconnect    tcp socket        。               。
   //       ,   disconnect,     ,        。  disconnect     。
   conn.disconnect();
   System.out.println("    ");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return openId;
 }
 public static String GetOpenID(String appid,String appsecret,String Code) {
  //      
  String URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&js_code="+Code+"&grant_type=authorization_code";
  String openId=interfaceUtil(URL, "");
  return openId;
 }
}

@RestController
@RequestMapping("/hwork/hworkLog")
@Slf4j
public class hworkLogContrller {
@RequestMapping(value = "/GetOpenIdServlet", method = RequestMethod.POST)
 public Result<String> GetOpenIdServlet(HttpServletRequest request, HttpServletResponse response){
  Result<String> result=new Result<String>();
  response.setContentType("text/html;charset=utf-8");
  /*        ajax     */
  response.setHeader("Access-Control-Allow-Origin", "*");
  /*                 , */
  response.setHeader("Access-Control-Allow-Methods", "GET,POST");
  //  json  
  String appid=request.getParameter("appid");
  String secret=request.getParameter("secret");
  String js_code=request.getParameter("js_code");
  if(appid!=null&&appid!=""&&secret!=null&&secret!=""&&js_code!=null&&js_code!=""){
   WeChatService getOpenId=new WeChatService();
   String openId=getOpenId.GetOpenID(appid,secret,js_code);
   result.setResult(openId);
   result.setMessage("       ");
  }else{
   result.setMessage("    ");
   result.setSuccess(false);
  }
  return result;
 }
}
여기까지 오 면 openid 를 받 을 수 있 습 니 다.
총결산
위 에서 말 한 것 은 소 편 이 여러분 에 게 소개 한 위 챗 애플 릿 이 조용히 로그 인 한 실현 코드 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 저 에 게 메 시 지 를 남 겨 주세요.소 편 은 제때에 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
만약 당신 이 본문 이 당신 에 게 도움 이 된다 고 생각한다 면,전 재 를 환영 합 니 다.번 거 로 우 시 겠 지만 출처 를 밝 혀 주 십시오.감사합니다!

좋은 웹페이지 즐겨찾기