java开发Demo~微信扫码支付,java开发示例-程序员宅基地

技术标签: java  运维  数据库  

开发所需工具类


img_e9aae379ed635a160cdfa112351457ff.png

开发所需jar

img_91daabb3505225de542aac9f3599ac80.png

具体的代码不贴了,说明下PayConfigUtil中的参数


img_e785935e024bfb9944c69db8ebe76d95.png

APP_ID和APP_SECRET在公众平台 

MCH_ID和API_KEY在商户平台,其中API_KEY是自己设置的,并不是自动生成的。

Controller

通过此方法,前往可以生成二维码的页面

//微信前往支付页面

    @RequestMapping(value = "towxPay")

    public ModelAndView towxPay(ModelMap map,HttpServletRequest request,String chapterId,String chapterName,String price) throws IOException{

        ModelAndView mav = new ModelAndView();

        mav.setViewName("jsp/pay/weixinpayma");

        HttpSession session = request.getSession();

        session.setAttribute("chapterId", chapterId);

        session.setAttribute("chapterName", chapterName);

        session.setAttribute("price", price);

        return mav;

    }

返回的页面如下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

                <%

    String path = request.getContextPath();

    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()

            + path + "/";

%>

Insert title here

   


<%=basePath%index/payImg style="min-height:null;min-width:null;" width=null height=null />


   

    /* ajax轮回,不停的访问Controller,直到wxPayType=1时,付款成功 */

        var num = 0;

        $(function(){

            panduanWXPay();

        });

        function panduanWXPay(){

            $.post("<%=basePath%>index/panduanPay",function(data){

                var wxPayType = data.wxPayType;

                if(wxPayType==1){

                /* 成功 */

                    window.location.href='<%=basePath%>index/gouMai';

                }else if(wxPayType==0 && num!=400){

                    num++;

                    panduanWXPay();

                }else{

                    alert("支付超时");

                }

            });

        } 


payImg方法

//微信支付,生成二维码

    @RequestMapping(value = "payImg")

    public  void payImg(HttpServletRequest request, HttpServletResponse response) throws IOException{

        HttpSession session = request.getSession();

        String chapterName=(String)session.getAttribute("chapterName");

        String price=(String)session.getAttribute("price");

        int defaultWidthAndHeight=200;

        String nonce_str = PayCommonUtil.getNonce_str();

        long time_stamp = System.currentTimeMillis() / 1000;

        String product_id = chapterName+"*"+price;//订单名字和价钱,拼到了一起,后面用到的时候再拆

        String key = PayConfigUtil.API_KEY; // key

        SortedMap packageParams = new TreeMap();

        packageParams.put("appid", PayConfigUtil.APP_ID);

        packageParams.put("mch_id", PayConfigUtil.MCH_ID);

        packageParams.put("time_stamp", String.valueOf(time_stamp));

        packageParams.put("nonce_str", nonce_str);

        packageParams.put("product_id", product_id);

//      packageParams.put("chapterId", chapterId);

//      packageParams.put("price", price);

        String sign = PayCommonUtil.createSign("UTF-8", packageParams,key);//MD5哈希

        packageParams.put("sign", sign);

        //生成参数

        String str = ToUrlParams(packageParams);

        String payurl = "weixin://wxpay/bizpayurl?" + str;

//      logger.info("payurl:"+payurl);

        //生成二维码

        Map  hints=new HashMap();

        // 指定纠错等级 

        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); 

        // 指定编码格式 

        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 

        hints.put(EncodeHintType.MARGIN, 1);

        try {

            BitMatrix bitMatrix = new MultiFormatWriter().encode(payurl,BarcodeFormat.QR_CODE, defaultWidthAndHeight, defaultWidthAndHeight, hints);

            OutputStream out = response.getOutputStream();

            MatrixToImageWriter.writeToStream(bitMatrix, "png", out);//输出二维码

            out.flush();

            out.close();

        } catch (WriterException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

public String ToUrlParams(SortedMap packageParams){

        //实际可以不排序

        StringBuffer sb = new StringBuffer(); 

        Set es = packageParams.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 (null != v && !"".equals(v)) { 

                sb.append(k + "=" + v + "&"); 

            } 

        }

        sb.deleteCharAt(sb.length()-1);//删掉最后一个&

        return sb.toString();

    }

扫码时触动此方法,会在手机端显示付款信息

要将此方法的路径配置到回调url里,微信公众平台–>微信支付–>开发配置 


img_7cb898cf7db0bad23d60a98ead78bbe2.png

