av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

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

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

瀏覽:179日期: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才行,總的來說還是很簡單的 微信支付才是大坑

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

標簽: 微信
相關文章:
主站蜘蛛池模板: 国产一二区免费视频 | 特黄一级 | 精品1区2区| 国产色婷婷精品综合在线手机播放 | 日本免费一区二区三区视频 | 成人一区av | 日韩和的一区二区 | 欧美久久一区二区三区 | 青青久久 | 成人午夜免费福利视频 | 欧美精品在线免费 | 久久久在线视频 | 久久一热| 午夜性视频 | 成人精品国产免费网站 | 特级毛片爽www免费版 | 亚洲免费一区二区 | 亚洲欧洲精品在线 | 97精品国产手机 | 久久久夜色精品亚洲 | www.97国产| 中文字幕 视频一区 | 亚洲成av人片在线观看无码 | www.成人免费视频 | 色综合久久久 | 日韩理论电影在线观看 | 亚洲影音| 啪啪免费网站 | 精品国产视频 | 久久久成人免费视频 | 一级a性色生活片久久毛片 午夜精品在线观看 | 国产精品一区二区无线 | 青青草这里只有精品 | 精品无码久久久久久国产 | 精品国产一区二区三区久久狼黑人 | 欧美狠狠操| 性高朝久久久久久久3小时 av一区二区三区四区 | 国产中文字幕在线 | 在线黄色影院 | 性视频网 | 午夜免费福利影院 |