java版本微信服务商支付

服务商获取证书参数配置

 


import com.cieo.util.PropertyUtil;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

import static org.apache.http.HttpHeaders.ACCEPT;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;

/**
 * 服务商支付参数
 * @author terry
 */
@Component
@Slf4j
@RefreshScope
@Data
public class WeChatServicePayV3Config {


    /**
     * 商户证书序列号
     */
    private String merchantSerialNumber = "商户证书序列号";

    /**
     * 私钥 apiclient_key.pem文件的值
     */
    private String privateKey = "-----BEGIN PRIVATE KEY-----\n" +
            "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyEvVWy/vQ2z01\n" +
            "iJgULoMyEVbPFetVMPcC5lhlg1ZN/3oYE/TJI8fMWkm/CUsmqf/I541aYDDZ9oaH\n" +
            "ol3Sp9n2g8lvIR2tM8rr7nc+PkQ2rnILOELivndUzE9BTj9E63fD8QTTKMWPgiJB\n" +
            "gBXiVX4TR7DiBqVUi0l8/fbY\n" +
            "-----END PRIVATE KEY-----";


    private static final HttpHost proxy = null;


    /**
     * 平台证书认证
     */
    private Verifier verifier;

    /**
     * 创建平台证书验证
     *
     * @return 平台证书验证对象
     * @throws Exception
     */
    public Verifier createVerifier() throws Exception {
        String merchantId = PropertyUtil.getProperty("charge.service.wechat.miniapp.mchId");
        String apiV3Key = PropertyUtil.getProperty("charge.service.wechat.miniapp.v3.key");
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(privateKey);
        // 获取证书管理器实例
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
        // 添加代理服务器
        certificatesManager.setProxy(proxy);
        // 向证书管理器增加需要自动更新平台证书的商户信息
        certificatesManager.putMerchant(merchantId, new WechatPay2Credentials(merchantId,
                        new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)),
                apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 从证书管理器中获取verifier
        Verifier verifier = certificatesManager.getVerifier(merchantId);
        // 构造httpclient
        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
        URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader(ACCEPT, APPLICATION_JSON.toString());
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        return verifier;
    }

}
微信支付证书书定时刷新任务
@Component
@Slf4j
public class WhChatTask {


    @Resource
    private WeChatServicePayV3Config weChatServicePayV3Config;

    /**
     * 定时刷新证书
     *@throws Exception 抛出异常
     */
    @Scheduled(cron = "0 */30 * * * ?")
    public void getVerifierRefresh()throws Exception {
        weChatServicePayV3Config.setVerifier(weChatServicePayV3Config.createVerifier());

    }

    /**
     *启动加载证书
     * @throws Exception
     */
    @Scheduled(initialDelay = 1000, fixedRate = Long.MAX_VALUE)
    public void test()throws Exception {
        weChatServicePayV3Config.setVerifier(weChatServicePayV3Config.createVerifier());
    }
}

