app端直接使用微信支付(不推荐)

Author Avatar ZTFtrue 发表于 • 2017年09月21日 10:51 • 共 • 340 • 次浏览


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import okhttp3.OkHttpClient;


/**
 * Created by ztftrue on 2017/9/20
 */

public class DaShangActivity extends Activity {
    Context context;
  
    int money = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        context = this;
        Intent intent = getIntent();
        money = intent.getIntExtra("money", 1);
   }

    @Override
    protected void onResume() {
        super.onResume();
        getAllPayWeChat();
    }

    public static final String mchid = "";
    public static final String wechatKey = "";
    public static final String appId = "";
    public static final String bodyWechat = "账单名称";
    public static final String Notyurl = "http://通知url";
    String sign;
    WeChat books;
    public void getAllPayWeChat() {
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        OkHttpClient okHttpClient = new OkHttpClient();
        String re = httpsRequest(url, "POST", prepareOrder(appId, "193.112.1.1", getOrdId(), bodyWechat, mchid, getOrdId()));
        System.out.println(re);


        WechatXml parser = new WechatPrase();
        try {
            assert re != null;
            InputStream in_nocode = new ByteArrayInputStream(re.getBytes("UTF-8"));
            books = parser.parse(in_nocode);
        } catch (Exception e) {
            e.printStackTrace();
        }



        IWXAPI api = WXAPIFactory.createWXAPI(DaShangActivity.this, "wx29a44cc4440d0f75");
        api.registerApp("wx29a44cc4440d0f75");
        String timesss = String.valueOf(System.currentTimeMillis());


        String stringA = "appid=" + books.getPrepay_id() +
                "&noncestr=" + books.getNonce_str() +
                "&partnerid=" + mchid + "&package=" + "Sign=WXPay"
                + "&prepayid="
                + books.getPrepay_id();
        stringA = stringA + "×tamp=" + timesss;//注:key为商户平台设置的密钥key
        sign = getMd5(stringA).toUpperCase(); //注:MD5签名方式¬


        if (api.getWXAppSupportAPI() >= com.tencent.mm.opensdk.constants.Build.PAY_SUPPORTED_SDK_INT) {
            PayReq req = new PayReq();
            req.appId = "wx29a44cc4440d0f75";
            req.prepayId = books.getPrepay_id();
            req.nonceStr = books.getNonce_str();

            req.partnerId = mchid;

            req.timeStamp = timesss;
            req.packageValue = "Sign=WXPay";

            req.sign = timesss;
            req.extData = "app data";


            api.sendReq(req);
        } else {
            Toast.makeText(context, getString(R.string.no_suport_wechat), Toast.LENGTH_SHORT).show();
        }
        finish();
    }



    public String getOrdId() {
        UUID uuid = UUID.randomUUID();
        String a = uuid.toString();
        a = a.replace("-", "");

        if (a.length() > 32) {
            a = a.substring(0, 31);
        }
        return a;
    }

    /**
     * 用于获取一个String的md5值
     *
     * @param str
     * @return
     */
    public static String getMd5(String str) {
        byte[] bs = new byte[0];
        try {
            bs = MessageDigest.getInstance("MD5").digest(str.getBytes());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }


    private String prepareOrder(String appid, String ip, String orderId,
                                String body, String mchid, String nonceStr) {
        String stringA = "appid=" + appid + "&body=" + body + "&device_info=WEB" + "&mch_id="
                + mchid + "&nonce_str=" + nonceStr + "¬ify_url="
                + Notyurl + "&out_trade_no=" + orderId + /*"&sign_type=MD5" +*/ "&spbill_create_ip=" + ip
                + "&total_fee=" + money + "&trade_type=APP";
        stringA = stringA + "&key=" + wechatKey;//注:key为商户平台设置的密钥key
        sign = getMd5(stringA).toUpperCase(); //注:MD5签名方式¬
        Map<String, Object> oparams = new HashMap<>();
        oparams.put("appid", appid);//应用号
        oparams.put("body", body);// 商品描述
        oparams.put("mch_id", mchid);// 商户号
        oparams.put("device_info", "WEB");// 商户号
        oparams.put("nonce_str", nonceStr);// 16随机字符串(大小写字母加数字)
        oparams.put("notify_url", Notyurl);// 微信回调地址
        oparams.put("out_trade_no", orderId);// 商户订单号
//        oparams.put("sign_type", "MD5");
        oparams.put("spbill_create_ip", ip);// IP地址
        oparams.put("total_fee", money);
        oparams.put("trade_type", "APP");// 支付类型 APP
        oparams.put("sign", sign);


        UUID uuid = UUID.randomUUID();
        nonceStr = uuid.toString();
        if (nonceStr.length() > 32) {
            nonceStr = nonceStr.replace("-", "");
        }
        if (nonceStr.length() > 32) {
            nonceStr = nonceStr.substring(0, 31);
        }


        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        mapToXMLTest2(oparams, sb);
        sb.append("</xml>");
        return sb.toString();
    }

    private void mapToXMLTest2(Map map, StringBuffer sb) {
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext(); ) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (null == value)
                value = "";
            if (value.getClass().getName().equals("java.util.ArrayList")) {
                ArrayList list = (ArrayList) map.get(key);
                sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++) {
                    HashMap hm = (HashMap) list.get(i);
                    mapToXMLTest2(hm, sb);
                }
                sb.append("</" + key + ">");

            } else {
                if (value instanceof HashMap) {
                    sb.append("<" + key + ">");
                    mapToXMLTest2((HashMap) value, sb);
                    sb.append("</" + key + ">");
                } else {
                    sb.append("<" + key + ">" + value + "</" + key + ">");
                }

            }

        }
    }

    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {

            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时:{}" + ce);
        } catch (Exception e) {
            System.out.println("https请求异常:{}" + e);
        }
        return null;
    }
}

