SpringBoot+uniapp+jsapi微信支付,找了了好久资料,自己记录一下

  • 1. 申请小程序并认证
    • 1) 获取AppID和AppSecret
    • 2) 配置服务器域名
    • 3) 关联商户号
  • 2.申请微信商户号
    • 1) 申请安全证书
    • 2)申请jsapi支付
    • 3)开发设置也要配一下
  • 3.授权登录uniapp代码
    • 1)先让用户授权登录,顺便获取一下openid
    • 2) 授权登录java代码
  • 4.支付相关代码
    • 1)uniapp支付代码
    • 2) java代码

1. 申请小程序并认证

1) 获取AppID和AppSecret

开发管理->开发设置

2) 配置服务器域名

wx需要https的域名+端口号(ip地址好像不行)
开发管理->开发设置

3) 关联商户号

微信支付->商户号管理

填写一些资料就可以了,但是不知道为啥我这里关联后不显示,但是在商户号端能查询到.

2.申请微信商户号

1) 申请安全证书

申请之后在账户中心->API安全申请两个证书

证书设置这里百度上有资料,就不说了.

2)申请jsapi支付

产品中心->我的产品->jsapi支付
当初做的时候商户号里面的支付太多了,不知道申请哪个,但是以我的资质就只能申请这个… 万幸这个就是我想要的
网上找的图,jsapi支付和这个差不多(先说好啊,互联网的精神就是分享,希望上传这张图片的大佬不要找我)

3)开发设置也要配一下

3.授权登录uniapp代码

支付需要用到用户的openid,所以得先获取到

1)先让用户授权登录,顺便获取一下openid

我记得这个方法好像只能用按钮触发,也就是需要写一个授权登录的按钮,点击调用这个方法

<view class="diygw-col-0 text-white" v-on:click="dianji" style="font-size: 24rpx;"> 点击授权 </view>

这个代码需要写在uniapp的methods里面


