java 微信小程序code獲取openid的操作
最近有個(gè)小程序的項(xiàng)目 需要前端傳code 后端獲取openid 這里是純后端
在這里記錄一下吧
主要代碼:
這里是獲取openid的實(shí)現(xiàn)類
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;
}
//小程序唯一標(biāo)識(shí) (在微信小程序管理后臺(tái)獲取)
String wxspAppid = "***********";
//小程序的 app secret (在微信小程序管理后臺(tái)獲取)
String wxspSecret = "*********************";
//授權(quán)(必填)
String grant_type = "authorization_code";
//https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
//1、向微信服務(wù)器 使用登錄憑證 code 獲取 session_key 和 openid
//請(qǐng)求參數(shù)
String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
//發(fā)送請(qǐng)求
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
System.out.println("sr========"+sr);
//解析相應(yīng)內(nèi)容(轉(zhuǎn)換成json對(duì)象)
JSONObject json =JSON.parseObject(sr);
System.out.println("json============"+json);
//獲取會(huì)話密鑰(session_key)json.get("session_key").toString();
String session_key = json.get("session_key").toString();
//用戶的唯一標(biāo)識(shí)(openid)
String openid = (String) json.get("openid");
map.put("session_key",session_key);
map.put("openid",openid);
return map;
}
}
這里還需要一個(gè)工具類 用來(lái)發(fā)送請(qǐng)求的
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發(fā)送GET方法的請(qǐng)求
*
* @param url
* 發(fā)送請(qǐng)求的URL
* @param param
* 請(qǐng)求參數(shù),請(qǐng)求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
* @return URL 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
*/
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();
// 設(shè)置通用的請(qǐng)求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實(shí)際的連接
connection.connect();
// 獲取所有響應(yīng)頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應(yīng)頭字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來(lái)讀取URL的響應(yīng)
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發(fā)送GET請(qǐng)求出現(xiàn)異常!" + e);
e.printStackTrace();
}
// 使用finally塊來(lái)關(guān)閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 發(fā)送POST方法的請(qǐng)求
*
* @param url
* 發(fā)送請(qǐng)求的 URL
* @param param
* 請(qǐng)求參數(shù),請(qǐng)求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
* @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
*/
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();
// 設(shè)置通用的請(qǐng)求屬性
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");
// 發(fā)送POST請(qǐng)求必須設(shè)置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流
//out = new PrintWriter(conn.getOutputStream());
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
// 發(fā)送請(qǐng)求參數(shù)
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來(lái)讀取URL的響應(yīng)
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("發(fā)送 POST 請(qǐng)求出現(xiàn)異常!"+e);
e.printStackTrace();
}
//使用finally塊來(lái)關(guān)閉輸出流、輸入流
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;//訂單號(hào)
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;
//字符數(shù)組轉(zhuǎn)換成字符串
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;
}
}
}
如果一切順利的話 傳過(guò)來(lái)code就會(huì)返回open_id和session_key
中間可能會(huì)有報(bào)錯(cuò) 主要原因在appid和appsecret這,前端需要配置appid才行,總的來(lái)說(shuō)還是很簡(jiǎn)單的 微信支付才是大坑
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
深入解析JVM之內(nèi)存結(jié)構(gòu)及字符串常量池(推薦)
Java作為一種平臺(tái)無(wú)關(guān)性的語(yǔ)言,其主要依靠于Java虛擬機(jī)——JVM,接下來(lái)通過(guò)本文給大家介紹JVM之內(nèi)存結(jié)構(gòu)及字符串常量池的相關(guān)知識(shí),需要的朋友可以參考下2020-07-07
spring?boot項(xiàng)目中集成rocketmq詳細(xì)步驟
這篇文章主要給大家介紹了關(guān)于spring?boot項(xiàng)目中集成rocketmq的相關(guān)資料,springboot集成rocketmq的方法非常簡(jiǎn)單,文中直接上代碼,需要的朋友可以參考下2023-09-09
Java將GeoHash轉(zhuǎn)化為對(duì)應(yīng)的經(jīng)緯度坐標(biāo)實(shí)例代碼
這篇文章主要介紹了Java實(shí)現(xiàn)將GeoHash轉(zhuǎn)化為對(duì)應(yīng)的經(jīng)緯度坐標(biāo)的相關(guān)資料,需要的朋友可以參考下2016-01-01
Mybatis實(shí)現(xiàn)分包定義數(shù)據(jù)庫(kù)的原理與過(guò)程
這篇文章主要給大家介紹了關(guān)于Mybatis實(shí)現(xiàn)分包定義數(shù)據(jù)庫(kù)的原理與過(guò)程,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-01-01
Java?IO網(wǎng)絡(luò)模型實(shí)現(xiàn)解析
這篇文章主要為大家介紹了Java?IO網(wǎng)絡(luò)模型實(shí)現(xiàn)解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
項(xiàng)目打包成jar后包無(wú)法讀取src/main/resources下文件的解決
本文主要介紹了項(xiàng)目打包成jar后包無(wú)法讀取src/main/resources下文件的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
Java深入了解數(shù)據(jù)結(jié)構(gòu)之優(yōu)先級(jí)隊(duì)列(堆)
普通的隊(duì)列是一種先進(jìn)先出的數(shù)據(jù)結(jié)構(gòu),元素在隊(duì)列尾追加,而從隊(duì)列頭刪除。在優(yōu)先隊(duì)列中,元素被賦予優(yōu)先級(jí)。當(dāng)訪問(wèn)元素時(shí),具有最高優(yōu)先級(jí)的元素最先刪除。優(yōu)先隊(duì)列具有最高級(jí)先出 (first in, largest out)的行為特征。通常采用堆數(shù)據(jù)結(jié)構(gòu)來(lái)實(shí)現(xiàn)2022-01-01