//微信扫码的时候,触发此方法

    @RequestMapping(value = "Re_notify")

    public void Re_notify(HttpServletRequest request, HttpServletResponse response) throws IOException{

        HttpSession session = request.getSession();

        String chapterId=(String)session.getAttribute("chapterId");

        String chapterName=(String)session.getAttribute("chapterName");

        String price=(String)session.getAttribute("price");

        System.out.println(chapterId+":"+chapterName+":"+price);

        // 读取xml

                InputStream inputStream;

                StringBuffer sb = new StringBuffer();

                inputStream = request.getInputStream();

                String s;

                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

                while ((s = in.readLine()) != null) {

                    sb.append(s);

                }

                in.close();

                inputStream.close();

                SortedMap packageParams = PayCommonUtil.xmlConvertToMap(sb.toString());

//              logger.info(packageParams);

                // 账号信息

                String key = PayConfigUtil.API_KEY; // key

                String resXml="";//反馈给微信服务器

                // 验签

                if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {

                    //appid openid mch_id is_subscribe nonce_str product_id sign

                    //统一下单

                    String openid = (String)packageParams.get("openid");

                    String product_id = (String)packageParams.get("product_id");

                    //解析product_id,计算价格等

                    String thePricce = product_id.substring(product_id.lastIndexOf("*")+1);

                    String newProductId = product_id.substring(0, product_id.indexOf("*"));

                    String out_trade_no = String.valueOf(System.currentTimeMillis()); // 订单号 

                    String order_price = thePricce; // 价格"1"  注意:价格的单位是分 

                    String body = newProductId;  // 商品名称product_id  这里设置为product_id

                    String attach = "十倍课"; //附加数据

                    String nonce_str0 = PayCommonUtil.getNonce_str();

                    // 获取发起电脑 ip 

                    String spbill_create_ip = PayConfigUtil.CREATE_IP;   

                    String trade_type = "NATIVE";

                    SortedMap unifiedParams = new TreeMap(); 

                    unifiedParams.put("appid", PayConfigUtil.APP_ID); // 必须

                    unifiedParams.put("mch_id", PayConfigUtil.MCH_ID); // 必须

                    unifiedParams.put("out_trade_no", out_trade_no); // 必须

                    unifiedParams.put("product_id", product_id);

                    unifiedParams.put("body", body); // 必须

                    unifiedParams.put("attach", attach);

                    unifiedParams.put("total_fee", order_price);  // 必须

                    unifiedParams.put("nonce_str", nonce_str0);  // 必须

                    unifiedParams.put("spbill_create_ip", spbill_create_ip); // 必须

                    unifiedParams.put("trade_type", trade_type); // 必须 

                    unifiedParams.put("openid", openid); 

                    unifiedParams.put("notify_url", PayConfigUtil.NOTIFY_URL);//异步通知url

                    String sign0 = PayCommonUtil.createSign("UTF-8", unifiedParams,key); 

                    unifiedParams.put("sign", sign0); //签名

                    String requestXML = PayCommonUtil.getRequestXml(unifiedParams); 

//                  logger.info(requestXML);

                    //统一下单接口

                    String rXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML); 

                    //统一下单响应

                    SortedMap reParams = PayCommonUtil.xmlConvertToMap(rXml);

//                  logger.info(reParams);

                    //验签

                    if (PayCommonUtil.isTenpaySign("UTF-8", reParams, key)) {

                        // 统一下单返回的参数

                        String prepay_id = (String)reParams.get("prepay_id");//交易会话标识  2小时内有效

                        String nonce_str1 = PayCommonUtil.getNonce_str();

                        SortedMap resParams = new TreeMap(); 

                        resParams.put("return_code", "SUCCESS"); // 必须

                        resParams.put("return_msg", "OK");

                        resParams.put("appid", PayConfigUtil.APP_ID); // 必须

                        resParams.put("mch_id", PayConfigUtil.MCH_ID);

                        resParams.put("nonce_str", nonce_str1); // 必须

                        resParams.put("prepay_id", prepay_id); // 必须

                        resParams.put("result_code", "SUCCESS"); // 必须

                        resParams.put("err_code_des", "OK");

                        String sign1 = PayCommonUtil.createSign("UTF-8", resParams,key); 

                        resParams.put("sign", sign1); //签名

                        resXml = PayCommonUtil.getRequestXml(resParams);

//                      logger.info(resXml);

                    }else{

//                      logger.info("签名验证错误");

                        resXml = "" + "" 

                                + "" + " ";

                    }

                }else{

//                  logger.info("签名验证错误");

                    resXml = "" + "" 

                            + "" + " ";

                }

                //------------------------------ 

                //处理业务完毕 

                //------------------------------ 

                BufferedOutputStream out = new BufferedOutputStream( 

                        response.getOutputStream()); 

                out.write(resXml.getBytes()); 

                out.flush(); 

                out.close(); 

    }

微信支付成功时访问的方法

密码错误等未支付成功的情况下,不会访问。 

此路径是PayConfigUtil中配置的

