微信小程序实现支付前端后端代码

微信小程序实现支付前端后端代码

公司根据业务需求,要做支付功能,网上查了些资料花了两天时间实现的支付流程,微信支付是必须开通商户号,然后绑定要实现的支付的小程序。

1.后端代码

需要创建一些配置类

package com.asa.utils.wxpay;

/**
 * 微信支付配置类
 */
public class WxPayConfig {
    //小程序appid
    public static final String appid = "***********;
    //微信支付的商户id
    public static final String mch_id = "**********;//商户号
    //微信支付的商户密钥
    public static final String key = "fsdgegwe24EDGFDGgegfetrfrwefger2";//商户的key
    //支付成功后的服务器回调url,回调函数的地址(就是自己写在Controller里的回调函数)但是不许外网能访问(可以进行内网穿透)
    public static final String notify_url = "https://*********/asa/wmp/wxNotify";
    //签名方式
    public static final String SIGNTYPE = "MD5";
    //交易类型
    public static final String TRADETYPE = "JSAPI";
    //微信统一下单接口地址
    public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    //AppSecret(小程序密钥)
    public static final String app_secret ="fb19e7c6f590ec17cfcd2ef8e2315acc";
}

package com.asa.utils.wxpay;


import java.util.Random;

/**
 *
 */
public class StringUtils extends org.apache.commons.lang.StringUtils {
    /**
     * StringUtils工具类方法
     * 获取一定长度的随机字符串,范围0-9,a-z
     * @param length:指定字符串长度
     * @return 一定长度的随机字符串
     */
    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


}

package com.asa.utils.wxpay;

public class RandomUtil {

    public String getRandomCode(int codeLen) {
        java.util.Random randomCode = new java.util.Random();
        String strCode = "";
        while (codeLen > 0) {
            int charCode = randomCode.nextInt(9);
            strCode += charCode;
            codeLen--;
        }
        return strCode;
    }
}

package com.asa.utils.wxpay;

import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;


