java的ios内购代码

业务处理层


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.okgene.vip.Fire.bean.UserInfoWX;
import org.okgene.vip.OKXSS;
import org.okgene.vip.fireFly.service.pay.ApplePayService;
import org.okgene.vip.pojo.ExtResult;
import org.okgene.vip.utils.IosVerifyUtil;
import org.okgene.vip.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/app")
public class ApplePayController {

    Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ApplePayService applePayService;


    /**
     * TransactionID:苹果配置的产品id
     *  Payload:需要客户端传过来的参数2
     * 苹果内购支付
     * @Title: doIosRequest
     * @Description:Ios客户端内购支付
     */
    @RequestMapping("/applePay")
    @OKXSS
    public  ExtResult doIosRequest(HttpServletRequest request, @RequestBody JSONObject object)  {
        ExtResult ext = ExtResult.NEW();
        String TransactionID = object.getString("transactionId");
        String Payload = object.getString("payload");
        String type = object.getString("type");
        Long channelId = object.getLong("channelId");
        Long orderId = object.getLong("orderId");
        if (StringUtils.isBlank(TransactionID)||StringUtils.isBlank(Payload)||StringUtils.isBlank(type)||channelId==null||orderId==null){
            ext.setMsg("缺少参数");
            ext.setCode(-1);
            return ext;
        }
//        System.out.println("客户端传过来的值1:" + TransactionID + "客户端传过来的值2:" + Payload);
        //1.先线上测试    发送平台验证
        String verifyResult = IosVerifyUtil.buyAppVerify(Payload, 1);
        // 苹果服务器没有返回验证结果
        if (verifyResult == null) {
            ext.setMsg("无订单信息!");
            ext.setCode(-1);
            return ext;
        } else {
            // 苹果验证有返回结果
            log.info("线上,苹果平台返回JSON:" + verifyResult);
            JSONObject job = JSONObject.parseObject(verifyResult);
            String states = job.getString("status");
            //是沙盒环境,应沙盒测试,否则执行下面
            if ("21007".equals(states)) {
                //2.再沙盒测试  发送平台验证
                verifyResult = IosVerifyUtil.buyAppVerify(Payload, 0);
                log.info("沙盒环境,苹果平台返回JSON:" + verifyResult);
                job = JSONObject.parseObject(verifyResult);
                states = job.getString("status");
            }
            log.info("苹果平台返回值:job" + job);
            if ("0".equals(states)) {
                // 前端所提供的收据是有效的    验证成功
                //处理自己的业务
                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)) {
                    UserInfoWX appUser = Tools.getCurrentAppUser(request);
                    try {
                        ext.setMsg(applePayService.pay(type,orderId,appUser,channelId));
                    }catch (Exception e){
                        log.info("applePay 修改数据失败",e);
                        ext.setCode(-1);
                        ext.setMsg("支付异常,请联系客服");
                    }
                    return ext;
                }
  /************************************************+自己的业务逻辑end**********************************************************/
            } else {
                ext.setMsg( "receipt数据有问题");
                ext.setCode(-1);
            }
        }
        return ext;
    }
} 

用到的工具类


import javax.net.ssl.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Locale;


public class IosVerifyUtil {


    private static class TrustAnyTrustManager implements X509TrustManager {

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

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

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

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        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 账单
     * @return null 或返回结果 沙盒 https://sandbox.itunes.apple.com/verifyReceipt
     * @url 要验证的地址
     */
    public static String buyAppVerify(String receipt, int type) {
        //环境判断 线上/开发环境用不同的请求链接
        String url = "";
        if (type == 0) {
            url = url_sandbox; //沙盒测试
        } else {
            url = url_verify; //线上测试
        }
        //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-data\":\"" + receipt + "\"}");
            hurlBufOus.write(str.getBytes());
            hurlBufOus.flush();

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

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

        }
        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;
    }
}




你可能感兴趣的:(Java,ios)