服务商微信预下单

   public Map<String, Object> servicePay( String openCode,String outTradeNo,Integer total,String description,String preOrderId) throws Exception {
        WeChatCode2SessionDo authorization_code = weChatAuthClient.jsCode2Session(PropertyUtil.getProperty("charge.wechat.miniapp.appId"),
                PropertyUtil.getProperty("charge.wechat.miniapp.secret"),
                openCode,
                "authorization_code"
        );
        String privateKey = weChatServicePayV3Config.getPrivateKey();
        String merchantSerialNumber = weChatServicePayV3Config.getMerchantSerialNumber();
        String merchantId = PropertyUtil.getProperty("charge.service.wechat.miniapp.mchId");
        String cisMerchantId = PropertyUtil.getProperty("charge.service.wechat.miniapp.cis.mchId");
        String appId = PropertyUtil.getProperty("charge.wechat.miniapp.appId");
        String callbackUrl = PropertyUtil.getProperty("forest.variables.weChatServerCallBackUrlServicePayV3");
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(privateKey);
        X509Certificate wechatPayCertificate = weChatServicePayV3Config.getVerifier().getValidCertificate();

        ArrayList<X509Certificate> wechatPayCertificates = new ArrayList<>();
        wechatPayCertificates.add(wechatPayCertificate);
        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
                .withWechatPay(wechatPayCertificates);
        CloseableHttpClient httpClient = builder.build();

        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi");
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put("sp_mchid", merchantId)
                .put("sp_appid", appId)
                .put("sub_mchid", cisMerchantId)
                .put("description", description)
                .put("notify_url", callbackUrl)
                .put("out_trade_no", outTradeNo);
        rootNode.putObject("amount")
                .put("total", total);
        rootNode.putObject("payer")
                .put("sp_openid", authorization_code.getOpenid());
        objectMapper.writeValue(bos, rootNode);

        httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
        CloseableHttpResponse response = httpClient.execute(httpPost);

        String bodyAsString = EntityUtils.toString(response.getEntity());
        System.out.println("支付回参:+"+bodyAsString);
        String prepayId = JSONObject.parseObject(bodyAsString).getString("prepay_id");
        if(StringUtil.isBlank(prepayId)){
            PreOrderEvent.PreOrderDeleteHandel excelHandel = new PreOrderEvent.PreOrderDeleteHandel(preOrderId);
            eventManager.eventPublish(excelHandel, KelpConstants.adminId);
            Magic.throwException("下订单失败:"+bodyAsString);
        }
        String packageStr = "prepay_id=" + prepayId;
        JSONObject payMap = new JSONObject();
        payMap.put("appId", appId);
        long timestamp = System.currentTimeMillis() / 1000;
        payMap.put("timeStamp", timestamp + "");
        String nonceStr = WeChatPayV3Util.getRandomStringByLength(32);
        payMap.put("nonceStr", nonceStr);
        payMap.put("package", packageStr);
        payMap.put("signType", "RSA");
        // 生成请求签名
        String packageSign = WeChatPayV3Util.sign(WeChatPayV3Util.buildMessage(appId, timestamp, nonceStr, packageStr).getBytes(), privateKey);
        payMap.put("paySign", packageSign);
        bos.close();
        httpClient.close();
        return payMap;
    }
小程序paySign参数的加密
  public static String sign(byte[] message, String privateKey) throws SignatureException,InvalidKeyException, NoSuchAlgorithmException {
        //签名方式
        Signature sign = Signature.getInstance("SHA256withRSA");
        //私钥
        sign.initSign(PemUtil.loadPrivateKey(privateKey));
        sign.update(message);

        return Base64.getEncoder().encodeToString(sign.sign());
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java开发微信服务下载交易账单 V3的具体步骤如下: 1. 导入微信支付 SDK 您可以在 Maven 中添加以下依赖项,以使用微信支付 SDK: ```xml <dependency> <groupId>com.github.wxpay</groupId> <artifactId>wxpay-sdk</artifactId> <version>3.0.9</version> </dependency> ``` 2. 创建微信支付配置 在进行微信支付操作前,需要先创建微信支付配置。可以通过以下代码来创建: ```java WXPayConfig config = new MyWXPayConfig(); WXPay wxpay = new WXPay(config); ``` 其中,MyWXPayConfig 是您自己定义的微信支付配置类。在该类中,需要设置以下参数:appId、mchId、key、certPath、notifyUrl 等。 3. 构建请求参数 在进行微信服务下载交易账单 V3的操作时,需要构建参数并发送请求。可以通过以下代码来构建参数: ```java Map<String, String> reqData = new HashMap<>(); reqData.put("bill_date", "20220801"); reqData.put("bill_type", "ALL"); reqData.put("tar_type", "GZIP"); reqData.put("sub_mch_id", "xxxxxx"); String resp = wxpay.downloadBill(reqData); ``` 其中,bill_date 表示账单日期,格式为yyyyMMdd;bill_type 表示账单类型,可选值包括:ALL、SUCCESS、REFUND、RECHARGE_REFUND 等;tar_type 表示压缩类型,可选值包括:GZIP、UNCOMPRESSED;sub_mch_id 表示子户号,可选参数,如果不传则默认为服务户号。 4. 处理响应结果 微信支付 API 返回的是一个 XML 格式的字符串,需要进行解析。可以通过以下代码来处理响应结果: ```java Map<String, String> respData = WXPayUtil.xmlToMap(resp); ``` 其中,WXPayUtil 是微信支付 SDK 中提供的工具类,可以通过 Maven 中添加以下依赖项来使用: ```xml <dependency> <groupId>com.github.wxpay</groupId> <artifactId>wxpay-java-sdk</artifactId> <version>3.0.9</version> </dependency> ``` 以上就是使用 Java 开发微信服务下载交易账单 V3 的全部步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值