Google pay java 后端验证方式二

Google Pay主要支付流程

1.手机端向Java服务端发起支付,生成预订单,给手机端返回生成的订单号

2.手机端向Google发起支付(传入本地服务器生成的订单号)

3.Google服务器将支付结果返回给手机端(因这边用到的是消耗型的产品,所以购买后必须要通知gp我已经消耗了这次交易)

4.手机端向Java服务端发送校验请求,校验通过后即可处理订单(服务端重试校验,发货,保证订单正常发货成功)

配置

packageName:应用包名

credential:密钥

Java服务端处理

前提条件,需要在海外服务器才能成功调取Google Api否则会出现超时的情况

maven依赖:

<project>
  <dependencies>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-androidpublisher</artifactId>
      <version>v3-rev20211125-1.32.1</version>
    </dependency>
  </dependencies>
</project>

 校验代码:

@RestController
public class GoogleController {

    //	packageName为应用程序包名、productId商品id、purchaseToken谷歌返回的收据
    @PostMapping("/")
    public ProductPurchase checkOrder(@RequestBody GooglePayDto googlePayDto,
                              HttpServletRequest requestDto) throws IOException, GeneralSecurityException {
        //使用服务帐户Json文件获取Google凭据
        List<String> scopes = new ArrayList<>();
        scopes.add(AndroidPublisherScopes.ANDROIDPUBLISHER);
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:static/刚下载的json文件,这里放到了static目录下");
        GoogleCredential credential = GoogleCredential.fromStream(resource.getInputStream())
                .createScoped(scopes);
//        使用谷歌凭据和收据从谷歌获取购买信息
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
        AndroidPublisher publisher = new AndroidPublisher.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName("应用程序名").build();
        AndroidPublisher.Purchases purchases = publisher.purchases();
        final AndroidPublisher.Purchases.Products.Get request = purchases.products().get(googlePayDto.getPackageName(), googlePayDto.getProductId(),googlePayDto.getPurchaseToken());
        System.out.println("==============="+request+"================");
        final ProductPurchase purchase = request.execute();
        //处理业务
        Integer purchaseState = purchase.getPurchaseState();
        if (!GooglePayStatus.PURCHASED.getValue().equals(purchaseState) &&!GoogleConsumptionStatus.YET_TO_BE_CONSUMED.getValue().equals(purchase.getConsumptionState())) {
            log.info("==========>订单校验【成功】");
        } else {
            log.info("==========>订单校验【失败】");
        }
        return purchase;
    }
}
public class GooglePayDto {

    String packageName;
    String productId;
    String purchaseToken;

    public String getPackageName() {
        return packageName;
    }

    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public String getPurchaseToken() {
        return purchaseToken;
    }

    public void setPurchaseToken(String purchaseToken) {
        this.purchaseToken = purchaseToken;
    }
}

测试

前台传入三个参数

packageName:包名

productId:商品id

purchaseToken:支付凭证

结果:

image.png

以下是使用Java实现微信支付后端代码的示例: 1. 创建统一下单请求对象 ```java public class UnifiedOrderRequest { private String appid; // 公众账号ID private String mch_id; // 商户号 private String nonce_str; // 随机字符串 private String body; // 商品描述 private String out_trade_no; // 商户订单号 private int total_fee; // 标价金额,单位为分 private String spbill_create_ip; // 终端IP private String notify_url; // 通知地址 private String trade_type; // 交易类型 private String openid; // 用户标识 // 省略 getter 和 setter 方法 } ``` 2. 创建统一下单响应对象 ```java public class UnifiedOrderResponse { private String return_code; // 返回状态码 private String return_msg; // 返回信息 private String appid; // 公众账号ID private String mch_id; // 商户号 private String nonce_str; // 随机字符串 private String sign; // 签名 private String result_code; // 业务结果 private String prepay_id; // 预支付交易会话标识 private String trade_type; // 交易类型 private String code_url; // 维码链接 // 省略 getter 和 setter 方法 } ``` 3. 发送统一下单请求 ```java public class WechatPayService { private static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; public UnifiedOrderResponse unifiedOrder(UnifiedOrderRequest request) throws Exception { String xml = buildUnifiedOrderXml(request); String responseXml = postXml(UNIFIED_ORDER_URL, xml); return parseUnifiedOrderXml(responseXml); } private String buildUnifiedOrderXml(UnifiedOrderRequest request) throws Exception { Map<String, Object> data = new HashMap<>(); data.put("appid", request.getAppid()); data.put("mch_id", request.getMch_id()); data.put("nonce_str", request.getNonce_str()); data.put("body", request.getBody()); data.put("out_trade_no", request.getOut_trade_no()); data.put("total_fee", request.getTotal_fee()); data.put("spbill_create_ip", request.getSpbill_create_ip()); data.put("notify_url", request.getNotify_url()); data.put("trade_type", request.getTrade_type()); data.put("openid", request.getOpenid()); data.put("sign", WechatPayUtil.sign(data, "商户密钥")); return WechatPayUtil.mapToXml(data); } private UnifiedOrderResponse parseUnifiedOrderXml(String xml) throws Exception { Map<String, String> data = WechatPayUtil.xmlToMap(xml); UnifiedOrderResponse response = new UnifiedOrderResponse(); response.setReturn_code(data.get("return_code")); response.setReturn_msg(data.get("return_msg")); response.setAppid(data.get("appid")); response.setMch_id(data.get("mch_id")); response.setNonce_str(data.get("nonce_str")); response.setSign(data.get("sign")); response.setResult_code(data.get("result_code")); response.setPrepay_id(data.get("prepay_id")); response.setTrade_type(data.get("trade_type")); response.setCode_url(data.get("code_url")); return response; } private String postXml(String url, String xml) throws Exception { HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(xml, ContentType.APPLICATION_XML)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String responseXml = EntityUtils.toString(entity); EntityUtils.consume(entity); return responseXml; } } ``` 4. 处理支付结果通知 ```java public class WechatPayNotifyService { public void handleNotify(HttpServletRequest request, HttpServletResponse response, String merchantKey) throws Exception { String xml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8); Map<String, String> data = WechatPayUtil.xmlToMap(xml); if (WechatPayUtil.verifySign(data, merchantKey)) { if ("SUCCESS".equals(data.get("return_code")) && "SUCCESS".equals(data.get("result_code"))) { // 支付成功,处理业务逻辑 } String responseXml = buildNotifyResponseXml("SUCCESS", "OK"); response.getWriter().write(responseXml); } else { String responseXml = buildNotifyResponseXml("FAIL", "签名验证失败"); response.getWriter().write(responseXml); } } private String buildNotifyResponseXml(String returnCode, String returnMsg) { Map<String, String> data = new HashMap<>(); data.put("return_code", returnCode); data.put("return_msg", returnMsg); return WechatPayUtil.mapToXml(data); } } ``` 以上代码仅为示例,实际使用时需要根据具体业务需求进行适当调整。同时,为了确保交易的安全性,建议使用 HTTPS 协议进行通信,并对敏感信息进行加密处理。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值