dianji(){uni.getUserProfile({lang: 'zh_CN',desc: '用于登陆',success: function (wxInfo) {uni.login({provider:'weixin',success: function (res) {let data={code:res.code,userInfo: JSON.stringify(wxInfo.userInfo)}//这里说白了就是用getUserProfile获得的code请求wx的地址换取openid//剩下的俩参数一个是用户头像和昵称,传过去是因为我想直接存在数据库里面uni.request({url:url+"/callBack",data:{"code":data.code,"avatarUrl":wxInfo.userInfo.avatarUrl,"nickName":wxInfo.userInfo.nickName},success: (res) => {}})},});},fail: function (res) {wx.showModal({title: '友情提示',content: '已拒绝小程序获取信息',showCancel: !1,})}})
}

2) 授权登录java代码

工具类

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;public class AuthUtil {public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {JSONObject jsonObject = null;HttpClient client=new DefaultHttpClient();HttpGet httpGet = new HttpGet(url);HttpResponse response = client.execute(httpGet);HttpEntity entity = response.getEntity();if (entity != null) {String result = EntityUtils.toString(entity, "UTF-8");jsonObject = JSONObject.fromObject(result);}httpGet.releaseConnection();return jsonObject;}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;public class HttpUtils {private final static int CONNECT_TIMEOUT = 5000; // in millisecondsprivate final static String DEFAULT_ENCODING = "UTF-8";public static String sendGet(String url) {String result = "";BufferedReader in = null;try {URL realUrl = new URL(url);// 打开和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();// 获取所有响应头字段// 遍历所有的响应头字段// 定义 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) {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("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(param);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;while ((line = in.readLine()) != null) {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 postData(String urlStr, String data, String contentType){BufferedReader reader = null;try {URL url = new URL(urlStr);URLConnection conn = url.openConnection();conn.setDoOutput(true);conn.setConnectTimeout(CONNECT_TIMEOUT);conn.setReadTimeout(CONNECT_TIMEOUT);if(contentType != null)conn.setRequestProperty("content-type", contentType);OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);if(data == null)data = "";writer.write(data);writer.flush();writer.close();reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));StringBuilder sb = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) {sb.append(line);sb.append("\r\n");}return sb.toString();} catch (IOException e) {//logger.error("Error connecting to " + urlStr + ": " + e.getMessage());} finally {try {if (reader != null){reader.close();}} catch (IOException e) {}}return null;}
}
import javax.servlet.http.HttpServletRequest;public class IpUtils {/*** @TODO : 获取ip* @return_type : String* @param request* @return*/public static String getIpAddr(HttpServletRequest request) {if (request == null){return "unknown";}String ip = request.getHeader("x-forwarded-for");if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){ip = request.getHeader("X-Forwarded-For");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){ip = request.getHeader("X-Real-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;}/*** @TODO : 获取浏览器类型* @return_type : String* @param request* @return*/public static String getBrowser(HttpServletRequest request) {String userAgent = request.getHeader("user-agent");if (userAgent.contains("Firefox")){return "火狐浏览器";}else if (userAgent.contains("Chrome")){return "谷歌浏览器";}else if (userAgent.contains("Trident")){return "IE浏览器";}else{return "浏览器";}}
}

XXX替换成自己的参数

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.UUID;import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;public class WxConstant {//AppIDpublic static final String APPID ="XXXXXXXXX";//小程序秘钥public static final String APPSECRET="XXXXXXXXXXXXX";//商户号public static String weChatPayMchId = "XXXXXXXX";//支付key 商户秘钥  商户号里你自己设置的32位密码public static String weChatPayKey = "XXXXXXXXXXXXXXX";public static String weChatRedirectUri = "http://www.baidu.com";//支付回调地址  写本项目的地址就行public static String weChatPayNotifyUrl = "https://xxxxxxx:端口号/weChatPayNotify";public static String weChatAuthorizeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";public static String weChatAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";public static String weChatUserinfoUrl = "https://api.weixin.qq.com/sns/userinfo";public static String weChatPayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";public static String weChatPayOrderQueryUrl = "https://api.mch.weixin.qq.com/pay/orderquery";//private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";private static final String SYMBOLS2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";private static final Random RANDOM = new SecureRandom();/*** 获取微信Jsapi的accessToken*/public static String getAccessToken() throws IOException{String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";url = url.replace("APPID",APPID).replace("APPSECRET",APPSECRET);String result = HttpUtils.sendGet(url);JSONObject jsonObject = JSON.parseObject(result);String accessToken = jsonObject.getString("access_token");return accessToken;}/**** @Title: getNonceStr* @Description: 生成随机字符串* @param @return* @return String    返回类型* @throws*/public static String getNonceStr() {String currT = getCurrTime();String strT = currT.substring(8, currT.length());String strRandom = buildRandom(4) + "";return strT + strRandom;}/**** @Title: buildRandom* @Description: 生成随机数* @param @param length* @param @return* @return int    返回类型* @throws*/public static int buildRandom(int length) {int mm= 1;double random = Math.random();if (random < 0.1) {random = random + 0.1;}for (int i = 0; i < length; i++) {mm= mm* 10;}return (int) ((random * mm));}/**** @Title: getCurrTime* @Description: 获取当前时间* @param @return* @return String    返回类型* @throws*/public static String getCurrTime() {Date date = new Date();SimpleDateFormat of= new SimpleDateFormat("yyyyMMddHHmmss");String s = of.format(date);return s;}/*** 随机字符串* @return*/public static String generateNonceStr() {return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);}/**** @Title: createSignBySha1* @Description: 生成签名* @param @param params* @param @return* @return String    返回类型* @throws*/@SuppressWarnings("rawtypes")public static String createSignBySha1(SortedMap<Object, Object> params) {StringBuffer sb = new StringBuffer();Set es = params.entrySet();Iterator it = es.iterator();while (it.hasNext()) {Map.Entry entry = (Map.Entry) it.next();String k = (String) entry.getKey();String v = (String) entry.getValue();if (v != null && !v.equals("")) {sb.append(k + "=" + v + "&");}}String result = sb.toString().substring(0, sb.toString().length()-1);return getSHA1(result);}/**** @Title: getTimestamp* @Description: 获取时间戳(秒)* @param @return    参数* @return String    返回类型* @throws*/public static String getTimestamp() {return String.valueOf(System.currentTimeMillis() / 1000);}/**** @Title: getSHA1* @Description: SHA1签名生成* @param @param str* @param @return    参数* @return String    返回类型* @throws*/public static String getSHA1(String str){StringBuffer hexstr = new StringBuffer();try {MessageDigest md = MessageDigest.getInstance("SHA-1");md.update(str.getBytes());byte[] digest = md.digest();String shaHex = "";for (int i = 0; i < digest.length; i++) {shaHex = Integer.toHexString(digest[i] & 0xFF);if (shaHex.length() < 2) {hexstr.append(0);}hexstr.append(shaHex);}} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return hexstr.toString();}/**** @Title: getJsapiTicket* @Description: 获取JsapiTicket* @param @param access_token* @param @return* @return String    返回类型* @throws*/public static String getJsapiTicket(String access_token)  throws IOException{String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi".replace("ACCESS_TOKEN",access_token);String result = HttpUtils.sendGet(url);JSONObject jsonObject = JSON.parseObject(result);String ticket= jsonObject.getString("ticket");return ticket;}public static String createLinkString(Map<String, String> params){List<String> keys = new ArrayList<String>(params.keySet());Collections.sort(keys);String prestr = "";for (int i = 0; i < keys.size(); i++) {String key = keys.get(i);String value = params.get(key);
//          try {//              value = URLEncoder.encode(value, "UTF-8");
//          }catch (Exception e){//              e.printStackTrace();
//          }if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符prestr = prestr + key + "=" + value;} else {prestr = prestr + key + "=" + value + "&";}}return prestr;}public static String generateSignature(final Map<String, String> data, String key, String signType) throws Exception {Set<String> keySet = data.keySet();String[] keyArray = keySet.toArray(new String[keySet.size()]);Arrays.sort(keyArray);StringBuilder sb = new StringBuilder();for (String k : keyArray) {if (k.equals("sign")) {continue;}if (data.get(k).trim().length() > 0) {//参数值为空,则不参与签名sb.append(k).append("=").append(data.get(k).trim()).append("&");}}sb.append("key=").append(key);if ("MD5".equals(signType)) {return MD5(sb.toString()).toUpperCase();}else if ("HMACSHA256".equals(signType)) {return HMACSHA256(sb.toString(), key);}else {throw new Exception(String.format("Invalid sign_type: %s", signType));}}public static String MD5(String data) throws Exception {java.security.MessageDigest md = MessageDigest.getInstance("MD5");byte[] array = md.digest(data.getBytes("UTF-8"));StringBuilder sb = new StringBuilder();for (byte item : array) {sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));}return sb.toString().toUpperCase();}public static String HMACSHA256(String data, String key) throws Exception {Mac sha256_HMAC = Mac.getInstance("HmacSHA256");SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");sha256_HMAC.init(secret_key);byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));StringBuilder sb = new StringBuilder();for (byte item : array) {sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));}return sb.toString().toUpperCase();}public static String mapToXml(Map<String, String> map) throws Exception {StringBuffer sb = new StringBuffer();sb.append("<xml>");Set<String> set = map.keySet();Iterator<String> it = set.iterator();while (it.hasNext()) {String key = it.next();sb.append("<" + key + ">").append(map.get(key)).append("</" + key + ">");}sb.append("</xml>");return sb.toString();}public static Map<String, String> xmlToMap(String strXML) throws Exception {try {Map<String, String> data = new HashMap<String, String>();DocumentBuilder documentBuilder = newDocumentBuilder();InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));org.w3c.dom.Document doc = documentBuilder.parse(stream);doc.getDocumentElement().normalize();NodeList nodeList = doc.getDocumentElement().getChildNodes();for (int idx = 0; idx < nodeList.getLength(); ++idx) {Node node = nodeList.item(idx);if (node.getNodeType() == Node.ELEMENT_NODE) {org.w3c.dom.Element element = (org.w3c.dom.Element) node;data.put(element.getNodeName(), element.getTextContent());}}try {stream.close();} catch (Exception ex) {// do nothing}return data;} catch (Exception ex) {getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);throw ex;}}public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);documentBuilderFactory.setXIncludeAware(false);documentBuilderFactory.setExpandEntityReferences(false);return documentBuilderFactory.newDocumentBuilder();}public static Document newDocument() throws ParserConfigurationException {return newDocumentBuilder().newDocument();}public static Logger getLogger() {Logger logger = LoggerFactory.getLogger("wxpay java sdk");return logger;}/*** @TODO :* @AUTH : linfeng* @DATE : 2020年10月19日 上午9:34:49* @return_type : String* @return*/public static String generateNonceStr5() {char[] nonceChars = new char[6];for (int index = 0; index < nonceChars.length; ++index) {nonceChars[index] = SYMBOLS2.charAt(RANDOM.nextInt(SYMBOLS2.length()));}return new String(nonceChars);}public static byte[] readInput(InputStream in) throws IOException {ByteArrayOutputStream out = new ByteArrayOutputStream();int len = 0;byte[] buffer = new byte[1024];while ((len = in.read(buffer)) > 0) {out.write(buffer, 0, len);}out.close();in.close();return out.toByteArray();}
}

登录请求

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;@RestController
@CrossOrigin(value ="*")
public class WxLogin {@Autowiredusermapper usermapper;/**** @param code        登录后获取到的code,使用code换取openid* @param avatarUrl   用户头像* @param nickName    用户名* @return* @throws IOException*/@RequestMapping("/callBack")protected Boolean callBack(String code,String avatarUrl,String nickName) throws IOException {//拼接urlString url = "https://api.weixin.qq.com/sns/jscode2session?appid="+WxConstant.APPID+"&secret="+WxConstant.APPSECRET+"&js_code=" + code + "&grant_type=client_credential";JSONObject jsonObject = AuthUtil.doGetJson(url);//1.获取微信用户的openidString openid = jsonObject.getString("openid");//查询数据库中是否有该用户user userIsEmpty = usermapper.getUserIsEmpty(openid);//如果没有则加入到数据库中if (userIsEmpty==null){usermapper.addUser(nickName,avatarUrl,openid);//true为新用户return true;}else{//false为老用户return false;}}
}

搞了这么多才刚刚完成微信登录

4.支付相关代码

1)uniapp支付代码

//这里需要的参数是用户的openid和支付金额
<view class="diygw-col-24 text2-clz" @click="wxPay(openid,money)" style="font-size: 25rpx;"> 付款 </view>
wxPay(openid,money){//先去请求后端获得支付相关的参数uni.request({url:url+"/pay",method:"POST",header:{'content-type': 'application/x-www-form-urlencoded'},data:{"userid":openid,//这里需要*100 因为wx支付是以分(一分钱的分)为单位的"money":money*100},success: (res) => {//这里是请求后端获得的参数,使用这个参数来发起付款请求//这里这样赋值其实有点多余,是因为当时查了很多资料给出的参数各种各样,所以说还是得看官方文档this.appid=res.data.appID;this.nonceStr=res.data.nonceStr;this.package=res.data.package;this.timeStamp=res.data.timeStamp;this.paySign=res.data.paySign;uni.requestPayment({"provider": "wxpay",  //固定值为"wxpay""appid": this.appid,  // 微信开放平台 - 应用 - AppId,注意和微信小程序、公众号 AppId 可能不一致"nonceStr": this.nonceStr, // 随机字符串"package": this.package,   "signType": 'MD5',// 固定值// "partnerid": res.data.partnerid,      // 微信支付商户号// "prepayid": res.data.prepayid, // 统一下单订单号 "timeStamp": this.timeStamp,        // 时间戳(单位:秒)"paySign":this.paySign ,// 签名,这里用的 MD5/RSA 签名success: function (res2) {uni.showToast({icon:"success",title:"付款成功"})console.log("支付成功");},fail: function (err) {uni.showToast({icon:"success",title:"付款失败"})console.log('支付失败:' + JSON.stringify(err));}});},})
}

2) java代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;/*** @Author xyd* @Date 2022/9/27 18:17* @Version 1.0*/@RestController
@CrossOrigin(value ="*")
public class WxPayController {@Autowiredusermapper usermapper;/*** 获取微信预支付订单,返回给前端就行* @param request* @return*/@RequestMapping(value = "/pay",method = RequestMethod.POST,produces = "application/json;charset=utf-8")public Map<String,String> weChatPay(HttpServletRequest request,@RequestParam(name = "openid" )String openid,@RequestParam(name = "money" )String money) {//接收前端post请求中的参数String ip = IpUtils.getIpAddr(request);String[] ipArr = ip.split(",");//调用微信统一下单接口Map<String, String> map = new HashMap<>();//公众账号IDmap.put("appid", WxConstant.APPID);//商户号map.put("mch_id", WxConstant.weChatPayMchId);//随机字符串map.put("nonce_str", WxConstant.generateNonceStr());//商品描述map.put("body", "pay");//商户订单号map.put("out_trade_no", WxConstant.generateNonceStr());//标价金额 转换成分 微信发起付款请求要求是字符串map.put("total_fee", money);//交易类型map.put("trade_type", "JSAPI");//终端IPmap.put("spbill_create_ip", ipArr[0]);//通知地址map.put("notify_url", WxConstant.weChatPayNotifyUrl);//openid 如何获取查询微信支付官方文档map.put("openid", openid);//签名类型map.put("sign_type", "MD5");//签名try {map.put("sign", WxConstant.generateSignature(map, WxConstant.weChatPayKey, "MD5"));} catch (Exception e) {e.printStackTrace();}String resultXml = null;Map<String, String> resultMap = null;try {resultXml = HttpUtils.postData(WxConstant.weChatPayUrl, WxConstant.mapToXml(map),"utf-8");} catch (Exception e) {e.printStackTrace();}try {resultMap = WxConstant.xmlToMap(resultXml);} catch (Exception e) {e.printStackTrace();}System.out.println(resultMap);if(resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")) {//成功之后保存自己的业务逻辑System.out.println("成功");Map<String, String> dataMap = new HashMap<>();dataMap.put("appId", WxConstant.APPID);dataMap.put("timeStamp", System.currentTimeMillis()/1000+"");dataMap.put("nonceStr", WxConstant.generateNonceStr());dataMap.put("package", "prepay_id=" + resultMap.get("prepay_id"));dataMap.put("signType", "MD5");try {dataMap.put("paySign", WxConstant.generateSignature(dataMap, WxConstant.weChatPayKey, "MD5"));} catch (Exception e) {e.printStackTrace();}System.out.println(dataMap);return dataMap;}else {Map<String, String> map1= new HashMap<>();map1.put("code","error");return map1;}}/*** 支付回调* @param request* @return*/@RequestMapping("/weChatPayNotify")public String weChatPayNotify(HttpServletRequest request) {String resultStr = "";Map<String, String> returnMap = new HashMap<>();try {resultStr = new String(WxConstant.readInput(request.getInputStream()),"utf-8");System.out.println("支付回调:"+resultStr);Map<String, String> resultMap = WxConstant.xmlToMap(resultStr);String resultCode = resultMap.get("result_code");String returnCode = resultMap.get("return_code");if("SUCCESS".equals(returnCode)&&"SUCCESS".equals(resultCode)) {Map<String, Object> map = new HashMap<>();map.put("out_trade_no =?", resultMap.get("out_trade_no"));/** 自己的业务逻辑 根据out_trade_no  查询订单信息**/returnMap.put("return_code", "SUCCESS");returnMap.put("return_msg", "OK");return WxConstant.mapToXml(returnMap);}else {return "";}} catch (Exception e) {e.printStackTrace();return "";}}
}

到这里就结束了,按流程沾进来80%成功,剩下的20%祈祷吧,毕竟没有100%好使的代码!

springboot+uniapp授权登录+jsapi支付相关推荐

  1. uniappH5+springboot微信授权登录获取用户数据(非静默授权)

    uniappH5+springboot微信授权登录获取用户数据(非静默授权) 微信网页授权开发文档 准备工作 微信公众号appid和appSecret及配置相关的ip白名单 配置网页授权域名,具体操作 ...

  2. springboot微信授权登录

    水平有限!实现方法直接找的网上的以为大神所编写的api来实现,这里主要是记录一下自己实现的过程.具体方法请参考网址:https://github.com/liyiorg/weixin-popular, ...

  3. uniapp授权登录微信支付宝小程序获取code和基础信息

    项目背景:采用uniapp框架开发微信和支付宝两端小程序,前端授权基础信息和code传给后端获取openid(微信)和user_id(支付宝)建立用户体系. 项目描述:之前分开用原生框架开发的时候,都 ...

  4. uni-app授权登录,获取用户信息及用户手机号

    最近刚接触了uni-app,用于开发微信小程序,设计到了微信授权登录.抽个时间整理个笔记,适用于向我一样刚开始上手uni-app的初学者. 首先要明确uni-app框架有自己的开发一套开发流程,和微信 ...

  5. 微信网页-授权登录-分享-支付

    一个H5全部涉及,第一次使用,记录下来. 授权登录 1.需要一个公众号,正式没有可以去申请个测试的公众号,公众号后台授权管理配置授权回调域名. 2.jssdk提供了一个授权的地址,直接跳转过去即可 f ...

  6. uni-app授权登录功能的实现,包括微信授权、QQ授权

    今天讲述一下购靓号平台APP的两种常用授权登录方式,废话不多说,公众号搜索[购靓号]自行体验.个人引以为豪的作品.哈哈哈 首先是APP微信授权登录 APP微信授权需要到微信开放平台申请,在hbuild ...

  7. uniapp授权登录

    一.uni.getProvider 获取服务供应商 获取服务供应商 - uni-app官网 (dcloud.io) // 获取服务供应商uni.getProvider({service: 'oauth ...

  8. angularjs 微信授权登录 微信支付

    最近做一个项目,用angular 一个单页应用,打算打包成 跨平台移动App 以及在微信里面使用.给大家一个案例 首先,熟悉一下微信授权部分的源代码,如下所示: javascript 前端代码: va ...

  9. niushop打包云闪付小程序,调起云闪付授权登录

    首先niushop打包云闪付小程序,比较简单,不用配置专门的打包按钮,直接打包h5就行. 使用niushop做云闪付牵涉到授权登录.支付等,这里先讲讲授权登录. 首先调用upsdk.pluginRea ...

最新文章

  1. mysql connection闪退重连_玩家排位巅峰赛开局闪退,重连失败,10分钟后一个提示让他懵了...
  2. 嘻哈说:开放封闭原则
  3. Spring 一二事(4) - 单例
  4. hapi lab测试框架简单使用
  5. php 类学习,php的类学习(一)
  6. golang学习之旅(2)- go的数据基本数据类型及变量定义方式
  7. 每天一个小异常——ssh整合空指针异常
  8. SQL注入分类,一看你就明白了。SQL注入点/SQL注入类型/SQL注入有几种/SQL注入点分类
  9. 序《戎马书生马福祥》
  10. 图片适应窗口_毕业论文排版保姆级教程——图片和公式排版
  11. POJ1579 HDU1331 HDU1579 ZOJ1168 Function Run Fun【记忆化递归】
  12. Studio One 5 Professional for Mac(多功能数字音频工作站)
  13. Oracle12c创建可插入式数据库pdb和连接pdb并创建用户心得
  14. 验证英文日期格式的正则表达式
  15. 原来这才是折叠屏的刚需...
  16. Ubuntu 软件仓库源
  17. 费马小定理简单证明和一些简单应用
  18. 2345看图王批量重命名照片
  19. cad vba 打开文件对话框_AutoCAD VBA选择文件夹的代码
  20. 快手 7 月起取消大小周引发热议

热门文章

  1. android 打开闪光灯
  2. 高新技术企业认定不通过存在的原因
  3. 用PDF编辑器有哪些方法可以提取页面?
  4. redis中有key但是删不掉_Redis大key的发现与删除方法全解析
  5. 推荐三款强大且漂亮的统计图控件
  6. 基于微信小程序的智能停车场管理系统的设计与实现
  7. 健身俱乐部如何让会员持续满意?
  8. Hybrid A*学习
  9. 无人驾驶汽车系统入门(二十二)——使用Autoware实践激光雷达与摄像机组合标定
  10. 2014年武汉的IT行情好像不太好(续):20个月过后,再看当时面试过的几个公司--武汉财富基石-崩盘,辣妈萌宝-创业失败,朋友公司转交他人管理