public class PayUtil {
    /**
     * 签名字符串
     * @param "text需要签名的字符串"
     * @param key 密钥
     * @param "input_charset编码格式"
     * @return 签名结果
     */
    public static String sign(String text, String key, String input_charset) {
        text = text + "&key=" + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }
    /**
     * 签名字符串
     *  @param "text需要签名的字符串"
     * @param sign 签名结果
     * @param "key密钥"
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static boolean verify(String text, String sign, String key, String input_charset) {
        text = text + key;
        String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
        if (mysign.equals(sign)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * @param content
     * @param charset
     * @return
     * @throws
     * @throws UnsupportedEncodingException
     */
    public static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    private static boolean isValidChar(char ch) {
        if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
            return true;
        if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
            return true;// 简体中文汉字编码
        return false;
    }
    /**
     * 除去数组中的空值和签名参数
     * @param "sArray" 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }
    /**
     * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param "params" 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    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);
            if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }
    /**
     *
     * @param "requestUrl请求地址"
     * @param "requestMethod请求方法"
     * @param "outputStr参数"
     */
    public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
        // 创建SSLContext
        StringBuffer buffer = null;
        try{
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //往服务器端写内容
            if(null !=outputStr){
                OutputStream os=conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }
    public static String urlEncodeUTF8(String source){
        String result=source;
        try {
            result=java.net.URLEncoder.encode(source, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) throws Exception {
        if(null == strxml || "".equals(strxml)) {
            return null;
        }
        /*=============  !!!!注意,修复了微信官方反馈的漏洞,更新于2018-10-16  ===========*/
        try {
            Map<String, String> data = new HashMap<String, String>();
            // TODO 在这里更换
            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);

            InputStream stream = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().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) {
            throw ex;
        }
    }
//    /**
//     * 获取子结点的xml
//     * @param children
//     * @return String
//     */
//    public static String getChildrenText(List children) {
//        StringBuffer sb = new StringBuffer();
//        if(!children.isEmpty()) {
//            Iterator it = children.iterator();
//            while(it.hasNext()) {
//                Element e = (Element) it.next();
//                String name = e.getName();
//                String value = e.getTextNormalize();
//                List list = e.getChildren();
//                sb.append("<" + name + ">");
//                if(!list.isEmpty()) {
//                    sb.append(getChildrenText(list));
//                }
//                sb.append(value);
//                sb.append("</" + name + ">");
//            }
//        }
//
//        return sb.toString();
//    }
    public static InputStream String2Inputstream(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }
}

package com.asa.utils.wxpay;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {
    /**
     * IpUtils工具类方法
     * 获取真实的ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值,第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
}

package com.asa.utils.wxpay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequest {

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和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();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 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;
    }
}

接下来是有两个方法,一个是微信支付统一下单接口,另一个是下单支付成功后回调接口,
注意一下,回调接口不能在内网,必须是外网,测试的时间要么模拟参数用postman测试,或者使用内网穿透

package com.asa.controller.wmp;

import com.alibaba.fastjson.JSONObject;
import com.asa.dao.common.ICashFlowDao;
import com.asa.dao.merchant.IMerchantDao;
import com.asa.entity.pojo.common.CashFlow;
import com.asa.entity.pojo.merchant.Merchant;
import com.asa.service.common.ICashFlowService;
import com.asa.service.merchant.IMerchantService;
import com.asa.utils.pdf.MerchantContractPDF;
import com.asa.utils.wxpay.*;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信统一支付接口
 *
 */
@Controller
@RequestMapping("/wmp/wx")
public class PayController {

    @Autowired
    private IMerchantDao merchantDao;
    @Autowired
    private ICashFlowService cashFlowService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private ICashFlowDao cashFlowDao;



    /**
     * 发起微信支付
     * @param money
     * @param request
     * @return
     */
    @RequestMapping(value = "/wxPay")
    @ResponseBody
    public Map<String,Object> wxPay(String money,String code,String wareName,int type,String merchantAccount,HttpServletRequest request){
      try {
         // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
          //请求参数
          String grant_type="authorization_code";
          String params = "appid=" + WxPayConfig.appid + "&secret=" + WxPayConfig.app_secret + "&js_code=" + code + "&grant_type=" + grant_type;
          //发送请求
          String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
          JSONObject json=JSONObject.parseObject(sr);
          String openid= (String) json.get("openid");
          //解析相应内容(转换成json对象)
          System.out.println(sr);
          //微信里面的价格是以分为单位
          //生成的随机字符串
          String nonce_str = StringUtils.getRandomStringByLength(32);
          //商户订单号
          String out_trade_no= new RandomUtil().getRandomCode(10);
          //商品名称
          String body = wareName;
          //获取客户端的ip地址
          String spbill_create_ip = IpUtils.getIpAddr(request);
          //组装参数,用户生成统一下单接口的签名
          Map<String, String> packageParams = new HashMap<String, String>();
          packageParams.put("appid", WxPayConfig.appid);
          packageParams.put("mch_id", WxPayConfig.mch_id);
          packageParams.put("nonce_str", nonce_str);
          packageParams.put("body", body);
          packageParams.put("out_trade_no", out_trade_no);//商户订单号
          packageParams.put("total_fee", money);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
          packageParams.put("spbill_create_ip", spbill_create_ip);
          packageParams.put("notify_url", WxPayConfig.notify_url);//支付成功后的回调地址
          packageParams.put("trade_type", WxPayConfig.TRADETYPE);//支付方式
          packageParams.put("openid", openid);
          // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
          String prestr = PayUtil.createLinkString(packageParams);
          //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
          String mysign = PayUtil.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();
          //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
          String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>"
                  + "<body><![CDATA[" + body + "]]></body>"
                  + "<mch_id>" + WxPayConfig.mch_id + "</mch_id>"
                  + "<nonce_str>" + nonce_str + "</nonce_str>"
                  + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"
                  + "<openid>" + openid + "</openid>"
                  + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                  + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                  + "<total_fee>" + money + "</total_fee>"
                  + "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"
                  + "<sign>" + mysign + "</sign>"
                  + "</xml>";
          System.out.println("调试模式_统一下单接口 请求XML数据:" + xml);
          //调用统一下单接口,并接受返回的结果
          String result = PayUtil.httpRequest(WxPayConfig.pay_url, "POST", xml);
          //业务逻辑
          /**此处添加自己的业务逻辑代码end**/
          


          System.out.println("调试模式_统一下单接口 返回XML数据:" + result);
          // 将解析结果存储在HashMap中
          Map map = PayUtil.doXMLParse(result);
          System.out.println(map);
          String return_code = (String) map.get("return_code");//返回状态码
          Map<String, Object> response = new HashMap<String, Object>();//返回给小程序端需要的参数
          if(return_code.equals("SUCCESS")){
              String prepay_id = String.valueOf(map.get("prepay_id"));//返回的预付单信息
              response.put("nonceStr", nonce_str);
              response.put("package", "prepay_id=" + prepay_id);
              Long timeStamp = System.currentTimeMillis() / 1000;
              response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误
              //拼接签名需要的参数
              String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;
              //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
              String paySign = PayUtil.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();
              response.put("paySign", paySign);
          }
          response.put("appid", WxPayConfig.appid);
          return response;

      }catch (Exception e){
          e.printStackTrace();
      }
        return null;
    }

    /**
     * 微信支付成功的回掉函数
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxNotify")
    @ResponseBody
    public String wxNotify(HttpServletRequest request, HttpServletResponse response)throws Exception{
        System.out.println("进入了回调》》》》》》》》》》》》》》》》》》》》》》》》");
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine()) != null){
            sb.append(line);
        }
        br.close();
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的报文:" + notityXml);
        Map map = PayUtil.doXMLParse(notityXml);
        String returnCode = (String) map.get("return_code");
        if("SUCCESS".equals(returnCode)){
            //验证签名是否正确
            Map<String, String> validParams = PayUtil.paraFilter(map);  //回调验签时需要去除sign和空值参数
            String validStr = PayUtil.createLinkString(validParams);//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
            String sign = PayUtil.sign(validStr, WxPayConfig.key, "utf-8").toUpperCase();//拼装生成服务器端验证的签名

            //根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等
            if(sign.equals(map.get("sign"))){
                /**此处添加自己的业务逻辑代码start**/
                System.out.println("开始=================");
                String out_trade_no=(String) map.get("out_trade_no");
                String transaction_id=(String) map.get("transaction_id");
                String total_fee=(String) map.get("total_fee");

                System.out.println("结束=============================");
                //通知微信服务器已经支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            }
        }else{
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[出现错误]]></return_msg>" + "</xml> ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");
        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
        Map maps = PayUtil.doXMLParse(resXml);
        String returnCodes = (String) maps.get("return_code");
        return returnCodes;
    }


}

统一下单接口的业务代码我已经删了,具体实现逻辑是先创建订单,给订单设定一个未支付的状态,如果用户支付成功后,则调用回调接口,改变订单状态,设为支付成功

前端代码

js

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    payCount: [
      {count: 100, check: false}, 
      {count: 300, check: false}, 
      {count: 500, check: false}, 
      {count: 1000, check: false}
    ],
    count: '', //金额
    showInout: false,
    zdyCount: '',
    availableBalance:0,
    code:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that=this
    this.setData({
      availableBalance:options.availableBalance
    })
  
  },
  bindChoose(e){
    // count 就是金额
    const { index, count } = e.currentTarget.dataset;
    const payCount = this.data.payCount;
    payCount.forEach((el, idx) => {
      if(index == idx){
        el.check = true;  
      }else{
        el.check = false;
      }
    })
    this.setData({
      count: count,
      payCount: payCount,
      showInout: false
      
    })
    console.log(this.data.count)
  },
  zdyCount(){
    const payCount = this.data.payCount;
    payCount.forEach((el, idx) => {
      el.check = false
    })
    this.setData({
      payCount: payCount,
      count: 0,
      showInout: true
    })
  },
  inputedit(e){
    let dataset = e.currentTarget.dataset;
    let value = e.detail.value;
    this.data[dataset.zdyCount] = value;
    this.setData({
      zdyCount: this.data[dataset.zdyCount]
    })
  },
  charge(){
    let that=this
    console.log()
    console.log(this.data.zdyCount)
    if(this.data.count == 0 && this.data.zdyCount == 0){
      wx.showToast({
        title: '请选择充值金额',
        icon: 'none',
        duration: 1000,
        mask:true
     })
     return
    }
    if(this.data.showInout){
      const zdyCount = this.data.zdyCount;
      this.setData({
        count: zdyCount
      })
    }
  wx.login({
    success:function(res){
      that.data.code=res.code //获得登录凭证code
      wx.getStorage({
        key: 'userInfo',
        success: function(res){
          wx.request({
            url: app.globalData.api + '/asa/wmp/wx/wxPay',
            header: {
             //设置参数内容类型为x-www-form-urlencoded
             'content-type': 'application/x-www-form-urlencoded',
             'Accept': 'application/json'
           },
           data:{
             money:that.data.count*100, //微信支付金额,微信是以分为单位
             code:that.data.code, //小程序登录凭证
             merchantAccount:res.data.user.merchantAccount, //业务参数
             wareName: "小程序商家充值",//商品名称
             type: parseInt(14) //业务参数
           },
           method: 'POST',
           success: function(res){
             var data=res.data
                wx.requestPayment({
                  timeStamp: data.timeStamp,
                  nonceStr: data.nonceStr,
                  package: data.package,
                  signType: 'MD5',
                  paySign: data.paySign,
                  success: function(res){
                   wx.showToast({
                     title: '支付成功',
                     icon: 'success',
                     duration: 2000
                   })
                    //返回指定页面
                    setTimeout(item=>{
                    wx.reLaunch({
                      url: '../income/income',
                    })
                     },2000)
                  },
                  fail: function (res) {
                    console.log(res)
                  },
                  complete:function(e){

                  }
                })
               
             
    
             
           },
           fail: function (res) {
             console.log(res)
           },
    
          })
        }
      
      
      })
    }
  })
        

         



  }
})

