当前位置: 首页 > 工具软件 > iOS Spring > 使用案例 >

Spring Boot + IOS内购(IAP)

岳劲
2023-12-01

分享一个关于IAP(IOS内购)的项目

IAP验证工具类

/**
 * @program: learningapi
 * @description: IOS验证工具
 * @author: Irving Wei
 * @create: 2018-09-10 17:20
 **/
public class IosVerifyUtil {

    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static final String url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
    private static final String url_verify = "https://buy.itunes.apple.com/verifyReceipt";

    /**
     * 苹果服务器验证
     *
     * @param receipt
     *            账单
     * @url 要验证的地址
     * @return null 或返回结果 沙盒 https://sandbox.itunes.apple.com/verifyReceipt
     *
     */
    public static String buyAppVerify(String receipt,int type) {
        //环境判断 线上/开发环境用不同的请求链接
        String url = "";
        if(type==0){
            url = url_sandbox; //沙盒测试
        }else{
            url = url_verify; //线上测试
        }
        //  将传过来的转义符 """ 替换成 "\""
        receipt = receipt.replaceAll(""","\"");

        //String url = EnvUtils.isOnline() ?url_verify : url_sandbox;

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL console = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "text/json");
            conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            BufferedOutputStream hurlBufOus = new BufferedOutputStream(conn.getOutputStream());

            String str = String.format(Locale.CHINA, receipt);//拼成固定的格式传给平台
            hurlBufOus.write(str.getBytes());
            hurlBufOus.flush();

            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            return sb.toString();
        } catch (Exception ex) {
            System.out.println("苹果服务器异常");
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 用BASE64加密
     *
     * @param str
     * @return
     */
    public static String getBASE64(String str) {
        byte[] b = str.getBytes();
        String s = null;
        if (b != null) {
            s = new sun.misc.BASE64Encoder().encode(b);
        }
        return s;
    }

}

业务代码

/**
 * @program: learningapi
 * @description: IOS 内购
 * @author: Irving Wei
 * @create: 2018-09-10 17:02
 **/

@Controller
@RequestMapping("/buy")
public class IapChargeController extends AbstractRestController {
    @Autowired
    private LoggerService loggerService;

    @ApiOperation(value = "ios内购-充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户 Token", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "payload", value = "需要客户端传过来的参数", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "transactionID", value = "交易单号,需要客户端传过来的参数", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/recharge", method = RequestMethod.GET)
    @Transactional
    public ResponseEntity<WrappedResponse<List<AppBannerEntity>>> getBanner(HttpServletRequest request) {
        String token = ServletRequestUtils.getStringParameter(request, "token", "");
        String transactionID = ServletRequestUtils.getStringParameter(request, "transactionID", "");
        String payload = ServletRequestUtils.getStringParameter(request, "payload", "");

        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("客户端传过来的值1:" + transactionID + "客户端传过来的值2:" + payload);

        String verifyResult = IosVerifyUtil.buyAppVerify(payload, 1);            //1.先线上测试    发送平台验证
        if (verifyResult == null) {                                            // 苹果服务器没有返回验证结果
            System.out.println("无订单信息!");
        } else {                                                                // 苹果验证有返回结果
            System.out.println("线上,苹果平台返回JSON:" + verifyResult);
            JSONObject job = JSONObject.parseObject(verifyResult);
            String states = job.getString("status");

            if ("21007".equals(states)) {                                            //是沙盒环境,应沙盒测试,否则执行下面
                verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);            //2.再沙盒测试  发送平台验证
                System.out.println("沙盒环境,苹果平台返回JSON:" + verifyResult);
                job = JSONObject.parseObject(verifyResult);
                states = job.getString("status");
            }

            System.out.println("苹果平台返回值:job" + job);

          

            if (!"0".equals(states)) {
                // 记录日志,并返回失败
                
                return this.fail();
            } else {// 前端所提供的收据是有效的    验证成功
                String r_receipt = job.getString("receipt");
                JSONObject returnJson = JSONObject.parseObject(r_receipt);
                String in_app = returnJson.getString("in_app");
                JSONObject in_appJson = JSONObject.parseObject(in_app.substring(1, in_app.length() - 1));

                String product_id = in_appJson.getString("product_id");
                String transaction_id = in_appJson.getString("transaction_id");   // 订单号
/************************************************+自己的业务逻辑**********************************************************/

                if (transactionID.equals(transaction_id)) {
                    
                }
/************************************************+自己的业务逻辑end**********************************************************/
                return null;
            }
        }
        return null;
    }
}

 

 类似资料: