WX小程序


下載

package com.sky.utils;import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;/*** Http工具類*/
public class HttpClientUtil {static final  int TIMEOUT_MSEC = 5 * 1000;/*** 發送GET方式請求* @param url* @param paramMap* @return*/public static String doGet(String url,Map<String,String> paramMap){// 創建Httpclient對象CloseableHttpClient httpClient = HttpClients.createDefault();String result = "";CloseableHttpResponse response = null;try{URIBuilder builder = new URIBuilder(url);if(paramMap != null){for (String key : paramMap.keySet()) {builder.addParameter(key,paramMap.get(key));}}URI uri = builder.build();//創建GET請求HttpGet httpGet = new HttpGet(uri);//發送請求response = httpClient.execute(httpGet);//判斷響應狀態if(response.getStatusLine().getStatusCode() == 200){result = EntityUtils.toString(response.getEntity(),"UTF-8");}}catch (Exception e){e.printStackTrace();}finally {try {response.close();httpClient.close();} catch (IOException e) {e.printStackTrace();}}return result;}/*** 發送POST方式請求* @param url* @param paramMap* @return* @throws IOException*/public static String doPost(String url, Map<String, String> paramMap) throws IOException {// 創建Httpclient對象CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = null;String resultString = "";try {// 創建Http Post請求HttpPost httpPost = new HttpPost(url);// 創建參數列表if (paramMap != null) {List<NameValuePair> paramList = new ArrayList();for (Map.Entry<String, String> param : paramMap.entrySet()) {paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));}// 模擬表單UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);httpPost.setEntity(entity);}httpPost.setConfig(builderRequestConfig());// 執行http請求response = httpClient.execute(httpPost);resultString = EntityUtils.toString(response.getEntity(), "UTF-8");} catch (Exception e) {throw e;} finally {try {response.close();} catch (IOException e) {e.printStackTrace();}}return resultString;}/*** 發送POST方式請求* @param url* @param paramMap* @return* @throws IOException*/public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {// 創建Httpclient對象CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = null;String resultString = "";try {// 創建Http Post請求HttpPost httpPost = new HttpPost(url);if (paramMap != null) {//構造json格式數據JSONObject jsonObject = new JSONObject();for (Map.Entry<String, String> param : paramMap.entrySet()) {jsonObject.put(param.getKey(),param.getValue());}StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");//設置請求編碼entity.setContentEncoding("utf-8");//設置數據類型entity.setContentType("application/json");httpPost.setEntity(entity);}httpPost.setConfig(builderRequestConfig());// 執行http請求response = httpClient.execute(httpPost);resultString = EntityUtils.toString(response.getEntity(), "UTF-8");} catch (Exception e) {throw e;} finally {try {response.close();} catch (IOException e) {e.printStackTrace();}}return resultString;}private static RequestConfig builderRequestConfig() {return RequestConfig.custom().setConnectTimeout(TIMEOUT_MSEC).setConnectionRequestTimeout(TIMEOUT_MSEC).setSocketTimeout(TIMEOUT_MSEC).build();}}

?

package com.sky.controller.user;import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;import java.util.HashMap;
import java.util.Map;@RestController()
@RequestMapping("/user/user")
@Api(tags = "C端用戶相關接口")
@Slf4j
public class UserController {@Autowiredprivate UserService userService;@Autowiredprivate JwtProperties jwtProperties;/*** 微信登錄** @param userLoginDTO* @return*/@PostMapping("/login")@ApiOperation("微信登錄")public Result login(@RequestBody UserLoginDTO userLoginDTO) {log.info("微信登錄,code:{}", userLoginDTO.getCode());User user = userService.wxLogin(userLoginDTO);//產生JWT令牌Map<String, Object> claims = new HashMap<>();claims.put(JwtClaimsConstant.USER_ID, user.getId());String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);UserLoginVO userLoginVo= UserLoginVO.builder().id(user.getId()).openid(user.getOpenid()).token(token).build();return Result.success(userLoginVo);}}
package com.sky.service.impl;import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.User;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.DishVO;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Service
public class UserServiceImpl implements UserService {private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";@Autowiredprivate WeChatProperties weChatProperties;@Autowiredprivate UserMapper userMapper;/*** 微信登錄* @param userLoginDTO* @return*/@Overridepublic User wxLogin(UserLoginDTO userLoginDTO) {String openid = getOpenid(userLoginDTO.getCode());//3. 判斷openid是否為空if (openid==null){throw new LoginFailedException(MessageConstant.LOGIN_FAILED);}//查詢用戶是否存在User user = userMapper.getByOpenid(openid);if (user==null){user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();//查詢到openid不存在,創建用戶userMapper.insert(user);}return user;}private String getOpenid(String code) {//1. 調用微信接口服務 參數 appid secret js_code grant_type=authorization_codeMap<String, String>pramsMap = new HashMap<>();pramsMap.put("appid",weChatProperties.getAppid());pramsMap.put("secret",weChatProperties.getSecret());pramsMap.put("js_code",code);pramsMap.put("grant_type","authorization_code");String result = HttpClientUtil.doGet(WX_LOGIN_URL, pramsMap);//2. 解析微信接口返回openidJSONObject jsonObject = JSONObject.parseObject(result);String openid = jsonObject.getString("openid");return openid;}
}//    public User wxLogin(UserLoginDTO userLoginDTO) {
//        //1. 調用微信接口服務 參數 appid secret js_code grant_type=authorization_code
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        //構造字符串
//        StringBuilder property = new StringBuilder();
//        property.append("appid=").append(weChatProperties.getAppid())
//                .append("&secret=").append(weChatProperties.getSecret())
//                .append("&js_code=").append(userLoginDTO.getCode())
//                .append("&grant_type=authorization_code");
//
//        String url = WX_LOGIN_URL + "?" + property.toString();
//        HttpGet httpGet = new HttpGet(url);
//        //2.執行
//        CloseableHttpResponse response = null;
//        try {
//            response = httpClient.execute(httpGet);
//            int statusCode = response.getStatusLine().getStatusCode();
//            if (statusCode == 200) {
//                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
//                System.out.println(result);
//                JSONObject jsonObject = JSONObject.parseObject(result);
//                String openid = jsonObject.getString("openid");
//                if(openid==null){
//                    throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
//                }
//                //查詢用戶是否存在
//                User user = userMapper.getByOpenid(openid);
//                if (user == null) {
//                    user = User.builder()
//                            .openid(openid)
//                            .createTime(LocalDateTime.now())
//                            .build();
//                    //查詢到openid不存在,創建用戶
//                    userMapper.insert(user);
//                }
//                return user;
//
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }finally {
//            try {
//                response.close();
//                httpClient.close();
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//            }
//        return null;
//        }
//
//    }
//}

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/74317.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/74317.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/74317.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Vulnhub-wordpress通關攻略

姿勢一、后臺修改模板拿WebShell 第一步&#xff1a;進?Vulhub靶場并執?以下命令開啟靶場&#xff1b;在瀏覽器中訪問并安裝好.... 第二步&#xff1a;找到外觀--編輯--404.php&#xff0c;將原內容刪除并修改為一句話木馬&#xff0c;點擊更新--File edited successfully. &…

Spring Boot(十六):攔截器Interceptor

攔截器的簡介 攔截器&#xff08;Interceptor&#xff09;?是Spring框架中的概?念&#xff0c;它同樣適?用于Spring Boot&#xff0c;?因為Spring Boot是基于Spring框架的。攔截器是?一種AOP&#xff08;面向切面編程&#xff09;?的輕量級實現方式&#xff0c;它允許我…

Kotlin v2.1.20 發布,標準庫又有哪些變化?

大家吼哇&#xff01;就在三小時前&#xff0c;Kotlin v2.1.20 發布了&#xff0c;更新的內容也已經在官網上更新&#xff1a;What’s new in Kotlin 2.1.20 。 我粗略地看了一下&#xff0c;下面為大家選出一些我比較感興趣、且你可能也會感興趣的內容。 注意&#xff01;這里…

開源鏈動2+1模式、AI智能名片與S2B2C商城小程序源碼在社交電商渠道拓寬中的協同應用研究

摘要&#xff1a;本文基于"開源鏈動21模式""AI智能名片""S2B2C商城小程序源碼"三大技術要素&#xff0c;探討社交電商時代商家渠道拓寬的創新路徑。通過解析各技術的核心機制與應用場景&#xff0c;結合京東便利店等實際案例&#xff0c;論證其對…

【藍橋杯速成】| 10.回溯切割

前面兩篇內容我們都是在做有關回溯問題的組合應用 今天的題目主題是&#xff1a;回溯法在切割問題的應用 題目一&#xff1a;分割回文串 問題描述 131. 分割回文串 - 力扣&#xff08;LeetCode&#xff09; 給你一個字符串 s&#xff0c;請你將 s 分割成一些 子串&#xff…

【嵌入式硬件】三款DCDC調試筆記

關于開關電源芯片&#xff0c;重點關注輸入電源范圍、輸出電流、最低壓降。 1.MP9943: 以MP9943為例&#xff0c;輸入電壓范圍4-36V&#xff0c;輸出最大電流3A&#xff0c;最低壓降為0.3V 調整FB使正常輸出為5.06V 給定6V空載、5V空載、5V帶2A負載的情況&#xff1a; 6V帶2A…

2025年03月18日柯萊特(外包寧德)一面前端面試

目錄 自我介紹你怎么從0到1搭建項目的webpack 的構建流程手寫webpack插件你有什么想問我的嗎 2. 你怎么從 0 到 1 搭建項目的 在面試中回答從 0 到 1 搭建前端項目&#xff0c;可按以下詳細步驟闡述&#xff1a; 1. 項目前期準備 需求理解與分析 和產品經理、客戶等相關人…

在vitepress中使用vue組建,然后引入到markdown

在 VitePress 中&#xff0c;每個 Markdown 文件都被編譯成 HTML&#xff0c;而且將其作為 Vue 單文件組件處理。這意味著可以在 Markdown 中使用任何 Vue 功能&#xff0c;包括動態模板、使用 Vue 組件或通過添加 <script> 標簽為頁面的 Vue 組件添加邏輯。 值得注意的…

Jupyter Notebook 常用命令(自用)

最近有點忘記了一些常見命令&#xff0c;這里就記錄一下&#xff0c;懶得找了。 文章目錄 一、文件操作命令1. %cd 工作目錄2. %pwd 顯示路徑3. !ls 列出文件4. !cp 復制文件5. !mv 移動或重命名6. !rm 刪除 二、代碼調試1. %time 時間2. %timeit 平均時長3. %debug 調試4. %ru…

Java面試黃金寶典12

1. 什么是 Java 類加載機制 定義 Java 類加載機制是 Java 程序運行時的關鍵環節&#xff0c;其作用是把類的字節碼文件&#xff08;.class 文件&#xff09;加載到 Java 虛擬機&#xff08;JVM&#xff09;中&#xff0c;并且將字節碼文件轉化為 JVM 能夠識別的類對象。整個類…

第十四章:模板實例化_《C++ Templates》notes

模板實例化 核心知識點解析多選題設計題關鍵點總結 核心知識點解析 兩階段查找&#xff08;Two-Phase Lookup&#xff09; 原理&#xff1a; 模板在編譯時分兩個階段處理&#xff1a; 第一階段&#xff08;定義時&#xff09;&#xff1a;檢查模板語法和非依賴名稱&#xff0…

LSM-Tree(Log-Structured Merge-Tree)詳解

1. 什么是 LSM-Tree? LSM-Tree(Log-Structured Merge-Tree)是一種 針對寫優化的存儲結構,廣泛用于 NoSQL 數據庫(如 LevelDB、RocksDB、HBase、Cassandra)等系統。 它的核心思想是: 寫入時只追加寫(Append-Only),將數據先寫入內存緩沖區(MemTable)。內存數據滿后…

LangChain組件Tools/Toolkits詳解(6)——特殊類型注解Annotations

LangChain組件Tools/Toolkits詳解(6)——特殊類型注解Annotations 本篇摘要14. LangChain組件Tools/Toolkits詳解14.6 特殊類型注解Annotations14.6.1 特殊類型注解分類14.6.1 InjectedToolArg構建運行時綁定值工具14.6.3 查看并傳入參數14.6.4 在運行時注入參數14.6.5 其它特…

openharmony中hilog實證記錄說明(3.1和5.0版本)

每次用這個工具hilog都有一些小用法記不清&#xff0c;需要花一些時間去查去分析使用方法&#xff0c;為了給豐富多彩的生活留出更多的時間&#xff0c;所以匯總整理共享來了&#xff0c;它來了它來了~~~~~~~~~ 開始是想通過3.1來匯總的&#xff0c;但實際測試發現openharmony…

NVIDIA nvmath-python:高性能數學庫的Python接口

NVIDIA nvmath-python&#xff1a;高性能數學庫的Python接口 NVIDIA nvmath-python是一個高性能數學庫的Python綁定&#xff0c;它為Python開發者提供了訪問NVIDIA優化數學算法的能力。這個庫特別適合需要高性能計算的科學計算、機器學習和數據分析應用。 文章目錄 NVIDIA nv…

【euclid】20 2D包圍盒模塊(box2d.rs)

box2d.rs文件定義了一個二維軸對齊矩形&#xff08;Box2D&#xff09;&#xff0c;使用最小和最大坐標來表示。矩形在坐標類型&#xff08;T&#xff09;和單位&#xff08;U&#xff09;上是泛型的。代碼提供了多種方法來操作和查詢矩形&#xff0c;包括求交集、并集、平移、縮…

ChatTTS 開源文本轉語音模型本地部署 API 使用和搭建 WebUI 界面

ChatTTS&#xff08;Chat Text To Speech&#xff09;&#xff0c;專為對話場景設計的文本生成語音(TTS)模型&#xff0c;適用于大型語言模型(LLM)助手的對話任務&#xff0c;以及諸如對話式音頻和視頻介紹等應用。支持中文和英文&#xff0c;還可以穿插笑聲、說話間的停頓、以…

鏈表相關知識總結

1、數據結構 基本概念&#xff1a; 數據項&#xff1a;一個數據元素可以由若干個數據項組成數據對象&#xff1a;有相同性質的數據元素的集合&#xff0c;是數據的子集數據結構&#xff1a;是相互之間存在一種或多種特定關系的數據元素的集合 邏輯結構和物理結構&#xff1a…

藍橋杯備考-》單詞接龍

很明顯&#xff0c;這道題是可以用DFS來做的&#xff0c;我們直接暴力搜索&#xff0c;但是這里有很多點是我們需要注意的。 1.我們如何確定兩個單詞能接上&#xff1f; 比如touch和choose 應該合成為touchoose 就是這樣兩個單詞&#xff0c;我們讓一個指針指著第一個字符串…

C語言-訪問者模式詳解與實踐

C語言訪問者模式詳解與實踐 - 傳感器數據處理系統 1. 什么是訪問者模式&#xff1f; 在嵌入式系統中&#xff0c;我們經常需要對不同傳感器的數據進行多種處理&#xff0c;如數據校準、過濾、存儲等。訪問者模式允許我們在不修改傳感器代碼的情況下&#xff0c;添加新的數據處…