wxml

<!--index.wxml-->
<view class="pay">
  <view class="title">
    您当前的余额为:
    <text class="count" bindtap="money">{{availableBalance/100}}</text></view>
  <view class="detail">
    <view wx:for="{{payCount}}" wx:for-item="elem" wx:for-index="index" wx:key="index" 
    bindtap="bindChoose" data-index="{{index}}" data-count="{{elem.count}}"  class="part {{ elem.check && 'gbBlue' }}">{{ elem.count }}</view> 
  </view>
  <view class="zdy" bindtap="zdyCount">*自定义充值金额</view>
  <view class="zdyInput" wx:if="{{showInout}}">
    <input focus='true' value="{{zdyCount}}" data-zdyCount="zdyCount" bindinput="inputedit"></input>
  </view>
  <view class="btn" bindtap="charge">充值</view>
</view>

wxss

/**index.wxss**/
.pay{
  padding: 20rpx 50rpx;
}

.zdy{
  color: #B5B5B5;
  font-size: 30rpx; 
}

.pay .title{
  color: #B5B5B5;
  font-size: 30rpx;
}

.pay .title .count{
  color: #4C8FD6;
  font-size: 30rpx;
}

.detail{
  display: flex;
  flex-wrap: wrap;
  margin-top: 30rpx;
}
.detail .part{
  height: 150rpx;
  width: 45%;
  background: #EEEFF1;
  border-radius: 5%;
  margin-bottom: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.detail .part:nth-child(2n-1){
  margin-right: 10%;
}

.btn{
  position: absolute;
  bottom: 200rpx;
  left: 50rpx;
  right: 50rpx;
  text-align: center;
  height: 100rpx;
  line-height: 100rpx;
  background: #4C8FD6;
  border-radius: 50rpx;
}
.gbBlue{
  background: #4C8FD6 !important;
}

.zdyInput{
  text-align: center;
  background: #EEEFF1;
  margin-top: 40rpx;
}

.zdyInput input{
  width: 100%;
  height: 100rpx;
}

上面就是微信支付的整个流程,亲测有效,有啥不懂得欢迎交流

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值