JSAPI微信公众号apiV3文档支付


一.所需参数及maven依赖

官方文档
1.公众号id appid
2.商户号 mchid
3.APIv3秘钥 secret
4.商户api私钥 apiclient_key.pem
5.证书序列号

maven依赖

<!-- 微信支付V3版sdk -->
<dependency>
	<groupId>com.github.wechatpay-apiv3</groupId>
	<artifactId>wechatpay-apache-httpclient</artifactId>
	<version>0.2.1</version>
</dependency>

二.前端vue部分

// 确认支付
onSubmit() {
   
   
  // 手机端校验
  if (!navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
   
   
    this.$dialog.alert({
   
    message: '请在手机端微信关注公众号"跃迁赋能中心"进行购买' })
    return
  }

  // TODO 购买商品参数拼接、非空校验

  let that = this
  this.$api.request({
   
   
    url: '/wxpay/pay',
    method: 'post',
    params: params
  }).then(response => {
   
   
    // 拉起微信支付参数赋值
    that.payMap = response.data
    
    if (typeof WeixinJSBridge === 'undefined') {
   
   
      if (document.addEventListener) {
   
   
        document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false)
      } else if (document.attachEvent) {
   
   
        document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
        document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
      }
    } else {
   
   
      this.onBridgeReady()
    }
  })
},
// 拉起微信支付
onBridgeReady() {
   
   
  let payMap = this.payMap
  let that = this
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest', {
   
   
      'appId': payMap.appId, // 公众号名称,由商户传入
      'timeStamp': payMap.timeStamp, // 时间戳,自1970年以来的秒数
      'nonceStr': payMap.nonceStr, // 随机串
      'package': payMap.package,
      'signType': payMap.signType, // 微信签名方式:
      'paySign': payMap.paySign // 微信签名
    },
    function(res) {
   
   
      if (res.err_msg == 'get_brand_wcpay_request:ok') {
   
   
        // 付款成功处理
        that.$router.replace({
   
    path: '/' })
      }
    })
},

三.后端java部分

3.1 获取前端拉起微信支付参数
Controller

@ApiOperation("微信公众号支付")
@PostMapping("/pay")
public AjaxResult pay(HttpServletRequest request, @RequestParam(required = false) String miniIdStr,
    @RequestParam Double payAmount, @RequestParam String couponIdStr,
    @RequestParam(required = false) Long courseId) {
   
   
    Long personId = tokenService.getPersonId(request);
    // TODO 购买课程参数校验

    try {
   
   
        JSONObject result = officeOrderService.wxPay(personId, miniIdStr, payAmount, couponIdStr, courseId);
        Integer status = result.getInteger("status");
        if (status != null && status == 0) {
   
   
        	// 支付失败不反回前端拉起微信支付参数
            return AjaxResult.error("支付失败,请稍后再试");
        }
        return AjaxResult.success(result);
    } catch (Exception e) {
   
   
        log.error("微信支付下单接口失败,personId:{},miniIdStr:{},payAmount:{},couponIdStr:{},courseId:{}", personId,
            miniIdStr, payAmount, couponIdStr, courseId, e);
        return AjaxResult.error("支付失败,请稍后再试");
    }
}

Service

@Override
public JSONObject wxPay(Long personId, String miniIdStr, Double payAmount, String couponIdStr, Long courseId) {
   
   
    // 根据personId获取公众号openId
    String openId = wxLoginMapper.selectOpenIdByPersonId(personId);

    // 生成商品订单号
    String orderNumber = UUID.
### 实现Java对接微信公众号JSAPI支付(V2版本) #### Maven依赖 为了实现与微信公众号JSAPI支付接口对接,首先需要引入必要的Maven依赖: ```xml <dependency> <groupId>com.github.wechatpay-apiv3</groupId> <artifactId>wechatpay-java</artifactId> <version>0.2.7</version> </dependency> ``` 此依赖提供了处理微信支付所需的工具和支持[^2]。 #### 构造统一下单请求参数 在进行支付前,服务器需向微信发起统一订单创建请求。以下是构建该请求所需的主要字段及其说明: | 参数名 | 类型 | 描述 | | --- | --- | --- | | appid | String | 应用ID | | mch_id | String | 商户号 | | nonce_str | String | 随机字符串 | | sign_type | String | 签名类型,默认为MD5 | | body | String | 商品描述 | | out_trade_no | String | 商家订单号 | | total_fee | Integer | 订单总金额(分) | | spbill_create_ip | String | 客户端IP地址 | | notify_url | String | 接收异步通知URL | 这些信息会被封装成`UnifiedOrderRequest`对象并提交给微信支付平台以获取预支付交易会话标识(prepay_id)[^1]。 #### 获取prepay_id后的前端调起支付配置 当成功获得`prepay_id`之后,服务端应返回如下JSON结构供前端页面使用JavaScript API完成实际付款流程: ```json { "appId": "", "timeStamp": "", "nonceStr": "", "package": "prepay_id=", "signType":"", "paySign":"" } ``` 其中各个属性的具体含义已在上述表格中有所提及;而`paySign`则是基于以上五个键值对按照特定规则计算得出的签名结果。 #### Java代码示例 下面给出一段简单的Spring Boot风格的服务方法用于处理整个过程中的核心逻辑部分——即生成下单请求以及解析响应数据提取出`prepay_id`: ```java import com.github.wxpay.sdk.WXPayUtil; // ... other imports ... @Service public class WeChatPaymentService { private static final Logger logger = LoggerFactory.getLogger(WeChatPaymentService.class); @Value("${wechat.app.id}") private String appId; // Other properties like merchant id, key... public Map<String, Object> createPrepay(String orderId, int amountInFen) throws Exception { SortedMap<String, String> params = new TreeMap<>(); // Fill required parameters... params.put("appid", this.appId); params.put("mch_id", this.merchantId); params.put("body", "Test Product"); params.put("out_trade_no", orderId); params.put("total_fee", String.valueOf(amountInFen)); params.put("spbill_create_ip", getLocalIp()); params.put("notify_url", notificationUrl); params.put("trade_type", "JSAPI"); // Add more fields as needed according to your business requirements String xmlString = WXPayUtil.generateSignedXml(params, this.key); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder"); post.setEntity(new StringEntity(xmlString)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(responseBody)); org.w3c.dom.Document document = builder.parse(is); NodeList prepayIdNodes = document.getElementsByTagName("prepay_id"); if(prepayIdNodes.getLength()>0){ Element element=(Element)prepayIdNodes.item(0); return buildFrontEndConfig(element.getTextContent()); }else{ throw new RuntimeException("Failed to obtain prepay_id from wechat server."); } } catch (Exception e) { logger.error(e.getMessage(),e); throw e; } } else { throw new IOException("Unexpected status code:" + response.getStatusLine().getStatusCode()); } } private Map<String,Object> buildFrontEndConfig(String prepayId)throws Exception{ long timestamp=System.currentTimeMillis()/1000L;
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值