最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

教你用Java在個人電腦上實(shí)現(xiàn)微信掃碼支付

 更新時間:2021年06月13日 11:35:48   作者:記或往  
今天給大家?guī)淼氖荍ava實(shí)戰(zhàn)的相關(guān)知識,文章圍繞著Java在個人電腦上實(shí)現(xiàn)微信掃碼支付展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下

Java實(shí)現(xiàn)PC微信掃碼支付

做一個電商網(wǎng)站支付功能必不可少,那我們今天就來盤一盤微信支付。

微信支付官方網(wǎng)站

在這里插入圖片描述

業(yè)務(wù)流程:

開發(fā)指引文檔

在這里插入圖片描述

支付服務(wù)開發(fā)前提準(zhǔn)備:

1.SDK下載:SDK

2.利用外網(wǎng)穿透,獲得一個外網(wǎng)域名:natapp

在這里插入圖片描述

3.APPID,商戶ID,密鑰
注:上面三個參數(shù)需要自己申請

開發(fā)階段:

導(dǎo)入依賴:

<!--eureka的客戶端依賴-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- http客戶端 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <!-- 二維碼 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.3</version>
        </dependency>
        <!-- 生成二維碼 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.3</version>
        </dependency>
        <!--websocket 服務(wù)器主動發(fā)送請求給websocket-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

微信支付配置類

/**
 * 微信支付配置
 */
public class MyWXConfig extends WXPayConfig {
    //賬戶的APPID
    @Override
    public String getAppID() {
        return "wx307113892f15a42e";
    }
    //商戶ID
    @Override
    public String getMchID() {
        return "1508236581";
    }
    //秘鑰
    @Override
    public String getKey() {
        return "HJd7sHGHd6djgdgFG5778GFfhghghgfg";
    }
    @Override
    public InputStream getCertStream() {
        return null;
    }
    @Override
    public IWXPayDomain getWXPayDomain() {
        return new WXPayDomain();
    }
    class WXPayDomain implements IWXPayDomain{
        @Override
        public void report(String domain, long elapsedTimeMillis, Exception ex) {
        }
        @Override
        public DomainInfo getDomain(WXPayConfig config) {
            return new DomainInfo("api.mch.weixin.qq.com",true);
        }
    }
}

websocket配置類:

package com.cloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

wensocket工具類:

package com.cloud.config;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * WebSocket工具類
 * ServerEndpoint配置websocket的名稱,和前臺頁面對應(yīng)
 */
@ServerEndpoint(value = "/eshop")
@Component
public class WebSocketUtils {

    //WebSocket的對話對象
    private static Session session = null;

    //建立和前臺頁面連接后的回調(diào)方法
    @OnOpen
    public void onOpen(Session session){
        System.out.println("建立連接"+session);
        //給連接賦值
        WebSocketUtils.session = session;
    }

    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println("收到前臺消息:" + message);
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        System.out.println("連接關(guān)閉");
        session.close();
    }

    /**
     * 向前臺發(fā)消息
     * @param message
     * @throws IOException
     */
    public static void sendMessage(String message) throws IOException {
        System.out.println("發(fā)送消息:" + message);
        if( WebSocketUtils.session != null) {
            WebSocketUtils.session.getBasicRemote().sendText(message);
        }
    }
}

service:

package com.cloud.service;

import com.cloud.utils.MyWXConfig;
import com.cloud.utils.WXPay;
import com.cloud.utils.WXPayUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信支付Service
 */
@Service
public class PayService {

    /**
     * 下單
     * @param goodsId 商品id
     * @param price 價格
     * @return 二維碼的URL
     */
    public Map<String, String> makeOrder(String goodsId, Long price) throws Exception {
        //創(chuàng)建支付對象
        MyWXConfig config = new MyWXConfig();
        WXPay wxPay = new WXPay(config);
        Map<String,String> map = new HashMap<>();
        map.put("appid",config.getAppID());
        map.put("mch_id",config.getMchID());
        map.put("device_info","WEB");
        map.put("nonce_str", UUID.randomUUID().toString().replace("-",""));
        map.put("body","商城購物");
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        map.put("out_trade_no", tradeNo);
        map.put("fee_type","CNY");
        map.put("total_fee",String.valueOf(price));
        map.put("notify_url","http://68dhbz.natappfree.cc/pay/rollback"); //微信對商戶后臺的回調(diào)接口
        map.put("trade_type","NATIVE");
        map.put("product_id",goodsId);
        //執(zhí)行統(tǒng)一下單
        Map<String, String> result = wxPay.unifiedOrder(map);
        System.out.println("result:"+result);
        //保存訂單號
        result.put("trade_no",tradeNo);
        return result;
    }

