springboot微信支付pc页面生成二维码
生活随笔
收集整理的這篇文章主要介紹了
springboot微信支付pc页面生成二维码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
微信支付開發文檔:https://pay.weixin.qq.com/wiki/doc/api/index.html
咱們這次采用的是Native支付
Native支付使用場景:用戶打開"微信掃一掃“,掃描商戶的二維碼后完成支付
微信提供的api如下,咋們這次只使用統一下單的api。
?首先你得準備如下商號配置:
weixin:appid: wx8397f8696b538317 #微信公眾賬號或開放平臺APP的唯一標識partner: 1473426802 #財付通平臺的商戶賬號partnerkey: T6m9iK73b0kn9g5v426MKfHQH7X8rKwb #財付通平臺的商戶密鑰notifyurl: http://www.itcast.cn #回調地址寫入application.yml文件
server:port: 8040#微信支付信息配置: 這里請填寫自己的id.... weixin:appid: wx8397f8696b538317 #微信公眾賬號或開放平臺APP的唯一標識partner: 1473426802 #財付通平臺的商戶賬號partnerkey: T6m9iK73b0kn9g5v426MKfHQH7X8rKwb #財付通平臺的商戶密鑰notifyurl: http://www.itcast.cn #回調地址pom文件如下:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.21</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>1.7.21</version></dependency><dependency><groupId>jdom</groupId><artifactId>jdom</artifactId><version>1.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.4</version></dependency><!-- 微信支付依賴!xml————map相互轉換 --><dependency><groupId>com.github.wxpay</groupId><artifactId>wxpay-sdk</artifactId><version>0.0.3</version></dependency><!-- HttpClient工具包 --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><!-- 其它需要的依賴配置...父工程 statrt-web.... --><!-- 二維碼 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.2.0</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.2.0</version></dependency> HttpClient工具類 import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; 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.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext; import java.io.IOException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map;public class HttpClient {private String url;private Map<String, String> param;private int statusCode;private String content;private String xmlParam;private boolean isHttps;public boolean isHttps() {return isHttps;}public void setHttps(boolean isHttps) {this.isHttps = isHttps;}public String getXmlParam() {return xmlParam;}public void setXmlParam(String xmlParam) {this.xmlParam = xmlParam;}public HttpClient(String url, Map<String, String> param) {this.url = url;this.param = param;}public HttpClient(String url) {this.url = url;}public void setParameter(Map<String, String> map) {param = map;}public void addParameter(String key, String value) {if (param == null)param = new HashMap<String, String>();param.put(key, value);}public void post() throws ClientProtocolException, IOException {HttpPost http = new HttpPost(url);setEntity(http);execute(http);}public void put() throws ClientProtocolException, IOException {HttpPut http = new HttpPut(url);setEntity(http);execute(http);}public void get() throws ClientProtocolException, IOException {if (param != null) {StringBuilder url = new StringBuilder(this.url);boolean isFirst = true;for (String key : param.keySet()) {if (isFirst) {url.append("?");}else {url.append("&");}url.append(key).append("=").append(param.get(key));}this.url = url.toString();}HttpGet http = new HttpGet(url);execute(http);}/*** set http post,put param*/private void setEntity(HttpEntityEnclosingRequestBase http) {if (param != null) {List<NameValuePair> nvps = new LinkedList<NameValuePair>();for (String key : param.keySet()) {nvps.add(new BasicNameValuePair(key, param.get(key))); // 參數}http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 設置參數}if (xmlParam != null) {http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));}}private void execute(HttpUriRequest http) throws ClientProtocolException,IOException {CloseableHttpClient httpClient = null;try {if (isHttps) {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {// 信任所有@Overridepublic boolean isTrusted(X509Certificate[] chain,String authType)throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();} else {httpClient = HttpClients.createDefault();}CloseableHttpResponse response = httpClient.execute(http);try {if (response != null) {if (response.getStatusLine() != null) {statusCode = response.getStatusLine().getStatusCode();}HttpEntity entity = response.getEntity();// 響應內容content = EntityUtils.toString(entity, Consts.UTF_8);}} finally {response.close();}} catch (Exception e) {e.printStackTrace();} finally {httpClient.close();}}public int getStatusCode() {return statusCode;}public String getContent() throws ParseException, IOException {return content;} } PayController import com.github.wxpay.sdk.WXPayUtil; import com.sws.weixin.services.PayService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map;@RestController @RequestMapping("/weixin") public class PayController {@Autowiredprivate PayService payService;@GetMapping("/pay")public Object pay(String out_trade_no, String total_fee) throws Exception {//調用:統一下單!Map<String, String> pay = payService.pay("5000", "1");return pay;}//回調函數//必須得是post 的方式,這里查看yml: http://wsm.free.idcfengye.com/weixin/notifyurl /weixin/notifyurl 綁定的回調就是這個方法!@PostMapping("/notifyurl")public String notifyurl(HttpServletRequest request) {System.out.println("支付后回調---------------------------");InputStream is = null;ByteArrayOutputStream baos = null;try {is = request.getInputStream();baos = new ByteArrayOutputStream();byte[] bytes = new byte[1024];int len = 0;while ((len = is.read(bytes)) != -1) {baos.write(bytes, 0, len);}String str = new String(baos.toByteArray(), "UTF-8");System.out.println(str);//響應數據,如果不寫, 商戶就不會接受微信的回調,微信就會24小時內頻繁進行響應...Map respMap = new HashMap();respMap.put("return_code", "SUCCESS");respMap.put("return_msg", "OK");return WXPayUtil.mapToXml(respMap);//處理異常,最終關閉資源!} catch (Exception e) {e.printStackTrace();} finally {try {baos.close();is.close();} catch (IOException e) {e.printStackTrace();}}return "";} }接口
public interface PayService {public Map<String, String> pay(String out_trade_no, String total_fee) throws Exception; }實現接口
import com.github.wxpay.sdk.WXPayUtil; import com.sws.weixin.util.HttpClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map;@Service public class PayServiceimpl implements PayService{//從yml 中讀取對應的... yml配置屬性!@Value("${weixin.appid}")private String appid;@Value("${weixin.partner}")private String partner;@Value("${weixin.partnerkey}")private String partnerkey;@Value("${weixin.notifyurl}")private String notifyurl;//唯一訂單號 交易金額單位: 分@Overridepublic Map<String, String> pay(String out_trade_no, String total_fee) throws Exception{//設置統一下單: 請求參數;Map<String, String> param = new HashMap<>();param.put("appid", appid); //應用IDparam.put("mch_id", partner); //商戶ID號param.put("nonce_str", WXPayUtil.generateNonceStr()); //隨機數param.put("body", "My商場"); //訂單描述param.put("out_trade_no", out_trade_no); //商戶訂單號: 這是唯一的,會在微信存儲!param.put("total_fee", total_fee); //交易金額:param.put("spbill_create_ip", "127.0.0.1"); //終端IPparam.put("notify_url", notifyurl); //回調地址: 是后面需要進行商戶暴漏的回調接口!param.put("trade_type", "NATIVE"); //交易類型,NATIVEString xml = WXPayUtil.generateSignedXml(param, partnerkey); //將map 轉換成 xml 并傳入簽名String url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //統一下單的: api!//獲取HttpClient 請求對象!HttpClient httpClient = new HttpClient(url);//傳入參數,執行請求posthttpClient.setXmlParam(xml);httpClient.setHttps(true);httpClient.post();//獲取返回結果! 打印!String content = httpClient.getContent();System.out.println(content);//將返回xml 轉換成Map 方便展示輸出!Map<String, String> stringStringMap = WXPayUtil.xmlToMap(content);//輸出: 訂單號 金額 支付url(將這個綁定至上面的,二維碼中掃碼就可以,看到信息進行支付了!!)Map<String, String> result = new HashMap<>();result.put("out_trade_no", out_trade_no);result.put("total_fee", total_fee);result.put("code_url", stringStringMap.get("code_url"));//打印!System.out.println(stringStringMap.get("code_url"));return result;} }啟動項目訪問:http://localhost:8040/weixin/pay
code_url中的值為支付地址:weixin://wxpay/bizpayurl?pr=xxxxxxxx
將地址,采用前端js轉換成二維碼即可。
<html> <head> <title>二維碼入門小demo</title> <!--1.引入js 2. 創建一個img標簽 用來存儲顯示二維碼的圖片 3.創建js對象 4.設置js對象的配置項--> <script src="https://www.jq22.com/demo/erweima20161214/dist/umd/qrious.js"> </script> </head> <body><img id="myqrious" ></body><script>var qrious = new QRious({element:document.getElementById("myqrious"),// 指定的是圖片所在的DOM對象size:250, //指定圖片的像素大小level:'H', //指定二維碼的容錯級別(H:可以恢復30%的數據)value:'weixin://wxpay/bizpayurl?pr=xxxxxxxx'//指定二維碼圖片代表的真正的值})</script> </html>總結
以上是生活随笔為你收集整理的springboot微信支付pc页面生成二维码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS代码之《xml格式化》
- 下一篇: java简单的for循环多线程