生成带参数二维码的两种方法
需求介绍
业务需求,用户微信扫描二维码进入公众号中的某一个业务页面并可以完成相应的业务操作。
例如我的需求就是:用户扫描二维码进入公众号的居民满意度调查页面,用户在调查页面进行打分操作。
实现思路
- 生成包含小区ID和需要跳转的也公众号授权页面服务器路径参数的二维码图片;
- 将带参数的二维码图片保存至对应的图片服务器中。
- 生成对应的小区满意度调查通知(通知包含公众号二维码)。
- 打印通知张贴,扫描通知上的二维码进入调查打分页面。
关联公共号ID,获取token等基础操作在此省略,扫描二维码用户后续操作,不知道的可以查看上一篇微信公共号获取用户发送信息的前段内容,扫描二维码动作即是用户扫码推事件,设置事件类型值为scan。
方法一:通过微信生成带参数的二维码图片
package com.chachaba.app;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.chachaba.constant.result.CommonResult;
import com.chachaba.files.service.FilesService;
import com.chachaba.shiro.exception.ServiceException;
import com.chachaba.util.UrlEncode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 微信授权登录
*
* @author xingyu
* @date 2020年9月23日14:51:16
**/
@RestController
@RequestMapping("/app/wemp")
@Api(value = "wemp", description = "公众号专用接口,开发给前端")
public class APPWxMPUserController {
/**
* 微信公众号APPID
*/
private static final String APP_ID = "你的微信公众号APPID";
/**
* 微信公众号APPSECRET
*/
private static final String APPSECRET = "你的微信公众号APPSECRET";
/**
* 用户授权, 获取code参数的url地址
*/
private static final String LOGIN_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
/**
* 通过code获取access_token的url地址
*/
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
/**
* 通过access_token获取到微信用户信息的地址
*/
private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
@Autowired
private FilesService filesService;
@ApiOperation("获取微信授权的code并跳转到对应的url")
@ApiImplicitParam(name = "scope", value = "授权方式,值为snsapi_base或者snsapi_userinfo", paramType = "query", required = true, dataType = "String")
@RequestMapping("/getLoginUrl")
public CommonResult getLoginUrl(@ApiParam(name = "scope", value = "值有两个: snsapi_base 默认授权,获取不到WeChat用户详细信息 snsapi_userinfo弹出方式授权,可以获取到WeChat用户信息 ") String scope,
@ApiParam(name = "redirectUri", value = "用户同意授权后跳转的页面") String redirectUri,
@ApiParam(name = "state", value = "重定向后的参数") String state) throws Exception {
//获得url后面的参数
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("appid", APP_ID);
paramsMap.put("redirect_uri", URLEncoder.encode(redirectUri, "utf-8"));
paramsMap.put("response_type", "code");
paramsMap.put("scope", scope);
//重定向后带过去的参数
paramsMap.put("state", state);
String urlParams = UrlEncode.getUrlParams(paramsMap, true);
//微信官方要求必须带上#wechat_redirect
urlParams = "?" + urlParams + "#wechat_redirect";
Map<String, String> returnMap = new HashMap<>();
returnMap.put("url", LOGIN_URL + urlParams);
return new CommonResult(CommonResult.SUCCESS_CODE, "success", returnMap);
}
@ApiOperation("通过code获取到ACCESS_TOKEN")
@RequestMapping("/getAccessToken")
public CommonResult getAccessToken(@ApiParam(name = "code", value = "用户同意授权后获取的code值") String code) throws Exception {
if (StringUtils.isBlank(code)) {
throw new ServiceException("code参数为null,请检查");
}
//获得url后面的参数
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("appid", APP_ID);
paramsMap.put("secret", APPSECRET);
paramsMap.put("code", code);
paramsMap.put("grant_type", "authorization_code");
String urlParams = UrlEncode.getUrlParams(paramsMap, true);
urlParams = "?" + urlParams;
//生成新的访问的URL地址
String url = ACCESS_TOKEN_URL + urlParams;
String getResult = HttpUtil
.createGet(url)
.execute()
.charset("gbk")
.body();
//获得到access_token
Map<String, Object> returnMap = JSONObject.parseObject(getResult);
//获取用户access_token
String accessToken = (String) returnMap.get("access_token");
//获取到用户唯一标识openid
String openid = (String) returnMap.get("openid");
Map<String, Object> userInfo = getUserInfo(accessToken, openid, "zh_CN");
return new CommonResult(CommonResult.SUCCESS_CODE, "success", userInfo);
}
/**
* 通过 accessToken换区 微信授权用户详细信息
*
* @param accessToken 上一步获取的access_token
* @param openid 用户唯一标识
* @param lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
*/
private Map<String, Object> getUserInfo(String accessToken, String openid, String lang) {
//获得url后面的参数
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("access_token", accessToken);
paramsMap.put("openid", openid);
paramsMap.put("lang", lang);
String urlParams = UrlEncode.getUrlParams(paramsMap, true);
urlParams = "?" + urlParams;
//生成新的访问的URL地址
String url = USER_INFO_URL + urlParams;
String getResult = HttpUtil
.createGet(url)
.execute()
.charset("utf-8")
.body();
//获取的到微信用户信息
return JSONObject.parseObject(getResult);
}
/**
* 临时生成字符二维码url
*/
private static final String GET_CODE_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
/**
* 二维码有效时间
*/
private static final String QR_ORDER_EXPIRE_TIME ="2592000";
/**
* 返回二维码链接url
*/
public final static String BACK_QR_CODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
/**
* 获取AccessToken
*/
public final static String ACCESS_TOKEN_URL1 = "https://api.weixin.qq.com/cgi-bin/token";
public static String getToken(){
//获得url后面的参数
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("appid", APP_ID);
paramsMap.put("secret", APPSECRET);
paramsMap.put("grant_type", "client_credential");
String urlParams = UrlEncode.getUrlParams(paramsMap, true);
urlParams = "?" + urlParams;
//生成新的访问的URL地址
String url = ACCESS_TOKEN_URL1 + urlParams;
String getResult = HttpUtil
.createGet(url)
.execute()
.charset("gbk")
.body();
//获得到access_token
Map<String, Object> returnMap = JSONObject.parseObject(getResult);
//获取用户access_token
String accessToken = (String) returnMap.get("access_token");
return accessToken;
}
//永久二维码请求说明
//http请求方式: POST URL: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
// POST数据格式:json POST数据例子:{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}
// 或者也可以使用以下POST数据创建字符串形式的二维码参数: {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "test"}}}
/**
* @description: 获取二维码ticket后,开发者可用ticket换取二维码图片。
* @author: gxy
* @time: 2020/10/28 16:42
* @version 1.0
*
*/
public static String getTicketData(String str) {
String token = getToken();
if (StringUtils.isEmpty(str) || token == null) {
return null;
}
// if (str.length() > 64) {
// return null;
// }
//临时字符二维码url
String url = (GET_CODE_TICKET_URL).replace("TOKEN", token);
//二维码参数,以及过期时间
String data = "{\"expire_seconds\": " + QR_ORDER_EXPIRE_TIME + ", \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"test\"}}}";
data = data.replace("test", str);
String result = WxHttpUtil.sendHttpByPost(url, data);
if (!StringUtils.isEmpty(result)) {
JSONObject jsonObject = JSONObject.parseObject(result);
str = jsonObject.getString("ticket");
System.out.println("ticket = {} " + str);
return str;
}
return null;
}
/**
* @description: 用户返回二维码链接url
* @time: 2020/10/28 16:42
* @version 1.0
*/
public static String getTicket(String data) {
String url = BACK_QR_CODE_URL + data;
return url;
}
/**
* 居民调查问卷地址
*/
public final static String CUSTOMER_SURVEY_URL = "你的业务页面服务器地址";
/**
* 图片服务上传地址
*
*/
public final static String FTP_SERVER_URL = "你的图片服务器地址";
/**
*@description: 生成二维码页面
* @time: 2020/10/28 16:42
* @version 1.0
* @param modelMap
* @param dId 小区ID
* @param dName 小区名称
* @return
*/
@RequestMapping(value = "/con/qrPage")
public String getCustomerMsg1(ModelMap modelMap,String dId,String dName) {
String url =CUSTOMER_SURVEY_URL+"?dId="+dId+"&dName="+dName;
String ticket= getTicketData(url);
if(StringUtils.isEmpty(ticket)){
//换区ticktUrl失败 返回403页面
return "403";
}
String ticketUrl = getTicket(ticket);
System.out.println("返回的二维码 url = {} "+ticketUrl);
//将返回的二维码下载成图片 本地地址
// downloadPicture(ticketUrl,dId,dName);
//直接写入FTP服务器 图片地址
String viewPath = filesService.qrCodeWirte2Ftp(ticketUrl,dId,dName);
//返回服务显示地址
return viewPath;
}
private static void downloadPicture(String urlList,String dId,String dName) {
URL url = null;
//int imageNumber = 0;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
// 本地地址及名称
String imageName = "F:/" + dId+ ".jpg";
FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
byte[] context = output.toByteArray();
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*@description: 扫描二维码页面
* 用户扫描带场景值二维码时,可能推送以下两种事件:
* 如果用户还未关注公众号,则用户可以关注公众号,关注后微信会将带场景值关注事件推送给开发者。
* 如果用户已经关注公众号,则微信会将带场景值扫描事件推送给开发者。
*/
// scancode_push:扫码推事件的事件推送
// 推送XML数据包示例:
//
// <xml><ToUserName><![CDATA[gh_e136c6e50636]]></ToUserName>
// <FromUserName><![CDATA[oMgHVjngRipVsoxg6TuX3vz6glDg]]></FromUserName>
// <CreateTime>1408090502</CreateTime>
// <MsgType><![CDATA[event]]></MsgType>
// <Event><![CDATA[scancode_push]]></Event>
// <EventKey><![CDATA[6]]></EventKey>
// <ScanCodeInfo><ScanType><![CDATA[qrcode]]></ScanType>
// <ScanResult><![CDATA[1]]></ScanResult>
// </ScanCodeInfo>
// </xml>
}
工具类WxHttpUtil.java
package com.chachaba.app;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WxHttpUtil {
/**
* @param url
* @param data 生成字符二维码的数据包
* @return
*
*/
public static String sendHttpByPost(String url ,String data ){
try {
URL urlPost = new URL(url);
URLConnection urlConnection = urlPost.openConnection();
//要发送数据出去,必须设置为可发送状态
urlConnection.setDoOutput(true);
//获取输出流
OutputStream outputStream = urlConnection.getOutputStream();
//写出数据
outputStream.write(data.getBytes());
outputStream.flush();
outputStream.close();
//获取输入流
InputStream is = urlConnection.getInputStream();
int size ;
byte[] jsonBytes = new byte[1024];
StringBuilder stringBuilder = new StringBuilder();
while ((size=is.read(jsonBytes))!=-1){
stringBuilder.append(new String(jsonBytes,0,size));
}
is.close();
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param url
* @param url 换取二维码的数据包
* @return
*
*/
public static String sendHttpByGet(String url){
try {
URL urlGet = new URL(url);
URLConnection urlConnection = urlGet.openConnection();
InputStream is = urlConnection.getInputStream();
int size ;
byte[] jsonBytes = new byte[1024];
StringBuilder stringBuilder = new StringBuilder();
while ((size=is.read(jsonBytes))!=-1){
stringBuilder.append(new String(jsonBytes,0,size));
}
is.close();
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解析xml 获取key-value
*
* @param inputStream
* @return
*/
public static Map<String, String> getXmlData(InputStream inputStream) {
Map<String, String> map = new HashMap<>(12);
//截取xml
SAXReader reader = new SAXReader();
try {
Document document = reader.read(inputStream);
//获取根节点
Element rootElement = document.getRootElement();
// h获取所有的节点
List<Element> elements = rootElement.elements();
for (Element e : elements) {
map.put(e.getName(), e.getStringValue());
}
} catch (DocumentException e) {
e.printStackTrace();
}
return map;
}
/**
* * @description 将xml字符串转换成map
* * @param xml
* * @return Map
*
*/
public static Map<String, String> readStringXmlOut(String xml) {
Map<String, String> map = new HashMap<>(12);
Document doc = null;
try {
doc = DocumentHelper.parseText(xml); // 将字符串转为XML
Element rootElt = doc.getRootElement(); // 获取根节点
@SuppressWarnings("unchecked")
List<Element> list = rootElt.elements();// 获取根节点下所有节点
for (Element element : list) { // 遍历节点
map.put(element.getName(), element.getText()); // 节点的name为map的key,text为map的value
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
方法二:通过ZXing生成带参数的二维码图片
/**
* 微信端授权满意度问卷地址
*/
private static String QR_CODE_CUSTOMER_SURVEY_URL = " http://服务地址/wx_jump_satisScore.html?dId=DID";
/**
* 图片服务上传地址
*http://183.61.244.2:9995/file/lhwy
*/
private String FTP_SERVER_URL = "你的图片服务器地址";
/**
* 生成小区的二维码图片(本地项目upload路径) 并上传至FTP服务器
* (方法需要修改 用多进程或者直接上传)
* @param request
* @param dId
*/
public void createQRCode(HttpServletRequest request, String dId) {
// 存放在二维码中的内容 存跳转授权页面
String text =(QR_CODE_CUSTOMER_SURVEY_URL).replace("DID",dId);
//设置图片上传路径
String url = request.getSession().getServletContext().getRealPath("/upload");
System.out.println(url);
// 嵌入二维码的图片路径
String imgPath = url + "/logo.jpg";
// 生成的二维码的路径及名称
String destPath = url+"/Community_QRcode/"+dId+".jpg";
try {
//生成二维码
QRCodeUtil.encode(text, imgPath, destPath, true);
//上传至.2服务器中
String destPath1 = "file:///"+destPath;
String viewPath = filesService.qrCodeWirte2Ftp(destPath1,dId,"");
// 解析二维码
// String str = QRCodeUtil.decode(destPath);
// // 打印出解析出的内容
// System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
工具类 QRCodeUtil.java
package com.chachaba.assess.controller;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
/**
* @Date: 2020/10/23 5:20 下午
* @Description: 二维码工具类
*/
public class QRCodeUtil {
//编码
private static final String CHARSET = "utf-8";
//文件格式
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
/**
* 生成二维码
* @param content 内容
* @param imgPath logo
* @param needCompress 是否需要压缩
* @return java.awt.image.BufferedImage
* @throws Exception
*/
public static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入logo
* @param source 二维码图片
* @param imgPath logo路径
* @param needCompress 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println("" + imgPath + " 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二维码,获得到输入流 log内嵌
* @param content 内容
* @param imgPath logo路径
* @param output 输入流
* @param needCompress 是否压缩
* @throws Exception
*/
public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}
/**
* 获取指定的logo文件输入流
* @param logoPath logo路径
* @return java.io.InputStream
*/
public static InputStream getResourceAsStream(String logoPath) {
return QRCodeUtil.class.getResourceAsStream(logoPath);
}
/**
* 将要解析的二维码的存放路径
* @param file 要解析的二维码
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二维码
* @param path 要解析的二维码路径
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}
/**
* 生成二维码
* @param content
* @param imgPath
* @param destPath
* @param needCompress
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
mkdirs(destPath);
// String file = new Random().nextInt(99999999)+".jpg";
// ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
ImageIO.write(image, FORMAT_NAME, new File(destPath));
}
}
fileService.java 图片上传FTP 部分代码
/**
* @descript 将公共号返回的二维码转成图片穿到服务器上
* @date 2020-10-30 下午1:57:24
* @vision 1.0
* @param urlList
* @param dId
* @param dName
* @return
*/
@Override
public String qrCodeWirte2Ftp(String urlList,String dId,String dName){
URL url = null;
String viewPath ="";
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
//ftp配置
FtpUtils instance = FtpUtils.getInstance();
String DeString = AESEncryption.getInstance().decrypt(this.userPwd);
instance.doInitConfig(this.hostName, this.port, this.userName, DeString);
instance.open();
String fileSavePath = "/upload/Community_QRcode";
String fileName = dId +".jpg";
boolean isSuccess = instance.upload(this.defaultDir + fileSavePath, fileName, dataInputStream);
//看看地址
log.info("看看地址"+fileSavePath + "/" + fileName);
if (!isSuccess) {
throw new ServiceException("上传失败");
}
viewPath = "你的图片查看服务地址" +fileSavePath + "/" + fileName;
//-------------关流-----------------
dataInputStream.close();
instance.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return viewPath;
}
wx_jump_satisScore.html 微信授权跳转业务页面相关代码
<script type="text/javascript" charset="utf-8">
$(function () {
var dId = getQueryVariable("dId");
// var dName = getQueryVariable("dName");
getUrl(dId);
});
/**
* 此页面起到一个连接的作用, 即为要跳转的页面生成code参数
*
* 跳转到投诉页面 tscl_list.html
*/
function getUrl(dId) {
var url = "你的物业页面(我的满意度调查页面)";
$.ajax({
//url :url1,
url: pre_server_url + "/app/wemp/getLoginUrl",
type: "GET",
data: {scope: "snsapi_userinfo", redirectUri: url,state :dId},
success: function (result) {
//跳转到投诉页面 [带code参数]
window.location.href = result.data.url;
}
})
}
/**
* 获取URL参数
* @param variable
* @returns {*}
*/
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
业务页面部分代码
//获取token
function gettoken(code) {
var getopenidurl = pre_server_url + 'app/wemp/getAccessToken?code='
var getoken = pre_server_url + 'wechatUser/addOrGetWechatUser'
$.ajax({
type: "get",
url: getopenidurl + code,
crossDomain: true,
async: false,
success: function (result) {
var openid = result.data.openid;
var country = result.data.country;
var province = result.data.province;
var city = result.data.city;
var sex = result.data.sex;
var nickname = result.data.nickname;
var headimgurl = result.data.headimgurl;
if (result.data.errcode == 41001) {
weixinid = window.localStorage.getItem('touristId');
return;
}
$.ajax({
type: "post",
url: getoken,
dataType: 'json',
data: { openid, country, province, city, sex, nickname, headimgurl },
crossDomain: true,
async: false,
success: function (result) {
//localStorage.setItem("uId", result.data.id);
window.localStorage.setItem("touristId", result.data.id);
weixinid = result.data.id;
}
});
}
});
}