1、后端調(diào)用方法獲取AccessToken的工具類
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
public class qrUtils {
// private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={secret}";;
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='輸入自己的小程序ID'&secret='輸入自己的小程序密鑰'";;
/**
* 獲取微信的appId的工具類,字符串之后需要JSON.parseObject轉(zhuǎn)化。
*
* @param
* @param
* @return 獲取結(jié)果
*/
public static String getAccessToken() {
String accesstoken=new String();
String requestUrl = ACCESS_TOKEN_URL;
// //傳入?yún)?shù)替換
// requestUrl = requestUrl.replaceAll("appId", appId);
// requestUrl = requestUrl.replaceAll("secret", secret);
//超時,需要重新請求接口
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(requestUrl, String.class);
JSONObject jsonObject = JSON.parseObject(result.toString());
accesstoken = jsonObject.getString("access_token");
return result;
}
}
2、獲取完AccessToken后調(diào)用微信小程序接口,寫一個微信小程序工具類
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.ruoyi.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class WeChatUtil {
// 這是獲取不受限制的小程序碼,官網(wǎng)還有其他兩種
private static final String WX_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=AccessToken";
// public static WxCodeUnlimitedResponseParam getUnlimitedCode(String accessToken, String scene, String page) {
public static WxCodeUnlimitedResponseParam getUnlimitedCode(String accessToken) {
JSONObject jsonObject = JSON.parseObject(accessToken.toString());
String accesstoken1 = jsonObject.getString("access_token");
// url請求參數(shù)值
Map<String, Object> params = new HashMap<String, Object>();
//**注意:接口文檔錯誤需要將access_token參數(shù)放到url中,否則請求會失敗
//scene為你需要傳入得參數(shù)類似“id=????&code=222”,為參數(shù)名和值組成得字符串。
// 這些參數(shù)微信小程序上官網(wǎng)上有,根據(jù)需求添加
params.put("scene", "type=1");
params.put("page", "page/index/index");
params.put("width", 200);
params.put("auto_color", true);
params.put("check_path",false);
params.put("line_color", null);
params.put("is_hyaline", false);
byte[] byteArray = null;
/** 第一種方式:使用RestTemplate。項目采用了這種方式。 **/
// 調(diào)用微信接口
WxCodeUnlimitedResponseParam res = new WxCodeUnlimitedResponseParam();
try {
RestTemplate restTemplate = new RestTemplate();
String request =WX_CODE_URL.replaceAll("AccessToken",accesstoken1);
ResponseEntity<byte[]> entity = restTemplate.postForEntity(
request,
JSONObject.toJSONString(params), byte[].class);
// 如果你十分確認(rèn)微信正確返回了圖片,那么byteArray已經(jīng)是你想要的結(jié)果了。
byteArray = entity.getBody();
// 微信返回內(nèi)容,byte[]轉(zhuǎn)為string
String wxReturnStr = new String(byteArray);
if (wxReturnStr.indexOf("errCode") != -1) {
JSONObject json = JSONObject.parseObject(wxReturnStr);
res.setErrCode(json.get("errCode").toString());
res.setErrMsg(json.get("errMsg").toString());
} else {
res.setErrCode("0");
res.setErrMsg("ok");
res.setBuffer(byteArray);
}
} catch (Exception e) {
System.out.println("右岸頂針");
System.out.println("微信小程序碼getUnlimited接口調(diào)用失敗");
}
System.out.println(res);
return res;
}
}
3、后端controller類,編寫一個接口來調(diào)用以上工具類生成二維碼并轉(zhuǎn)換成base64的方式傳回前端
/**
* 生辰二維碼
*/
@GetMapping("/getInviteCode")
@ResponseBody
public String getInviteCode(HttpServletResponse response) throws IOException {
String accessToken=qrUtils.getAccessToken();
WxCodeUnlimitedResponseParam res= WeChatUtil.getUnlimitedCode(accessToken);
// //以流的方式返回給前端
InputStream inputStream = new ByteArrayInputStream(res.getBuffer());
BufferedImage bufferedImage = ImageIO.read(inputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (bufferedImage != null){
String format = "jpeg";
System.out.println(bufferedImage);
ImageIO.write(bufferedImage, format, baos);
byte[] imageBytes = baos.toByteArray();
baos.close();
return Base64.getEncoder().encodeToString(imageBytes);
}
return null;
}
4、前端用的是vue2+elementUI
<!-- 查看二維碼對話框 -->
<el-dialog :title="title" :visible.sync="open_qr_code" width="700px" append-to-body v-dialogDrag custom-class="center-dialog">
<el-card shadow="always">
<el-image :src="QRcodeSrc"></el-image>
</el-card>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="handleDownloadQrIMg(QRcodeSrc)">點擊下載</el-button>
<el-button type="primary" @click="cancel_detail">關(guān) 閉</el-button>
</div>
</el-dialog>
/**
* 生成二維碼
* */
createQRCode() {
this.loading = true;
createQRcode().then(response => {
this.QRcodeSrc = "data:image/png;base64," + response;
this.open_qr_code = true;
this.loading = false;
})
},
/**
* 下載圖片
* @returns {string}
*/
//imageBase64是后臺傳回來的base64數(shù)據(jù)
handleDownloadQrIMg(imageBase64) {
// 這里是獲取到的圖片base64編碼,這里只是個例子哈,要自行編碼圖片替換這里才能測試看到效果
const imgUrl = `${imageBase64}`;
// 如果瀏覽器支持msSaveOrOpenBlob方法(也就是使用IE瀏覽器的時候),那么調(diào)用該方法去下載圖片
if (window.navigator.msSaveOrOpenBlob) {
const bstr = atob(imgUrl.split(',')[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const blob = new Blob([u8arr]);
window.navigator.msSaveOrOpenBlob(blob, '簽到碼.jpg');
} else {
// 這里就按照chrome等新版瀏覽器來處理
const a = document.createElement('a');
a.href = imgUrl;
a.setAttribute('download', 'filename.jpg');
a.click();
}
}
然后就大功告成了?。。。。?span toymoban-style="hidden">文章來源地址http://www.zghlxwxcb.cn/news/detail-842937.html
文章來源:http://www.zghlxwxcb.cn/news/detail-842937.html
到了這里,關(guān)于Java集成微信小程序生成二維碼傳回前端,提供下載按鈕的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!