1. Android for wechat

1.1 Android Java:

JSONObject data = (JSONObject) bundle.getSerializable("data");
// {appid=wx7f229e38a04f2bec, noncestr=LXyHXBUVh39LYBrK, package=Sign=WXPay, partnerid=1523808161, prepayid=wx2613502950188989bf5937ec1163319167, sign=50F044924686609080E94B7C6EB7969E, timestamp=1551160229}
PayReq req = new PayReq();
req.appId = data.getString("appid");
req.partnerId = data.getString("partnerid");
req.prepayId = data.getString("prepayid");
req.nonceStr = data.getString("noncestr");
req.timeStamp = data.getString("timestamp");
req.packageValue = data.getString("package");
req.sign = data.getString("sign");
​
Log.d(TAG, req.checkArgs() + " param check result");
boolean v = api.sendReq(req);
Log.d(TAG, v + " startup pay result");

2.Android for Alipay

2.1 Init Alipay parameter

// APP_ID
private final String APP_ID = "20190307001";
       

2.2 Init the API parameter


// pay channel API
private final  String  BASE_URL =  "http://cashier.51mandou.com";
private final String GET_PAY_TOOLS = BASE_URL + "/payTools.json" ;

// createOrder API
public  final  String  CREATE_ORDER  =  BASE_URL+"/order.json";

 // order amount 
String amountStr = "99";

// your business No.
String bizNoStr = "biz No" ;

// your goods title
String titleStr = " test goods title";

// your app_id and secret
private final String APP_SECRET = "123";
   
// build request heads
private Headers headers = Headers.of("APP_ID", APP_ID, "APP_SECRET", APP_SECRET)

2.3 invoke pay channel API to get the pay channel


// the Request object is from okhttp3  jar
Request request = new Request.Builder()
                .url(Api.buildUrl(GET_PAY_TOOLS))
                .headers(headers)
                .build();

Call call   =  new  OkHttpClient().newCall(request);;

// call response
call.enqueue(new Callback() {
    
       // if response failure 
     @Override
     public void onFailure(Call call, IOException e) {
            Looper.prepare();
            Toast.makeText(MainActivity.this, "request failed",         Toast.LENGTH_LONG).show();
            Looper.loop();
     }
    
    // if request success
    @Override
    public void onResponse(Call call, Response response) throws IOException {
            String s = response.body().string();
            Log.d(TAG, "onResponse: " + s);

            JSONObject result = JSON.parseObject(s);

            String code = result.getString("code");

            // if the response is successful ,the code = "0"
            // for more detailed response information ,view the 
            // payTools.json API  
            // https://www.kancloud.cn/mandou/appinchinapay/965247
            if ("0".equals(code)) {

                // get the payTools.json api response data
                // to init you app pay view
                // the doInitPayTools() method detail is on the next step
                doInitPayTools(result.getJSONArray("data"));

            } else {

                Looper.prepare();
                Toast.makeText(getApplication(), result.getString("msg"), Toast.LENGTH_LONG).show();
                Looper.loop();

            }
        }
    });

2.4 Get pay channel API result and Init app view

// payToolList is payTools.json api result
private void doInitPayTools(JSONArray payToolList) {

        if (payToolList == null || payToolList.size() == 0) {
            Toast.makeText(MainActivity.this, "your app has not regested", Toast.LENGTH_LONG).show();
            return;
        }

        for (int i = 0; i < payToolList.size(); i++) {

            JSONObject payTool = payToolList.getJSONObject(i);
            String appId = payTool.getString("id");

            // get pay channel
            String payChannel = payTool.getString("payChannel");

            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("appId", appId);
            msg.setData(bundle);

            if ("WECHAT".equalsIgnoreCase(payChannel)) {
                msg.what = MSG_SHOW_WECHAT;
            } else if ("ALIPAY".equalsIgnoreCase(payChannel)) {
                msg.what = MSG_SHOW_ALIPAY;
            }

            handler.sendMessage(msg);
        }
    }

Handle process message


private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            String appId = msg.getData().getString("appId");

            switch (msg.what) {
                    case MSG_SHOW_ALIPAY:
                        //TODO:  to do your business  or init view
                        
                        // request apliPay, the method is at next step
                        sendPayRequest("ALIPAY");
                        break;
                    default:
                        break;
            }
        }
    };

2.5 Request Create Order API

private  void  sendPayRequest(final  String  payChannel) {

    // build the request parameter
    Map<String, Object> params = new HashMap<>();
        params.put("amount", new BigDecimal(amountStr).multiply(new BigDecimal(100)).longValue());
        params.put("bizNo", bizNoStr);
        params.put("goodsTitle", titleStr);
        params.put("payChannel", payChannel);

    // build the request object
        Request request = new Request.Builder()
                .url(CREATE_ORDER)
                 .post(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JSONObject.toJSONString(params)))
                .headers(headers)
                .build();
}

// callback process
Call call =  new OkHttp().newCall(request);
call.enqueue(new Callback() {
            // request failed callback 
            @Override
            public void onFailure(Call call, IOException e) {
                Looper.prepare();
                Toast.makeText(MainActivity.this, "request failed", Toast.LENGTH_LONG).show();
                Looper.loop();
            }

            // success response
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                // get  response data
                String s = response.body().string();

                Log.d(TAG, "onResponse: " + s);

                JSONObject result = JSON.parseObject(s);
                String code = result.getString("code");

                
                // if request is successful , code = "0"
                if ("0".equals(code)) {
                    JSONObject data = result.getJSONObject("data");
                    data.put("payChannel", payChannel);

                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", data);
                    
                    // handler process your business
                    msg.setData(bundle);
                    msg.what = MSG_CREATE_ORDER_RESP;
                    handler.sendMessage(msg);

                } else {
                    Looper.prepare();
                    Toast.makeText(MainActivity.this, result.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

handle process

private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
           
            switch (msg.what) {
                case MSG_CREATE_ORDER_RESP:

                    // to call alipay
                   JSONObject data = (JSONObject) bundle.getSerializable("data");

                    // the callAlipay(data) method is at next step
                    callAlipay(data);
                    break;
             
            }
        }
    };

2.6 Call Alipay

private void callAlipay(JSONObject data) {
        String sign = data.getString("sign");

        // remove useless key-value parameter
        data.remove("sign");
        data.remove("payChannel");
        
        // build request aplipay orderinfo paramter
        StringBuffer sb = new StringBuffer();
        for(String k: data.keySet()) {
            sb.append(k);
            sb.append('=');
            try {
                sb.append(URLEncoder.encode(data.getString(k), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sb.append('&');
        }

        try {
            sb.append("sign=").append(URLEncoder.encode(sign, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        final String orderInfo = sb.toString();

        Log.d(TAG, orderInfo);

        
        // request aplipay at new thread
        new Thread(new Runnable() {

            @Override
            public void run() {

                // Request Alipay 
                PayTask alipay = new PayTask(MainActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                
                // TODO :
                // if you want to show pay result page ,you can use Handle to process

               // Message msg = new Message();
                //msg.what = "pay_success";
                //msg.obj = result;
                //handler.sendMessage(msg);

            }
        }).start();
    }


3.Full Demo

3.1 Full demo url

https://github.com/yangfjiahl/Voucher.git