(原创)微信支付SDK调用的核心代码与分析(基于Android)

时间:2015-12-09 17:04:51   收藏:0   阅读:1005

先上代码,后面会分析

String url = "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android";
Button payBtn = (Button) findViewById(R.id.appay_btn);
payBtn.setEnabled(false);
Toast.makeText(PayActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
try{
byte[] buf = Util.httpGet(url);
if (buf != null && buf.length > 0) {
String content = new String(buf);
Log.e("get server pay params:",content);
JSONObject json = new JSONObject(content); 
if(null != json && !json.has("retcode") ){
PayReq req = new PayReq();
//req.appId = "wxf8b4f85f3a794e77"; // 测试用appId
req.appId    = json.getString("appid");
req.partnerId    = json.getString("partnerid");
req.prepayId    = json.getString("prepayid");
req.nonceStr    = json.getString("noncestr");
req.timeStamp    = json.getString("timestamp");
req.packageValue    = json.getString("package");
req.sign    = json.getString("sign");
req.extData    = "app data"; // optional
Toast.makeText(PayActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
// 在支付之前,如果应用没有注册到微信,应该先调用IWXMsg.registerApp将应用注册到微信
api.sendReq(req);
}else{
Log.d("PAY_GET", "返回错误"+json.getString("retmsg"));
Toast.makeText(PayActivity.this, "返回错误"+json.getString("retmsg"), Toast.LENGTH_SHORT).show();
}
}else{
Log.d("PAY_GET", "服务器请求错误");
Toast.makeText(PayActivity.this, "服务器请求错误", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
Log.e("PAY_GET", "异常:"+e.getMessage());
Toast.makeText(PayActivity.this, "异常:"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
payBtn.setEnabled(true);

其核心action为:

byte[] buf = Util.httpGet(url);
httpGet方法的代码如下:
public static byte[] httpGet(final String url) {
        if (url == null || url.length() == 0) {
            Log.e(TAG, "httpGet, url is null");
            return null;
        }

        HttpClient httpClient = getNewHttpClient();
        HttpGet httpGet = new HttpGet(url);

        try {
            HttpResponse resp = httpClient.execute(httpGet);
            if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());
                return null;
            }

            return EntityUtils.toByteArray(resp.getEntity());

        } catch (Exception e) {
            Log.e(TAG, "httpGet exception, e = " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

这里本质上是一个http的get请求,返回json格式的字符串.

在发出的请求中会将订单和app的信息传给服务器.并调用手机中的微信app

支付完成后,会从服务器拿到支付返回结果.

腾讯是保证分布式事务的一致性的,根据返回结果代码就可以知道支付效果.

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!