int wxPayType = 0;

    //微信扫码支付回调

    @RequestMapping(value = "Notify1")

    public void Notify1(HttpServletRequest request, HttpServletResponse response) throws IOException{

        InputStream inputStream;

        StringBuffer sb = new StringBuffer();

        inputStream = request.getInputStream();

        String s;

        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

        while ((s = in.readLine()) != null) {

            sb.append(s);

        }

        in.close();

        inputStream.close();

        SortedMap packageParams = PayCommonUtil.xmlConvertToMap(sb.toString());

//      logger.info(packageParams);

        // 账号信息

        String key = PayConfigUtil.API_KEY; // key

        String resXml = ""; // 反馈给微信服务器

        // 判断签名是否正确

        if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {

            // ------------------------------

            // 处理业务开始

            // ------------------------------

            if ("SUCCESS".equals((String) packageParams.get("result_code"))) {

                // 这里是支付成功

                // 执行自己的业务逻辑

                String mch_id = (String) packageParams.get("mch_id");

                String openid = (String) packageParams.get("openid");

                String is_subscribe = (String) packageParams.get("is_subscribe");

                String out_trade_no = (String) packageParams.get("out_trade_no");

                String total_fee = (String) packageParams.get("total_fee");

将用于标记是否成功的全局变量wxPayType设置为1,ajax轮回时,可以获取到其变化,从而进行页面跳转

                wxPayType=1;

                System.out.println("33333333333333333333333333333:"+wxPayType);

//          "支付成功"

// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.

                resXml = "" + ""

                        + "" + " ";

            } else {

//              logger.info("支付失败,错误信息:" + packageParams.get("err_code"));

                resXml = "" + ""

                        + "" + " ";

            }

        } else {

//          logger.info("签名验证错误");

            resXml = "" + "" 

                    + "" + " ";

        }

        // ------------------------------

        // 处理业务完毕

        // ------------------------------

        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

        out.write(resXml.getBytes());

        out.flush();

        out.close();

    }

ajax不停轮回,判断是否登录成功的方法

@RequestMapping(value = "panduanPay")

        @ResponseBody

        public Map panduanPay(HttpServletRequest request) throws IOException{

            Map map = new HashMap();

            try {

                Thread.sleep(500);

            } catch (InterruptedException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            //给页面返回wxPayType值,成功是返回的是1;还未支付成功,返回的是初始值0

            map.put("wxPayType",wxPayType);

            return map;

        }

成功后页面跳转的方法

//购买成功,存入购买表中

    @RequestMapping(value="gouMai")

    @ResponseBody

    public ModelAndView gouMai(HttpServletRequest req,String a,String urlName,String couName,ModelMap map){

        ModelAndView mav = new ModelAndView();

        Map mapp1 = new HashMap();

//      SysUserTab login_user = sysuserService.getSysUserById(userId);

        HttpSession session = req.getSession();

        SysUserTab login_user1 = (SysUserTab) session.getAttribute("login_user");

        String userId = login_user1.getUserId();

//      session.setAttribute("login_user", login_user);

        String chapterId = (String) session.getAttribute("chapterId");

        mapp1.put("userId", userId);

        mapp1.put("chapterId", chapterId);

        int num = sysBuyService.getBuyCount(mapp1);

        if(num==0){

            mapp1.put("buyId", UUID.randomUUID().toString().replace("-", ""));

            sysBuyService.insertBuy(mapp1);

        }

Java高架构师、分布式架构、高可扩展、高性能、高并发、性能优化、Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式项目实战学习架构师视频免费学习加群:835638062 点击链接加入群聊【Java高级架构】:https://jq.qq.com/?_wv=1027&k=5S3kL3v

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_34161029/article/details/89590546

智能推荐

while循环&CPU占用率高问题深入分析与解决方案_main函数使用while(1)循环cpu占用99-程序员宅基地

文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。​​​​​​while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99

【无标题】jetbrains idea shift f6不生效_idea shift +f6快捷键不生效-程序员宅基地

文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效

node.js学习笔记之Node中的核心模块_node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是-程序员宅基地

文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是

数学建模【SPSS 下载-安装、方差分析与回归分析的SPSS实现(软件概述、方差分析、回归分析)】_化工数学模型数据回归软件-程序员宅基地

文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件

利用hutool实现邮件发送功能_hutool发送邮件-程序员宅基地

文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件

docker安装elasticsearch,elasticsearch-head,kibana,ik分词器_docker安装kibana连接elasticsearch并且elasticsearch有密码-程序员宅基地

文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码

随便推点

Python 攻克移动开发失败!_beeware-程序员宅基地

文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware

Swift4.0_Timer 的基本使用_swift timer 暂停-程序员宅基地

文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停

元素三大等待-程序员宅基地

文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待

Java软件工程师职位分析_java岗位分析-程序员宅基地

文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析

Java:Unreachable code的解决方法_java unreachable code-程序员宅基地

文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code

标签data-*自定义属性值和根据data属性值查找对应标签_如何根据data-*属性获取对应的标签对象-程序员宅基地

文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象

推荐文章

热门文章

相关标签