자바 위 챗 애플 릿 code openid 가 져 오기

최근 에 작은 프로그램의 항목 이 있 습 니 다.전단 코드 백 엔 드 에서 openid 를 가 져 와 야 합 니 다.여 기 는 순 백 엔 드 입 니 다.
여기에 적어 주세요.
주 코드:
openid 를 가 져 오 는 실현 클래스 입 니 다.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.moszk.frame.basic.utils.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class WeiXinSubmitController {
    @ResponseBody
    @RequestMapping(value = "/wx/decodeUserInfo", method = RequestMethod.GET)
    public Map decodeUserInfo(String code) {
        System.out.println(code);
        Map map = new HashMap();
        //        
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code     ");
            return map;
        }
        //          (            )
        
        String wxspAppid = "***********";
        //     app secret (            )
        String wxspSecret = "*********************";
        //  (  )
        String grant_type = "authorization_code";
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        //1、              code    session_key   openid
        //    
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //    
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        System.out.println("sr========"+sr);
        //      (   json  )
        JSONObject json =JSON.parseObject(sr);
        System.out.println("json============"+json);
        //      (session_key)json.get("session_key").toString();
        String session_key = json.get("session_key").toString();
        //       (openid)
        String openid = (String) json.get("openid");
        map.put("session_key",session_key);
        map.put("openid",openid);
        return map;
    }
}
요청 을 보 낼 도구 클래스 가 필요 합 니 다.

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
public class HttpRequest {
    /**
     *    URL  GET     
     * 
     * @param url
     *                 URL
     * @param param
     *                ,        name1=value1&name2=value2    。
     * @return URL             
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            //    URL     
            URLConnection connection = realUrl.openConnection();
            //          
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
					
            //        
            connection.connect();
            //          
            Map<String, List<String>> map = connection.getHeaderFields();
            //           
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            //    BufferedReader      URL   
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("  GET      !" + e);
            e.printStackTrace();
        }
        //   finally       
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    /**
     *     URL   POST     
     * 
     * @param url
     *                  URL
     * @param param
     *                ,        name1=value1&name2=value2    。
     * @return             
     */
    public static String sendPost(String url, String param, String keyValue) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            //    URL     
            URLConnection conn = realUrl.openConnection();
            //          
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("api-key", keyValue);  
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
            //   POST          
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //   URLConnection        
            //out = new PrintWriter(conn.getOutputStream());
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            //       
            out.print(param);
            // flush      
            out.flush();
            //   BufferedReader      URL   
            in = new BufferedReader(
                      new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
            	System.out.println(line);
                result += line;
            }
        } catch (Exception e) {
            System.out.println("   POST       !"+e);
            e.printStackTrace();
        }
        //  finally       、   
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    public static String generateOrderId(){
		String keyup_prefix=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String keyup_append= String.valueOf(new Random().nextInt(899999)+100000);
        String pay_orderid=keyup_prefix+keyup_append;//   
		return pay_orderid;
	}
	public static String generateTime(){
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	}
    	
	public static String md5(String str) throws NoSuchElementException {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes("UTF-8"));
            byte[] byteDigest = md.digest();
            int i;
            //          
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            // 32   
            return buf.toString();//toUpperCase
            // 16    
             //return buf.toString().substring(8, 24).toUpperCase();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
모든 것 이 잘 되면 code 를 보 내 면 open 로 돌아 갑 니 다.id 와 sessionkey
중간 에 오류 가 발생 할 수 있 습 니 다.주요 원인 은 appid 와 appsicret 입 니 다.전단 에 appid 를 설정 해 야 합 니 다.전체적으로 간단 한 위 챗 결제 가 큰 구덩이 입 니 다.
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.만약 잘못 이 있 거나 완전히 고려 하지 않 은 부분 이 있다 면 아낌없이 가르침 을 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기