//解析xml
public class WeChat {


    /**
     * appid : 
     * attach : 支付测试
     * body : APP支付测试
     * mch_id : 
     * nonce_str : 1add1a30ac87aa2db72f57a2375d8fec
     * notify_url : 
     * out_trade_no : 1415659990
     * spbill_create_ip : 14.23.150.211
     * total_fee : 1
     * trade_type : APP
     * sign : 0CB01533B8C1EF103065174F50BCA001
     */

    private String appid;
    private String attach;
    private String body;
    private String mch_id;
    private String nonce_str;
    private String notify_url;
    private String out_trade_no;
    private String spbill_create_ip;
    private String total_fee;
    private String trade_type;
    private String sign;
private String prepay_id;

    public String getPrepay_id() {
        return prepay_id;
    }

    public void setPrepay_id(String prepay_id) {
        this.prepay_id = prepay_id;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public void setAttach(String attach) {
        this.attach = attach;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public void setMch_id(String mch_id) {
        this.mch_id = mch_id;
    }

    public void setNonce_str(String nonce_str) {
        this.nonce_str = nonce_str;
    }

    public void setNotify_url(String notify_url) {
        this.notify_url = notify_url;
    }

    public void setOut_trade_no(String out_trade_no) {
        this.out_trade_no = out_trade_no;
    }

    public void setSpbill_create_ip(String spbill_create_ip) {
        this.spbill_create_ip = spbill_create_ip;
    }

    public void setTotal_fee(String total_fee) {
        this.total_fee = total_fee;
    }

    public void setTrade_type(String trade_type) {
        this.trade_type = trade_type;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getAppid() {
        return appid;
    }

    public String getAttach() {
        return attach;
    }

    public String getBody() {
        return body;
    }

    public String getMch_id() {
        return mch_id;
    }

    public String getNonce_str() {
        return nonce_str;
    }

    public String getNotify_url() {
        return notify_url;
    }

    public String getOut_trade_no() {
        return out_trade_no;
    }

    public String getSpbill_create_ip() {
        return spbill_create_ip;
    }

    public String getTotal_fee() {
        return total_fee;
    }

    public String getTrade_type() {
        return trade_type;
    }

    public String getSign() {
        return sign;
    }

}
package com.morview.mesumeguide.activity.home;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

/**
 * Created by ztftrue on 2017/9/20
 */

public class WechatPrase implements WechatXml {
    @Override
    public WeChat parse(InputStream is) throws Exception {
        SAXParserFactory factory = SAXParserFactory.newInstance();  //取得SAXParserFactory实例
        SAXParser parser = factory.newSAXParser();                  //从factory获取SAXParser实例
        MyHandler handler = new MyHandler();                        //实例化自定义Handler
        parser.parse(is, handler);                                  //根据自定义Handler规则解析输入流
        return handler.getWeChats();
    }

    @Override
    public String serialize(List<WeChat> weChats) throws Exception {
        SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();//取得SAXTransformerFactory实例
        TransformerHandler handler = factory.newTransformerHandler();           //从factory获取TransformerHandler实例
        Transformer transformer = handler.getTransformer();                     //从handler获取Transformer实例
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");            // 设置输出采用的编码方式
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");                // 是否自动添加额外的空白
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");   // 是否忽略XML声明

        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        handler.setResult(result);

        String uri = "";    //代表命名空间的URI 当URI无值时 须置为空字符串
        String localName = "";  //命名空间的本地名称(不包含前缀) 当没有进行命名空间处理时 须置为空字符串

        handler.startDocument();
        handler.startElement(uri, localName, "books", null);

        AttributesImpl attrs = new AttributesImpl();    //负责存放元素的属性信息
        char[] ch = null;
        for (WeChat book : weChats) {
            attrs.clear();  //清空属性列表
            attrs.addAttribute(uri, localName, "id", "string", String.valueOf(book.getAppid()));//添加一个名为id的属性(type影响不大,这里设为string)
            handler.startElement(uri, localName, "book", attrs);    //开始一个book元素 关联上面设定的id属性

            handler.startElement(uri, localName, "name", null); //开始一个name元素 没有属性
            ch = String.valueOf(book.getAppid()).toCharArray();
            handler.characters(ch, 0, ch.length);   //设置name元素的文本节点
            handler.endElement(uri, localName, "name");

            handler.startElement(uri, localName, "price", null);//开始一个price元素 没有属性
            ch = String.valueOf(book.getAppid()).toCharArray();
            handler.characters(ch, 0, ch.length);   //设置price元素的文本节点
            handler.endElement(uri, localName, "price");

            handler.endElement(uri, localName, "book");
        }
        handler.endElement(uri, localName, "books");
        handler.endDocument();

        return writer.toString();
    }


    //需要重写DefaultHandler的方法  
    private class MyHandler extends DefaultHandler {

        private WeChat WeChats;
        private StringBuilder builder;

        //返回解析后得到的WeChat对象集合  
        public WeChat getWeChats() {
            return WeChats;
        }

        @Override
        public void startDocument() throws SAXException {
            super.startDocument();
            WeChats = new WeChat();
            builder = new StringBuilder();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            super.startElement(uri, localName, qName, attributes);
            if (localName.equals("xml")) {
                WeChats = new WeChat();
            }
            builder.setLength(0);   //将字符长度设置为0 以便重新开始读取元素内的字符节点  
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            super.characters(ch, start, length);
            builder.append(ch, start, length);  //将读取的字符数组追加到builder中  
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            super.endElement(uri, localName, qName);
            if (localName.equals("nonce_str")) {
                WeChats.setNonce_str(builder.toString());
            } else if (localName.equals("sign")) {
                WeChats.setSign(builder.toString());
            } else if (localName.equals("prepay_id")) {
                WeChats.setPrepay_id(builder.toString());
            }
        }
    }

}
public interface WechatXml {
    /**
     * 解析输入流 得到Book对象集合
     *
     * @param is
     * @return
     * @throws Exception
     */
    public WeChat parse(InputStream is) throws Exception;

    /**
     * 序列化Book对象集合 得到XML形式的字符串
     *
     * @param books
     * @return
     * @throws Exception
     */
    public String serialize(List<WeChat> books) throws Exception;
}


共有1个红包,共5
  1. ZTFtrue2017年09月21日 10:51 前创建了 5 元的红包; 红包已经充入.
最后编辑于 • 2017年09月24日 13:38 •  
3 回复
avatar
0
发放红包 2017年09月21日 15:19   # 1 楼

这java写的,代码写的有点臃肿啊😅😅😅


avatar
0
发放红包 2017年09月22日 10:15   # 2 楼

java语法没有出来。 三个点后加上java,应该会出来语法颜色。


public static void main() {
}

!我的天。好象语法着色有问题。


avatar
0
ZTFtrue 楼主
发放红包 2017年09月23日 18:50   # 3 楼

除了这个方法prepareOrder,请指出臃肿的地方 @yiqiquhuxi

你尚未登录,无法进行回复。