    /**
     * 生成二維碼
     * @param url
     * @param response
     */
    public void makeQRCode(String url, HttpServletResponse response){
        //通過支付鏈接生成二維碼
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 200, 200, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
            System.out.println("創(chuàng)建二維碼完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 檢查訂單狀態(tài)
     * @param tradeNo
     * @return
     * @throws Exception
     */
    public String checkOrder(String tradeNo) throws Exception {
        MyWXConfig config = new MyWXConfig();
        String str =
        "<xml>"+
           "<appid>"+config.getAppID()+"</appid>"+
            "<mch_id>"+config.getMchID()+"</mch_id>"+
            "<nonce_str>"+UUID.randomUUID().toString().replace("-","")+"</nonce_str>"+
            "<out_trade_no>"+tradeNo+"</out_trade_no>"+
            "<sign>5E00F9F72173C9449F802411E36208734B8138870ED3F66D8E2821D55B317078</sign>"+
        "</xml>";
        WXPay pay = new WXPay(config);
        Map<String,String> map = WXPayUtil.xmlToMap(str);
        Map<String, String> map2 = pay.orderQuery(map);
        String state = map2.get("trade_state");
        System.out.println("訂單"+tradeNo+",狀態(tài)"+state);
        return state;
    }
}

controller:

package com.cloud.controller;

import com.cloud.config.WebSocketUtils;
import com.cloud.service.PayService;
import com.cloud.utils.WXPayUtil;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author yanglihu
 */
@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private PayService payService;

    private String tradeNo;

    /**
     * 二維碼生成
     */
    @GetMapping("/code")
    public void qrcode(@RequestParam("goodsId")String goodsId,
                       @RequestParam("price")Long price,
                       HttpServletResponse response){
        try {
            Map<String,String> map = payService.makeOrder(goodsId, price);
            payService.makeQRCode(map.get("code_url"),response);
            System.out.println("生成訂單號:" + map.get("trade_no"));
            tradeNo = map.get("trade_no");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付后通知
     */
    @PostMapping("/rollback")
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //獲得微信傳來的xml字符串
        String str = Streams.asString(request.getInputStream());
        //將字符串xml轉(zhuǎn)換為Map
        Map<String, String> map = WXPayUtil.xmlToMap(str);
        //讀取訂單號
        String no = map.get("out_trade_no");
        //模擬修改商戶后臺數(shù)據(jù)庫訂單狀態(tài)
        System.out.println("更新訂單狀態(tài):"+no);
        //給微信發(fā)送消息
        response.getWriter().println("<xml>\n" +
                "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                "   <appid><![CDATA["+map.get("appid")+"]]></appid>\n" +
                "   <mch_id><![CDATA["+map.get("mch_id")+"]]></mch_id>\n" +
                "   <nonce_str><![CDATA["+map.get("nonce_str")+"]]></nonce_str>\n" +
                "   <openid><![CDATA["+map.get("openid")+"]]></openid>\n" +
                "   <sign><![CDATA["+map.get("sign")+"]]></sign>\n" +
                "   <result_code><![CDATA[SUCCESS]]></result_code>\n" +
                "   <prepay_id><![CDATA["+map.get("prepay_id")+"]]></prepay_id>\n" +
                "   <trade_type><![CDATA[NATIVE]]></trade_type>\n" +
                "</xml>");
        WebSocketUtils.sendMessage("ok");
    }

    /**
     * 檢查訂單狀態(tài)
     */
    @PostMapping("checkOrder")
    public String checkOrder() throws Exception {
        System.out.println("trade_no:" + tradeNo);
        if(StringUtils.isEmpty(tradeNo)){
            return null;
        }
        String success = payService.checkOrder(tradeNo);
        System.out.println("check:" + success);
        return success;
    }
}


支付頁面:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE">
		<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
		<title>樂優(yōu)商城--微信支付頁</title>
        <link rel="icon" href="/assets/img/favicon.ico" rel="external nofollow"  rel="external nofollow" >
    <link rel="stylesheet" type="text/css" href="css/webbase.css" rel="external nofollow"  rel="external nofollow"  />
    <link rel="stylesheet" type="text/css" href="css/pages-weixinpay.css" rel="external nofollow"  />
</head>
	<body>
		<!--頁面頂部白條條,由js動態(tài)加載-->
		<script type="text/javascript" src="plugins/jquery/jquery.min.js"></script>
		<div class="top"></div>
    	<script type="text/javascript">$(".top").load("shortcut.html");</script>		
			<div class="checkout py-container  pay">		
				<div class="checkout-steps">
					<div class="fl weixin">微信支付</div>
                    <div class="fl sao"> 
                        <p class="red">二維碼已過期,刷新頁面重新獲取二維碼。</p>                      
                        <div class="fl code">
                            <img src="http://api.eshop.com/pay/code?goodsId=11&price=1" alt="">
                            <div class="saosao">
                                <p>請使用微信掃一掃</p>
                                <p>掃描二維碼支付</p>
                            </div>
                        </div>
                        <div class="fl phone">
                        </div>
                    </div>
                    <div class="clearfix"></div>
				    <p><a href="pay.html" rel="external nofollow"  target="_blank">> 其他支付方式</a></p>
				</div>
			</div>
		</div>
<script type="text/javascript" src="js/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript" src="js/plugins/jquery.easing/jquery.easing.min.js"></script>
<script type="text/javascript" src="js/plugins/sui/sui.min.js"></script>
<script type="text/javascript" src="js/widget/nav.js"></script>
<script type="text/javascript">
	$(function(){
		$("ul.payType li").click(function(){
			$(this).css("border","2px solid #E4393C").siblings().css("border-color","#ddd");
		})
	})
</script>
<script>
	var websocket = null;
	//判斷當(dāng)前瀏覽器是否支持WebSocket
	if('WebSocket' in window){
		websocket = new WebSocket("ws://localhost:8888/eshop");
	}
	else{
		alert('Not support websocket')
	}
	//接收到消息的回調(diào)方法
	websocket.onmessage = function(event){
		console.log(event.data);
		if(event.data == "ok"){
			location.href = "paysuccess.html";
		}
	}
</script>
</body>

</html>

在這里插入圖片描述

成功頁面:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE">
		<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
		<title>樂優(yōu)商城--支付頁-成功</title>
		<link rel="icon" href="/assets/img/favicon.ico" rel="external nofollow"  rel="external nofollow" >
    <link rel="stylesheet" type="text/css" href="css/webbase.css" rel="external nofollow"  rel="external nofollow"  />
    <link rel="stylesheet" type="text/css" href="css/pages-paysuccess.css" rel="external nofollow"  />
</head>
	<body>
		<!--head-->	
		<!--頁面頂部白條條,由js動態(tài)加載-->
		<script type="text/javascript" src="plugins/jquery/jquery.min.js"></script>
		<div class="top"></div>
    	<script type="text/javascript">$(".top").load("shortcut.html");</script>	
		<div class="cart py-container">		
			<!--主內(nèi)容-->
			<div class="paysuccess">
				<div class="success">
					<h3><img src="img/_/right.png" width="48" height="48"> 恭喜您,支付成功啦!</h3>
					<div class="paydetail">
					<p>支付方式:微信支付</p>
					<p>支付金額:¥1006.00元</p>
					<p class="button"><a href="home-index.html" rel="external nofollow"  class="sui-btn btn-xlarge btn-danger">查看訂單</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="index.html" rel="external nofollow"  class="sui-btn btn-xlarge ">繼續(xù)購物</a></p>
				    </div>
				</div>
				
			</div>
		</div>
	
<script type="text/javascript" src="js/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript" src="js/plugins/jquery.easing/jquery.easing.min.js"></script>
<script type="text/javascript" src="js/plugins/sui/sui.min.js"></script>
<script type="text/javascript" src="components/ui-modules/nav/nav-portal-top.js"></script>
</body>

</html>

在這里插入圖片描述

java后臺顯示

在這里插入圖片描述

到此這篇關(guān)于教你用Java在個人電腦上實(shí)現(xiàn)微信掃碼支付的文章就介紹到這了,更多相關(guān)Java微信掃碼支付內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot 動態(tài)配置Profile環(huán)境的方式

    SpringBoot 動態(tài)配置Profile環(huán)境的方式

    這篇文章主要介紹了SpringBoot 動態(tài)配置Profile環(huán)境的方式,本文通過圖文實(shí)例相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-10-10
  • Spring MVC溫故而知新系列教程之請求映射RequestMapping注解

    Spring MVC溫故而知新系列教程之請求映射RequestMapping注解

    這篇文章主要介紹了Spring MVC溫故而知新系列教程之請求映射RequestMapping注解的相關(guān)知識,文中給大家介紹了RequestMapping注解提供的幾個屬性及注解說明,感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧
    2018-05-05
  • MyBatis傳入集合 list 數(shù)組 map參數(shù)的寫法

    MyBatis傳入集合 list 數(shù)組 map參數(shù)的寫法

    這篇文章主要介紹了MyBatis傳入集合 list 數(shù)組 map參數(shù)的寫法的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-06-06
  • SpringBoot實(shí)現(xiàn)PDF添加水印的示例

    SpringBoot實(shí)現(xiàn)PDF添加水印的示例

    本文主要介紹了SpringBoot實(shí)現(xiàn)PDF添加水印的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • Spring Security OAuth 自定義授權(quán)方式實(shí)現(xiàn)手機(jī)驗證碼

    Spring Security OAuth 自定義授權(quán)方式實(shí)現(xiàn)手機(jī)驗證碼

    這篇文章主要介紹了Spring Security OAuth 自定義授權(quán)方式實(shí)現(xiàn)手機(jī)驗證碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • Java求兩集合的交集、并集、差集實(shí)例

    Java求兩集合的交集、并集、差集實(shí)例

    這篇文章主要介紹了Java求兩集合的交集、并集、差集實(shí)例,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • 詳解Java分布式Session共享解決方案

    詳解Java分布式Session共享解決方案

    這篇文章主要介紹了詳解Java分布式Session共享解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • Spring Cloud Config與Bus整合實(shí)現(xiàn)微服務(wù)配置自動刷新功能

    Spring Cloud Config與Bus整合實(shí)現(xiàn)微服務(wù)配置自動刷新功能

    通過整合SpringCloud Config與Spring Cloud Bus,實(shí)現(xiàn)了微服務(wù)配置的自動刷新功能,這個機(jī)制允許一個微服務(wù)實(shí)例在配置更新時通過消息總線通知其他所有實(shí)例同步更新,從而保持配置的一致性并提升系統(tǒng)的運(yùn)維效率
    2024-10-10
  • Java實(shí)現(xiàn)將txt/word/pdf轉(zhuǎn)成圖片并在線預(yù)覽的功能

    Java實(shí)現(xiàn)將txt/word/pdf轉(zhuǎn)成圖片并在線預(yù)覽的功能

    本文將基于aspose-words(用于txt、word轉(zhuǎn)圖片),pdfbox(用于pdf轉(zhuǎn)圖片),封裝成一個工具類來實(shí)現(xiàn)txt、word、pdf等文件轉(zhuǎn)圖片的需求并實(shí)現(xiàn)在線預(yù)覽功能,需要的可以參考一下
    2023-05-05
  • 完美解決springboot中使用mybatis字段不能進(jìn)行自動映射的問題

    完美解決springboot中使用mybatis字段不能進(jìn)行自動映射的問題

    今天在springboot中使用mybatis的時候不能字段不能夠進(jìn)行自動映射,接下來給大家給帶來了完美解決springboot中使用mybatis字段不能進(jìn)行自動映射的問題,需要的朋友可以參考下
    2023-05-05

最新評論

天峨县| 盐源县| 临澧县| 木兰县| 大同市| 中牟县| 绵竹市| 江安县| 重庆市| 西安市| 焉耆| 陈巴尔虎旗| 余庆县| 泽普县| 两当县| 兴城市| 柳林县| 彰化县| 巨野县| 禹城市| 锡林浩特市| 边坝县| 株洲县| 连云港市| 滁州市| 大城县| 潞西市| 吉林市| 大名县| 连州市| 蓝山县| 梅河口市| 丹东市| 平南县| 永济市| 什邡市| 海伦市| 绥阳县| 衡水市| 新乡市| 达孜县|