亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

java 微信小程序code獲取openid的操作

瀏覽:141日期:2022-05-23 14:29:39

最近有個小程序的項目 需要前端傳code 后端獲取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;@RestControllerpublic 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和session_key

中間可能會有報錯 主要原因在appid和appsecret這,前端需要配置appid才行,總的來說還是很簡單的 微信支付才是大坑

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。

標簽: 微信
相關文章:
主站蜘蛛池模板: 不卡国产在线 | 国产欧美一区二区三区免费 | 狠狠色综合久久婷婷 | 欧美爱爱动态 | 夜夜偷影视 | 成年黄页网站视频全免费 | 丁香综合激情 | 国产大尺度吃奶无遮无挡 | 成年女人a毛片免费视频 | 亚洲日产综合欧美一区二区 | 欧美精品在线观看 | 中文字幕久久综合伊人 | 草逼视频免费看 | 久久精品亚洲热综合一本奇米 | 国产午夜精品久久久久九九 | 尤物视频www | 另类国产精品一区二区 | 久久综合中文字幕一区二区三区 | 免费a一级毛片在线播放 | 青青操免费在线视频 | 欧美sese| 日本一本高清视频 | 99re最新地址获取精品 | 国产免费一区二区三区 | 国产网址在线 | 日本中文字幕不卡免费视频 | 草草在线播放 | 亚洲免费二区三区 | 亚洲一区二区在线免费观看 | 香蕉视频在线免费看 | 久久99国产亚洲精品观看 | 黄色网址在线看 | 极品国模私拍福利在线观看 | 国产毛片在线高清视频 | 国产成人一区二区三区在线视频 | 欧美二级在线观看免费 | 高清性色生活片免费观看 | 久久精品国产99国产精品亚洲 | 午夜免费福利视频 | 国产精久久一区二区三区 | 国产高清不卡码一区二区三区 |