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:支付凭证
结果: