微信小程序 - 实现微信支付

微信小程序在微信的生态内,接入微信付一定是小程序开发中必须实现的一个功能,这里分享下小程序实现微信支付功能开发流程和思路。

参考文档:[微信支付开发文档]

1、准备工作:开通微信支付和微信商户号

没有开通微信支付的小程序,将不能实现使用微信支付。当然也没啥,可以按照步骤来申请,但是申请成功后发给你的邮件一定要保存,此邮件包含开发时需要使用的支付账户信息 。

b49f8bc9b210470d95067bb6a8659ec1e99.jpg

2、弄清楚开发流程

业务流程时序图如下:

8d50ab8f32f5dee80eba58e53ac73995c57.jpg

3.用户请求下单支付

前台代码:小程序调起支付

  formSubmit: function (e) {
    var that = this
    wx.request({
      url: url + "pay/buyGoods",
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: { 'Content-Type': 'application/json' },
      data: {
        token: app.globalData.token, // 用户标识
        goodsId: that.data.goodsId, //商品id
        phone: e.detail.value.phone, //付款用户电话
      },
      success: function (res) {
        if (res.data.data != null) {
          //调起微信支付
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp,
            nonceStr: res.data.data.nonceStr,
            package: res.data.data.packages,
            signType: 'MD5',
            paySign: res.data.data.paySign,
            success: function (ress) {
              wx.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 3000,
                success: function () {
                },
                fail: function (res) {
                  wx.showToast({
                    title: '支付失败',
                    icon: 'success',
                    duration: 3000,
                    success: function () {
                    },
                  })
                }
              })
            }
          })
        }
      }
    })
  }

4、后台生成订单,之后调用微信统一下单API,数据签名后返回前台支付参数


@Controller
@RequestMapping("/pay")
public class TransferController {

	private static final Logger LOG = Logger.getLogger(TransferController.class);

	// 调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易
	private static final String USER_PAY = "https://api.mch.weixin.qq.com/pay/unifiedorder";

	// 小程序ID
	private static final String APP_ID = ConfigUtil.getProperty("wx.appid");

	// 商户号
	private static final String MCH_ID = ConfigUtil.getProperty("wx.mchid");

	// API密钥
	private static final String API_SECRET = ConfigUtil.getProperty("wx.api.secret");

	@Autowired
	private TransferService transferService;

	@Autowired
	private WedoWxpayService wedoWxpayService;

	@RequestMapping(value = "/buyGoods")
	public @ResponseBody Map<String, String> buyGoods(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=UTF-8");
	
		String sum= req.getParameter("phone"); // 电话
		String goodsId= req.getParameter("goodsId");// 商品id

		// 发起预付款
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> restmap = null;
		String payId = "";
		try {
			Map<String, String> parm = new HashMap<String, String>();
			parm.put("appid", APP_ID); // 公众账号appid
			parm.put("mch_id", MCH_ID); // 商户号
			parm.put("nonce_str", PayUtil.getNonceStr()); // 随机字符串
			parm.put("out_trade_no", PayUtil.getTransferNo()); // 商户订单号
                        parm.put("total_fee", sum); // 付款金额sum
			parm.put("body", "xxx支付"); // 付款描述信息
			parm.put("spbill_create_ip", PayUtil.getLocalIp(req)); // Ip地址
			parm.put("trade_type", "JSAPI"); // 交易类型
			// 支付成功后的一个通知地址(接收微信支付异步通知回调地址)
			parm.put("notify_url", "http://xxx/xxx/transfer/Notify");
			parm.put("sign", PayUtil.getSign(parm, API_SECRET)); // 签名

			// 预支付请求
			String restxml = HttpUtils.posts(USER_PAY, XmlUtil.xmlFormat(parm, false));
			// 预支付返回解析
			restmap = XmlUtil.xmlParse(restxml);
			String prepay_id = "prepay_id=" + restmap.get("prepay_id").toString();

			// 返回给小程序前端的信息
			Map<String, String> result = new HashMap<String, String>();
			Map<String, String> resultMap = new HashMap<String, String>();
			result.put("appId", APP_ID); // 公众账号appid
			result.put("nonceStr", PayUtil.getNonceStr()); // 随机字符串
			result.put("package", prepay_id);
			result.put("timeStamp", new Date().getTime() / 1000 + "");
			result.put("signType", "MD5");

			resultMap.put("nonce_str", result.get("nonceStr"));
			resultMap.put("package", prepay_id);
			resultMap.put("timeStamp", result.get("timeStamp"));
			resultMap.put("signType", "MD5");
			resultMap.put("paySign", PayUtil.getSign(result, API_SECRET)); // 再次签名
			map = resultMap;

			payId = transferService.insert(parm.get("total_fee"),openid.replaceAll("\"", ""), parm.get("out_trade_no"),parm.get("body"), parm.get("spbill_create_ip"), prepay_id, result.get("timeStamp"), sum,goodsId);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		map.put("payId", payId);
		return map;
	}

	/**
	 * 支付结果通知
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/Notify")
	public @ResponseBody String Notify(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// 1.获取微信通知的参数
		String inputLine;
		String notityXml = "";
		try {
			while ((inputLine = req.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			req.getReader().close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		Map<String, String> resultMap = XmlUtil.xmlParse(notityXml);
		String resultCode = resultMap.get("result_code");
		System.out.println(resultMap);
		if (resultCode == "SUCCESS" || "SUCCESS".equals(resultCode)) {
			System.out.println(resultCode);
			// 2.更新订单的相关状态
			String outtradeno = resultMap.get("out_trade_no");
			transferService.updateByOutNo(outtradeno);
		} else {
			return null;
		}
		// 3.返回一个xml格式的结果给微信服务器
		Map<String, String> parm = new HashMap<String, String>();
		parm.put("return_code", "SUCCESS");
		parm.put("return_msg", "OK");
		return XmlUtil.xmlFormat(parm, false);
	}

}

代码很 low 但是这样简单几步,小程序的微信支付功能就简单实现了,文章仅仅提供了一个思路,具体实现根据自己项目而定。

 

水平有限,若有问题请留言交流!

互相学习,共同进步 :) 转载请注明出处谢谢!

转载于:https://my.oschina.net/hp2017/blog/1848407

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序是一种基于微信平台的应用的开发模式,可以快速的开发出符合用户需求的小程序。在小程序的开发中,组件是一个非常重要的概念,通过组件可以实现复用性和模块化编程思想。 组件应用是小程序开发的基础。通过组件可以将某一模块化并封装起来,使得组件可以在不同的页面间得到复用,大大提升了开发效率并减少了代码冗余。微信小程序提供了丰富的自带组件,包括文本、图片、按钮、输入框等等,开发者也可以自己开发组件来满足自己的需求。实际开发中,通过组件可以快速搭建页面框架和业务逻辑。 Demo是一个演示小程序的示例程序。在小程序的实际开发过程中,一个好的Demo非常重要。通过Demo,开发人员可以更深入的了解小程序的开发流程、组件的应用和实际的业务开发等等。在Demo中,通常会包括小程序的一些基础操作,如页面跳转、数据绑定、组件的使用等。而在实际开发中,Demo还会包括一些复杂的业务场景,如支付、登录、数据列表展示等等。Demo不仅为开发者提供了学习和实践的机会,也方便了使用者了解该小程序的功能和特点。 总之,微信小程序组件的应用和Demo的开发都是小程序开发过程中非常重要的两个部分。良好的组件应用和精心设计的Demo,可以在极短的时间内实现小程序开发。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值