安卓 集成微信支付和支付宝

最近比较闲,公司项目更换后台,于是自己来研究微信支付和支付宝支付,把自己学习的过程写下来,以备以后查看。

注:要集成微信支付和支付宝功能,必须要有以下几个配置信息,而这写信息需要公司去微信支付和支付宝开放平台申请并提供给开发者,当然自己也可以去申请,这里作者用的是公司提供的,这里不纠结这些过程。获得这些信息以后

将配置信息放到一个静态类中,以共统一使用,但是处于安全考虑,微信与支付宝推荐这些数据放到服务器,这里作者把他们都放在前端,整个过程都是前端处理,实际开发尽量预处理订单生成放到后端处理。
[java]  view plain  copy
  1. public class ParameterConfig {  
  2.       
  3.     public static final String  GANHOST = "http://101.226.197.11"; //服务器地址ip(根据自己替换)  
  4.   
  5.     /** 
  6.      * 微信 
  7.      */  
  8.    <span style="white-space:pre"> </span> //appid  
  9.     public static final String WX_APP_ID = "";// 自己填写自己项目的  
  10.     // 商户号  
  11.     public static final String WX_MCH_ID = "";// 自己填写自己项目的  
  12.     // API密钥,在商户平台设置  
  13.     public static final String WX_API_KEY = "";// 自己填写自己项目的  
  14.     //服务器回调接口  
  15.     public static final String WX_notifyUrl = GANHOST+"/service/orderComplete";// 用于微信支付成功的回调(按自己需求填写)  
  16.   
  17.       
  18.     /** 
  19.      * 支付宝 
  20.      */  
  21.     // 商户PID  
  22.     public static final String PARTNER = "";//自己填写自己项目的  
  23.     // 商户收款账号  
  24.     public static final String SELLER = "";//自己填写自己项目的  
  25.     // 商户私钥,pkcs8格式  
  26.     public static final String RSA_PRIVATE = "";//自己填写自己项目的  
  27.       
  28.     public static final String aliPay_notifyURL = GANHOST+"/service/alipay/orderComplete";//支付宝支付成功的回调  
  29.       
  30. }  

1.微信支付的集成前提条件

1.首先需要导入微信jar包,从开放平台可以下载到,加入到libs目录即可
2.配置manifest 

	a.用户权限

	<uses-permission android:name="android.permission.INTERNET" />
    	<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
    	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>	
 
 

b.activity配置,这里com.gan.mypay改成自己的包名(如果自己包名与src下的package 名不一样,这里要的是在manifest中配置的名称,同样需要在src建立以自己包名为路劲的package,一定确保有这个activity)这个activity是微信支付结果要回调的activty


   <!-- 微信支付 -->
        <activity
            android:name="com.gan.mypay.wxapi.WXPayEntryActivity"
             android:exported="true"
            android:launchMode="singleTop"/>
          <!-- 微信支付 -->

2.支付宝支付的集成前提条件

1.首先需要导入微信jar包,从开放平台可以下载到,加入到libs目录即可
2.配置manifest 

a .用户权限

	<uses-permission android:name="android.permission.INTERNET" />
    	<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
    	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

b.activity配置这里必须要这么配置

   <!-- 支付宝 -->
         <activity
            android:name="com.alipay.sdk.app.H5PayActivity"
             android:configChanges="orientation|keyboardHidden|navigation"
             android:exported="false"
             android:screenOrientation="behind" >
</activity>
<activity
            android:name="com.alipay.sdk.auth.AuthActivity"
           android:configChanges="orientation|keyboardHidden|navigation"
           android:exported="false"
           android:screenOrientation="behind" >
</activity>
<!-- 支付宝 -->

3.代码集成

1.首先要有个商品页面MainActivity,用来手机收集商品信息,这里需要后台交互生成订单,我偷懒就直接在页面生成了假订单

商品详情页
MainActivity.java(这里用了xutils的注入)
[java]  view plain  copy
  1. @ContentView(R.layout.activity_main)  
  2. public class MainActivity extends Activity {  
  3.   
  4.       
  5.     private Goods goods;  
  6.     private String username;  
  7.     private String mobile;  
  8.     private String adress;  
  9.     private int count;  
  10.   
  11.     @ViewInject(R.id.product_ordsubmit_username)  
  12.     private TextView usernameTV;  
  13.       
  14.     @ViewInject(R.id.product_ordsubmit_phone)  
  15.     private TextView phoneTV;  
  16.   
  17.     @ViewInject(R.id.product_ordsubmit_adress)  
  18.     private TextView adressTV;  
  19.   
  20.     @ViewInject(R.id.product_ordsubmit_desc)  
  21.     private TextView descTV;  
  22.       
  23.     @ViewInject(R.id.product_ordsubmit_price)  
  24.     private TextView priceTV;  
  25.       
  26.     @ViewInject(R.id.product_ordsubmit_intg)  
  27.     private TextView intgTV;  
  28.       
  29.     @ViewInject(R.id.product_ordsubmit_count1)  
  30.     private TextView countTV1;  
  31.       
  32.     @ViewInject(R.id.product_ordsubmit_count)  
  33.     private TextView countTV;  
  34.       
  35.     @ViewInject(R.id.product_ordsubmit_intgtotal1)  
  36.     private TextView intgtotal1TV;  
  37.       
  38.     @ViewInject(R.id.product_ordsubmit_intgtotal2)  
  39.     private TextView intgtotal2TV;  
  40.       
  41.     @ViewInject(R.id.product_ordsubmit_pricetotal1)  
  42.     private TextView pricetotal1TV;  
  43.       
  44.     @ViewInject(R.id.product_ordsubmit_pricetotal2)  
  45.     private TextView pricetotal2TV;  
  46.       
  47.     @ViewInject(R.id.product_ordsubmit_counttotal)  
  48.     private TextView counttotalTV;  
  49.       
  50.     @ViewInject(R.id.product_ordsubmit_ok)  
  51.     private Button okBtn;  
  52.       
  53.     @ViewInject(R.id.product_ordsubmit_say_et)  
  54.     private TextView sayEt;  
  55.       
  56.     @ViewInject(R.id.product_ordsubmit_img)  
  57.     private ImageView img;  
  58.       
  59.     @Override  
  60.     protected void onCreate(Bundle savedInstanceState) {  
  61.         super.onCreate(savedInstanceState);  
  62.         ViewUtils.inject(this);  
  63.         goods = new Goods();  
  64.         goods.costprice=100;  
  65.         goods.productid=692356222;  
  66.         goods.producttypeid=11;  
  67.         goods.productname="测试商品";  
  68.         goods.discountprice=0.01;  
  69.         goods.productdescription="商品描述";  
  70.         goods.companydesc="测试商户简单描述";  
  71.         goods.comanyadress="商户地址未知";  
  72.         goods.companyname="测试商户";  
  73.         goods.score=1;  
  74.         goods.status=1;  
  75.         goods.stock=300;  
  76.         count=1;  
  77.         initData();  
  78.         initView();  
  79.     }  
  80.   
  81.       
  82.       
  83.     private void initData() {  
  84.           
  85.             username ="客户名称";  
  86.             mobile = "13800380038";  
  87.             adress="客户地址";  
  88.               
  89.     }  
  90.   
  91.   
  92.   
  93.     private void initView() {     
  94.             usernameTV.setText("收货人:"+username);  
  95.             phoneTV.setText(mobile+"");  
  96.             adressTV.setText(adress);  
  97.             descTV.setText(goods.productdescription);  
  98.             priceTV.setText("¥"+goods.discountprice);  
  99.             intgTV.setText("积分:"+goods.score);  
  100.             countTV1.setText("X"+count);  
  101.             countTV.setText(count+"");  
  102.             intgtotal1TV.setText("共得到"+count*goods.score+"积分");  
  103.             intgtotal2TV.setText("积分:"+count*goods.score);  
  104.             counttotalTV.setText("共"+count+"件");  
  105.             pricetotal1TV.setText("¥"+Arith.mul(goods.discountprice, count));  
  106.             pricetotal2TV.setText("¥"+Arith.mul(goods.discountprice, count));  
  107.             //ImageLoader.getInstance().displayImage(goods.pic1, img);  
  108.     }  
  109.   
  110.     /** 
  111.      * 增加数量 
  112.      * @param v 
  113.      */  
  114.     @OnClick(R.id.product_ordsubmit_count_add)  
  115.     public void add(View v) {  
  116.         count++;  
  117.         countTV1.setText("X"+count);  
  118.         countTV.setText(count+"");  
  119.         intgtotal1TV.setText("共得到"+count*goods.score+"积分");  
  120.         intgtotal2TV.setText("积分:"+count*goods.score);  
  121.         counttotalTV.setText("共"+count+"件");  
  122.         pricetotal1TV.setText("¥"+Arith.mul(goods.discountprice, count));  
  123.         pricetotal2TV.setText("¥"+Arith.mul(goods.discountprice, count));  
  124.     }  
  125.   
  126.     /** 
  127.      * 减少数量 
  128.      * @param v 
  129.      */  
  130.     @OnClick(R.id.product_ordsubmit_count_sub)  
  131.     public void sub(View v) {  
  132.         if (count>1) {  
  133.             count--;  
  134.             countTV1.setText("X"+count);  
  135.             countTV.setText(count+"");  
  136.             intgtotal1TV.setText("共得到"+count*goods.score+"积分");  
  137.             intgtotal2TV.setText("积分:"+count*goods.score);  
  138.             counttotalTV.setText("共"+count+"件");  
  139.             pricetotal1TV.setText("¥"+Arith.mul(goods.discountprice, count));  
  140.             pricetotal2TV.setText("¥"+Arith.mul(goods.discountprice, count));  
  141.         }  
  142.     }  
  143.       
  144.       
  145.     /** 
  146.      * 提交订单 
  147.      * @param v 
  148.      */  
  149.     @OnClick(R.id.product_ordsubmit_ok)  
  150.     public void submit(View v) {  
  151.           
  152.         final OrderInfo orderInfo=new OrderInfo();  
  153.         orderInfo.userid=13752;  
  154.         orderInfo.areacode=23;  
  155.         orderInfo.buildno="10";  
  156.         orderInfo.roomno="1001";  
  157.         orderInfo.producttypeid=goods.producttypeid;  
  158.         orderInfo.productid=goods.productid;  
  159.         orderInfo.amount=goods.discountprice;//单价  
  160.         orderInfo.account=count;//数量  
  161.         orderInfo.totalamount=Arith.mul(goods.discountprice, count);  
  162.         //double offsetamount;//抵扣金额  
  163.         orderInfo.score=count*goods.score;  
  164.         //int assessitem;//评价项  
  165.         //int assesslevel;//评价级别  
  166.         //String assesscontent;//评价内容  
  167.         //long payid=;//支付编号  
  168.         orderInfo.status=2;//支付状态待付款  
  169.         orderInfo.type=11;//日用品  
  170.         orderInfo.usermemo =sayEt.getText().toString();//业主备注  
  171.         orderInfo.address =adress;  
  172.         orderInfo.productname =goods.productname;//  
  173.         orderInfo.desccontext =goods.productdescription;//  
  174.         orderInfo.outtradeno=System.currentTimeMillis()+""+orderInfo.userid;  
  175.         orderInfo.merchantid=goods.companyid;  
  176.         submitorder(orderInfo);  
  177.     }  
  178.     /** 
  179.      * 订单提交成功,进入付款界面 
  180.      * @param orderInfo  
  181.      * @return 
  182.      */  
  183.     private void submitorder(OrderInfo orderInfo) {  
  184.         Intent intent=new Intent(this, SelectPayTypeActivity.class);  
  185.         intent.putExtra("data", orderInfo);  
  186.         startActivity(intent);  
  187.     }  
  188. }  
[java]  view plain  copy
  1. <span style="white-space:pre">    </span>activty_main.xml  
[java]  view plain  copy
  1. <pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <ScrollView   
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="0dp"  
  10.         android:background="@color/igray"  
  11.         android:layout_weight="1"  
  12.         >  
  13.           
  14.         <LinearLayout   
  15.             android:layout_width="match_parent"  
  16.             android:layout_height="wrap_content"  
  17.             android:orientation="vertical"  
  18.             >  
  19.             <LinearLayout   
  20.                 android:layout_width="match_parent"  
  21.                 android:layout_height="wrap_content"  
  22.                 android:paddingLeft="15dp"  
  23.                 android:paddingRight="15dp"  
  24.                 android:paddingTop="10dp"  
  25.                 android:paddingBottom="10dp"  
  26.                 android:orientation="vertical"  
  27.                 android:background="@color/white"  
  28.                 >  
  29.                   
  30.                 <LinearLayout   
  31.                     android:layout_width="match_parent"  
  32.                     android:layout_height="wrap_content"  
  33.                     android:orientation="horizontal"  
  34.                     >  
  35.                    <TextView   
  36.                        android:id="@+id/product_ordsubmit_username"  
  37.                        android:layout_width="0dp"  
  38.                        android:layout_height="wrap_content"  
  39.                        android:layout_weight="1"  
  40.                        android:textSize="14sp"  
  41.                        android:gravity="center_vertical"  
  42.                        android:textColor="@color/black"  
  43.                        android:text="收货人:"  
  44.                        />   
  45.                     <TextView   
  46.                         android:id="@+id/product_ordsubmit_phone"  
  47.                         android:layout_width="0dp"  
  48.                        android:layout_height="wrap_content"  
  49.                        android:layout_weight="1"  
  50.                        android:textSize="14sp"  
  51.                        android:gravity="center_vertical|right"  
  52.                        android:textColor="@color/igray_et"  
  53.                        android:text="13862325641"  
  54.                        />   
  55.                 </LinearLayout>  
  56.                 <LinearLayout   
  57.                     android:layout_width="match_parent"  
  58.                     android:layout_height="wrap_content"  
  59.                     android:orientation="vertical"  
  60.                     >  
  61.                     <TextView android:layout_width="match_parent"  
  62.                        android:layout_height="wrap_content"  
  63.                        android:textSize="14sp"  
  64.                        android:gravity="center_vertical"  
  65.                        android:textColor="@color/igray_et"  
  66.                        android:text="收货地址:"  
  67.                        />   
  68.                     <TextView   
  69.                        android:id="@+id/product_ordsubmit_adress"  
  70.                        android:layout_width="match_parent"  
  71.                        android:layout_height="wrap_content"  
  72.                        android:textSize="14sp"  
  73.                        android:textColor="@color/igray_et"  
  74.                        android:drawableRight="@drawable/next"  
  75.                        android:text="上海市徐汇区浦北路中星城15号"  
  76.                        />   
  77.                       
  78.                 </LinearLayout>  
  79.                   
  80.             </LinearLayout>  
  81.             <View android:layout_width="match_parent"  
  82.                     android:layout_height="5dp"  
  83.                     android:background="@color/igray"/>  
  84.                 <LinearLayout   
  85.                     android:layout_width="match_parent"  
  86.                     android:layout_height="wrap_content"  
  87.                     android:background="@color/white"  
  88.                     android:paddingLeft="15dp"  
  89.                     android:paddingRight="15dp"  
  90.                     android:orientation="vertical"  
  91.                     >  
  92.   
  93.                       
  94.   
  95.                     <LinearLayout   
  96.                         android:layout_width="match_parent"  
  97.                         android:layout_height="wrap_content"  
  98.                         android:orientation="horizontal"  
  99.                         >  
  100.                         <ImageView  
  101.                         android:id="@+id/product_ordsubmit_img"     
  102.                         android:layout_width="100dp"  
  103.                         android:layout_height="100dp"  
  104.                         android:scaleType="centerCrop"  
  105.                         android:src="@drawable/user_head" />  
  106.                         <LinearLayout   
  107.                             android:layout_width="match_parent"  
  108.                             android:layout_height="match_parent"  
  109.                             android:orientation="vertical"  
  110.                             >  
  111.                             <TextView   
  112.                                 android:id="@+id/product_ordsubmit_desc"  
  113.                                 android:layout_width="match_parent"  
  114.                                 android:layout_height="0dp"  
  115.                                 android:layout_weight="1"  
  116.                                 android:textSize="14sp"  
  117.                                 android:text="商品描述"  
  118.                                 android:layout_margin="10dp"  
  119.                                 android:textColor="@color/black"/>  
  120.                                 <LinearLayout   
  121.                                     android:layout_width="match_parent"  
  122.                                     android:layout_height="wrap_content"  
  123.                                     android:orientation="horizontal"  
  124.                                     >  
  125.                                     <TextView   
  126.                                         android:id="@+id/product_ordsubmit_price"  
  127.                                         android:layout_width="wrap_content"  
  128.                                         android:layout_height="wrap_content"  
  129.                                         android:text="¥49"  
  130.                                         android:textSize="18sp"  
  131.                                         android:textColor="@color/Orange"  
  132.                                         android:layout_margin="5dp"  
  133.                                         />  
  134.                                      
  135.                                     <TextView   
  136.                                          android:id="@+id/product_ordsubmit_intg"  
  137.                                         android:layout_width="wrap_content"  
  138.                                         android:layout_height="wrap_content"  
  139.                                         android:text="积分:2"  
  140.                                         android:textSize="14sp"  
  141.                                         android:layout_margin="5dp"  
  142.                                         android:textColor="@color/igray_et"  
  143.                                         />  
  144.                                      <View android:layout_width="0dp"  
  145.                                         android:layout_height="0dp"  
  146.                                         android:layout_weight="1"/>  
  147.                                     <TextView   
  148.                                         android:id="@+id/product_ordsubmit_count1"  
  149.                                         android:layout_width="wrap_content"  
  150.                                         android:layout_height="wrap_content"  
  151.                                         android:text="X2"  
  152.                                         android:textSize="14sp"  
  153.                                         android:layout_margin="5dp"  
  154.                                         android:textColor="@color/igray_et"  
  155.                                         />  
  156.                                 </LinearLayout>  
  157.                               
  158.                         </LinearLayout>  
  159.                           
  160.                     </LinearLayout>  
  161.                     <LinearLayout   
  162.                             android:layout_width="match_parent"  
  163.                             android:layout_height="wrap_content"  
  164.                             android:orientation="horizontal"  
  165.                             android:paddingTop="5dp"  
  166.                             android:gravity="center_vertical"  
  167.                             android:paddingBottom="5dp"  
  168.                             >  
  169.                             <TextView android:layout_width="wrap_content"  
  170.                                 android:layout_height="wrap_content"  
  171.                                 android:text="购买数量"  
  172.                                 android:textColor="@color/black"  
  173.                                 android:textSize="14sp"  
  174.                                   
  175.                                 />  
  176.                             <View android:layout_width="0dp"  
  177.                                 android:layout_height="match_parent"  
  178.                                 android:layout_weight="1"/>  
  179.                             <ImageView   
  180.                                 android:id="@+id/product_ordsubmit_count_sub"  
  181.                                 android:layout_width="25dp"  
  182.                                 android:layout_height="25dp"  
  183.                                 android:src="@drawable/sub_orange"/>  
  184.                             <TextView  
  185.                                 android:id="@+id/product_ordsubmit_count"  
  186.                                 android:layout_width="wrap_content"  
  187.                                 android:layout_height="wrap_content"  
  188.                                 android:text="3"  
  189.                                 android:textColor="@color/black"  
  190.                                 android:layout_marginLeft="10dp"  
  191.                                 android:layout_marginRight="10dp"  
  192.                                 android:textSize="18sp"  
  193.                                   
  194.                                 />  
  195.                               
  196.                             <ImageView   
  197.                                 android:id="@+id/product_ordsubmit_count_add"  
  198.                                 android:layout_width="25dp"  
  199.                                 android:layout_height="25dp"  
  200.                                 android:src="@drawable/add_orange"/>  
  201.                      </LinearLayout>  
  202.                      <LinearLayout   
  203.                             android:layout_width="match_parent"  
  204.                             android:layout_height="wrap_content"  
  205.                             android:orientation="horizontal"  
  206.                             android:paddingTop="5dp"  
  207.                             android:focusableInTouchMode="true"  
  208.                             android:gravity="center_vertical"  
  209.                             android:paddingBottom="5dp"  
  210.                             >  
  211.                             <TextView android:layout_width="wrap_content"  
  212.                                 android:layout_height="wrap_content"  
  213.                                 android:text="业主留言:"  
  214.                                 android:textColor="@color/black"  
  215.                                 android:textSize="14sp"  
  216.                                   
  217.                                 />  
  218.                              
  219.                             <EditText   
  220.                                 android:id="@+id/product_ordsubmit_say_et"  
  221.                                 android:layout_width="wrap_content"  
  222.                                 android:layout_height="wrap_content"  
  223.                                 android:hint="选填,可以填你对卖家一致达成的要求"  
  224.                                 android:textColor="@color/igray_et"  
  225.                                 android:layout_marginLeft="10dp"  
  226.                                 android:singleLine="true"  
  227.                                   
  228.                                 android:layout_marginRight="10dp"  
  229.                                 android:textSize="14sp"  
  230.                                   
  231.                                 />  
  232.                               
  233.                      </LinearLayout>  
  234.                      <LinearLayout   
  235.                             android:layout_width="match_parent"  
  236.                             android:layout_height="wrap_content"  
  237.                             android:orientation="horizontal"  
  238.                             android:paddingTop="5dp"  
  239.                             android:gravity="center_vertical"  
  240.                             android:paddingBottom="5dp"  
  241.                             >  
  242.                             <TextView   
  243.                                 android:id="@+id/product_ordsubmit_intgtotal1"  
  244.                                 android:layout_width="wrap_content"  
  245.                                 android:layout_height="wrap_content"  
  246.                                 android:text="共得到6积分"  
  247.                                 android:textColor="@color/igray_et"  
  248.                                 android:textSize="14sp"  
  249.                                   
  250.                                 />  
  251.                            <View android:layout_width="0dp"  
  252.                                 android:layout_height="match_parent"  
  253.                                 android:layout_weight="1"/>  
  254.                             <TextView   
  255.                                 android:id="@+id/product_ordsubmit_counttotal"  
  256.                                 android:layout_width="wrap_content"  
  257.                                 android:layout_height="wrap_content"  
  258.                                 android:textSize="14sp"  
  259.                                 android:textColor="@color/black"  
  260.                                 android:text="共3件"/>  
  261.                             <TextView android:layout_width="wrap_content"  
  262.                                 android:layout_height="wrap_content"  
  263.                                 android:text="合计:"  
  264.                                 android:textColor="@color/black"  
  265.                                 android:layout_marginLeft="10dp"  
  266.                                 android:textSize="14sp"  
  267.                                   
  268.                                 />  
  269.                             <TextView   
  270.                                 android:id="@+id/product_ordsubmit_pricetotal1"  
  271.                                 android:layout_width="wrap_content"  
  272.                                 android:layout_height="wrap_content"  
  273.                                 android:textSize="18sp"  
  274.                                 android:textColor="@color/Orange"  
  275.                                 android:text="¥127"/>  
  276.                               
  277.                      </LinearLayout>  
  278.                 </LinearLayout>  
  279.                   
  280.         </LinearLayout>  
  281.     </ScrollView>  
  282.     <LinearLayout   
  283.         android:layout_width="match_parent"  
  284.         android:layout_height="44dp"  
  285.         android:paddingLeft="15dp"  
  286.         android:paddingRight="15dp"  
  287.         android:paddingTop="5dp"  
  288.         android:paddingBottom="5dp"  
  289.         android:gravity="right|center_vertical"  
  290.         android:background="@color/white">  
  291.            
  292.                 <TextView android:layout_width="wrap_content"  
  293.                     android:layout_height="wrap_content"  
  294.                     android:text="合计:"  
  295.                     android:textColor="@color/black"  
  296.                       
  297.                     android:textSize="14sp"  
  298.                       
  299.                     />  
  300.                 <TextView   
  301.                     android:id="@+id/product_ordsubmit_pricetotal2"  
  302.                     android:layout_width="wrap_content"  
  303.                     android:layout_height="wrap_content"  
  304.                     android:textSize="14sp"  
  305.                     android:textColor="@color/Orange"  
  306.                     android:text="¥127"/>  
  307.                 <TextView   
  308.                     android:id="@+id/product_ordsubmit_intgtotal2"  
  309.                     android:layout_width="wrap_content"  
  310.                     android:layout_height="wrap_content"  
  311.                     android:text="积分:6"  
  312.                     android:textColor="@color/igray_et"  
  313.                     android:layout_marginLeft="10dp"  
  314.                     android:layout_marginRight="10dp"  
  315.                     android:textSize="12sp"  
  316.                       
  317.                     />  
  318.                 <Button   
  319.                     android:id="@+id/product_ordsubmit_ok"  
  320.                     android:layout_width="wrap_content"  
  321.                     android:layout_height="wrap_content"  
  322.                     android:background="@drawable/shape_btn_oval_orange_bg2"  
  323.                     android:text="确认"/>  
  324.           
  325.     </LinearLayout>  
  326.       
  327. </LinearLayout>  

2.在mainactivty中点击确认按钮调用支付方式选择页面SelectPayTypeActivity,用来发起支付选择

选择支付方式
[java]  view plain  copy
  1. SelectPayTypeActivity.java  
[java]  view plain  copy
  1. <pre name="code" class="java">@ContentView(R.layout.activity_select_pay_type)  
  2. public class SelectPayTypeActivity extends Activity {  
  3.   
  4.     @ViewInject(R.id.paytype_of_weixin_ck)  
  5.     private CheckBox weixinCK;  
  6.       
  7.     @ViewInject(R.id.paytype_of_zhifubao_ck)  
  8.     private CheckBox zhifubaoCK;  
  9.   
  10.       
  11.     @ViewInject(R.id.last_pay_count_tv)  
  12.     private TextView payCountTv;  
  13.   
  14.   
  15.     private OrderInfo orderInfo;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         ViewUtils.inject(this);  
  21.         initData();  
  22.         initView();  
  23.     }  
  24.   
  25.     private void initView() {  
  26.         payCountTv.setText("¥"+orderInfo.totalamount);  
  27.           
  28.     }  
  29.   
  30.     private void initData() {  
  31.         orderInfo=(OrderInfo) getIntent().getSerializableExtra("data");  
  32.           
  33.     }  
  34.     @Override  
  35.     protected void onNewIntent(Intent intent) {  
  36.         super.onNewIntent(intent);  
  37.         int code=intent.getIntExtra("result"1);  
  38.         switch (code) {  
  39.         case 0://表示成功  
  40.             finish();  
  41.             break;  
  42.         case -1://表示失败  
  43.             finish();         
  44.             break;  
  45.         case -2:表示取消  
  46.             finish();  
  47.             break;  
  48.         case 1://未知不做处理  
  49.               
  50.             break;  
  51.   
  52.         default:  
  53.             break;  
  54.         }  
  55.     }  
  56.       
  57.       
  58.     @OnClick(R.id.paytype_of_weixin)  
  59.     public void wx(View v) {  
  60.         if (zhifubaoCK.isChecked()) {  
  61.             zhifubaoCK.setChecked(false);  
  62.         }  
  63.         if (!weixinCK.isChecked()) {  
  64.             weixinCK.setChecked(true);  
  65.         }  
  66.           
  67.     }  
  68.       
  69.     @OnClick(R.id.paytype_of_zhifubao)  
  70.     public void zfb(View v) {  
  71.         if (weixinCK.isChecked()) {  
  72.             weixinCK.setChecked(false);  
  73.         }  
  74.         if (!zhifubaoCK.isChecked()) {  
  75.             zhifubaoCK.setChecked(true);  
  76.         }  
  77.           
  78.           
  79.     }  
  80.       
  81.     @OnClick(R.id.paytype_of_weixin_ck)  
  82.     public void wxck(View v) {  
  83.         if (zhifubaoCK.isChecked()) {  
  84.             zhifubaoCK.setChecked(false);  
  85.         }  
  86.         if (!weixinCK.isChecked()) {  
  87.             weixinCK.setChecked(true);  
  88.         }  
  89.     }  
  90.       
  91.     @OnClick(R.id.paytype_of_zhifubao_ck)  
  92.     public void zfbck(View v) {  
  93.         if (weixinCK.isChecked()) {  
  94.             weixinCK.setChecked(false);  
  95.         }  
  96.         if (!zhifubaoCK.isChecked()) {  
  97.             zhifubaoCK.setChecked(true);  
  98.         }  
  99.     }  
  100.       
  101.     @OnClick(R.id.btn_pay_submit)  
  102.     public void paysubmit(View v) {  
  103.           
  104.         if (weixinCK.isChecked()) {  
  105.               
  106.             if (!isWeixinAvilible(this)) {  
  107.                 Toast.makeText(this"请先安装微信或者选择其他支付方式",0).show();  
  108.                 return;  
  109.             }  
  110.             //微信支付  
  111.             payByWX(handler,orderInfo);  
  112.         }else{  
  113.             if (!isZfbAvilible(this)) {  
  114.                 Toast.makeText(this"请先安支付宝或者选择其他支付方式",0).show();  
  115.                 return;  
  116.             }  
  117.             //支付宝支付  
  118.             payByzfb(handler,orderInfo);  
  119.         }  
  120.           
  121.     }  
  122.       
  123.       
  124.       
  125.     Handler handler=new Handler(){  
  126.         @Override  
  127.         public void handleMessage(Message msg) {  
  128.               
  129.             switch (msg.what) {  
  130.               
  131.             case 9000://支付宝支付成功  
  132.                 Intent it;  
  133.                 finish();  
  134.                 break;  
  135.             case 8000://支付宝支付失败  
  136.                 finish();  
  137.                 break;  
  138.             default:  
  139.                 break;  
  140.             }  
  141.         }  
  142.     };  
  143.       
  144.     /** 
  145.      * 调用支付宝支付 
  146.      * @param handler 
  147.      * @param order  
  148.      */  
  149.     private void payByzfb(Handler handler, OrderInfo order) {  
  150.         AlipayUtil alipay=new AlipayUtil(this,order,handler);  
  151.     }  
  152.   
  153.     /** 
  154.      * 调用微信支付 
  155.      * @param handler 
  156.      * @param orderInfo2  
  157.      */  
  158.     private void payByWX(Handler handler, OrderInfo order) {  
  159.         WXpayUtil wxpay=new WXpayUtil(this,order);  
  160.     }  
  161.       
  162.       
  163.       
  164.     /** 
  165.      * 检查微信是否存在 
  166.      * @param context 
  167.      * @return 
  168.      */  
  169.     public  boolean isWeixinAvilible(Context context) {  
  170.         PackageManager packageManager = context.getPackageManager();// 获取packagemanager  
  171.         List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息  
  172.         if (pinfo != null) {  
  173.             for (int i = 0; i < pinfo.size(); i++) {  
  174.                 String pn = pinfo.get(i).packageName;  
  175.                 System.out.println(pinfo.get(i).packageName);  
  176.                 if (pn.equals("com.tencent.mm")) {  
  177.                     return true;  
  178.                 }  
  179.             }  
  180.         }  
  181.   
  182.         return false;  
  183.     }  
  184.     /** 
  185.      * 检查支付包是否存在 
  186.      * @param context 
  187.      * @return 
  188.      */  
  189.     private boolean isZfbAvilible(Context context) {  
  190.         PackageManager packageManager = context.getPackageManager();// 获取packagemanager  
  191.         List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息  
  192.         if (pinfo != null) {  
  193.             for (int i = 0; i < pinfo.size(); i++) {  
  194.                 String pn = pinfo.get(i).packageName;  
  195.                 System.out.println(pinfo.get(i).packageName);  
  196.                 if (pn.equals("com.alipay.android.app")) {  
  197.                     return true;  
  198.                 }  
  199.             }  
  200.         }  
  201.         return false;  
  202.     }  
  203. }  
activty_selecte_pay_type.xml
 
 
[java]  view plain  copy
  1. <pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@color/white"  
  6.     android:orientation="vertical" >  
  7.     <LinearLayout   
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:orientation="horizontal"  
  11.         android:padding="10dp"  
  12.         android:gravity="center_vertical"  
  13.         >  
  14.         <TextView   
  15.             android:layout_width="wrap_content"  
  16.             android:layout_height="wrap_content"  
  17.             android:layout_marginLeft="10dp"  
  18.             android:textSize="18sp"  
  19.             android:textColor="@color/black"  
  20.             android:text="需支付:"/>  
  21.          <TextView   
  22.                
  23.             android:id="@+id/last_pay_count_tv"  
  24.             android:layout_width="match_parent"  
  25.             android:layout_height="wrap_content"  
  26.             android:layout_marginLeft="10dp"  
  27.             android:textSize="22sp"  
  28.             android:textColor="@color/Orange"  
  29.             android:text="¥152"/>  
  30.     </LinearLayout>  
  31.     <View android:layout_width="match_parent"  
  32.         android:layout_height="5dp"  
  33.         android:background="@color/igray"/>  
  34.    <LinearLayout   
  35.        android:layout_width="match_parent"  
  36.        android:layout_height="match_parent"  
  37.        android:orientation="vertical"  
  38.        android:paddingLeft="10dp"  
  39.        android:paddingRight="10dp"  
  40.        android:paddingBottom="10dp"  
  41.        >  
  42.        <LinearLayout   
  43.             android:id="@+id/paytype_of_weixin"   
  44.            android:layout_width="match_parent"  
  45.            android:layout_height="wrap_content"  
  46.            android:padding="10dp"  
  47.            android:orientation="horizontal"  
  48.            android:gravity="center_vertical"  
  49.            >  
  50.            <ImageView android:layout_width="44dp"  
  51.                android:layout_height="44dp"  
  52.                android:src="@drawable/icon64_wx"/>  
  53.            <TextView android:layout_width="wrap_content"  
  54.                android:layout_height="wrap_content"  
  55.                android:text="微信支付"  
  56.                android:layout_marginLeft="10dp"  
  57.                android:layout_marginRight="10dp"  
  58.                android:textSize="20sp"  
  59.                />  
  60.            <View android:layout_width="0dp"  
  61.                android:layout_height="match_parent"  
  62.                android:layout_weight="1"/>  
  63.            <CheckBox   
  64.                android:id="@+id/paytype_of_weixin_ck"   
  65.                android:layout_width="wrap_content"  
  66.                android:checked="true"  
  67.                android:layout_height="wrap_content"  
  68.                android:focusable="false"  
  69.                />  
  70.        </LinearLayout>  
  71.        <View  
  72.             android:layout_width="match_parent"  
  73.            android:layout_height="1dp"  
  74.            android:background="@color/igray"/>  
  75.         <LinearLayout   
  76.            android:id="@+id/paytype_of_zhifubao"    
  77.             android:layout_width="match_parent"  
  78.            android:layout_height="wrap_content"  
  79.            android:padding="10dp"  
  80.            android:orientation="horizontal"  
  81.            android:gravity="center_vertical"  
  82.            >  
  83.            <ImageView android:layout_width="44dp"  
  84.                android:layout_height="44dp"  
  85.                android:src="@drawable/zfb_icon_120"/>  
  86.            <TextView android:layout_width="wrap_content"  
  87.                android:layout_height="wrap_content"  
  88.                android:text="支付宝"  
  89.                android:layout_marginLeft="10dp"  
  90.                android:layout_marginRight="10dp"  
  91.                android:textSize="20sp"  
  92.                />  
  93.            <View android:layout_width="0dp"  
  94.                 
  95.                android:layout_height="match_parent"  
  96.                android:layout_weight="1"/>  
  97.            <CheckBox   
  98.                android:id="@+id/paytype_of_zhifubao_ck"    
  99.                android:layout_width="wrap_content"  
  100.                android:layout_height="wrap_content"  
  101.                android:focusable="false"  
  102.                />  
  103.        </LinearLayout>  
  104.        <View android:layout_width="match_parent"  
  105.            android:layout_height="1dp"  
  106.            android:background="@color/igray"/>  
  107.          
  108.        <RelativeLayout android:layout_width="match_parent"  
  109.            android:layout_height="match_parent"  
  110.            >  
  111.            <Button   
  112.                  
  113.                android:id="@+id/btn_pay_submit"    
  114.                android:layout_width="match_parent"  
  115.                android:layout_height="40dp"  
  116.                android:text="支付"  
  117.                android:textColor="@color/white"  
  118.                android:layout_marginBottom="10dp"  
  119.                android:layout_marginLeft="40dp"  
  120.                android:layout_marginRight="40dp"  
  121.                android:layout_alignParentBottom="true"  
  122.                android:background="@drawable/shape_btn_oval_orange_bg2"  
  123.                />  
  124.              
  125.              
  126.        </RelativeLayout>  
  127.    </LinearLayout>  
  128.      
  129. </LinearLayout>  

3.根据支付方式调用对应工具类微信(WXpayUtil),支付宝(AlipayUtil)

 
 
 WXpayUtil.java 
[java]  view plain  copy
  1. public class WXpayUtil {  
  2.     private IWXAPI api;  
  3.     private OrderInfo order;  
  4.     private Context context;  
  5.     private PayReq req;  
  6.     private Map<String,String> resultunifiedorder;  
  7.     private static final String TAG = "ewuye.online.SelectPayTypeActivity";  
  8.   
  9.     public WXpayUtil(Context mcontext,OrderInfo order){  
  10.         //初始化微信支付  
  11.         this.order=order;  
  12.         this.context=mcontext;  
  13.         if (TextUtils.isEmpty(ParameterConfig.WX_APP_ID) || TextUtils.isEmpty(ParameterConfig.WX_MCH_ID) || TextUtils.isEmpty(ParameterConfig.WX_API_KEY)) {  
  14.             new AlertDialog.Builder(context).setTitle("警告").setMessage("需要配置WX_APP_ID | WX_MCH_ID| WX_API_KEY\n请到ParameterConfig.java里配置")  
  15.                     .setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  16.                         public void onClick(DialogInterface dialoginterface, int i) {  
  17.                             //  
  18.                             ((Activity)context).finish();  
  19.                         }  
  20.                     }).show();  
  21.             return;  
  22.         }  
  23.           
  24.         api = WXAPIFactory.createWXAPI(context, null);  
  25.         req = new PayReq();  
  26.         //生成prepay_id  
  27.         GetPrepayIdTask getPrepayId = new GetPrepayIdTask();  
  28.         getPrepayId.execute();  
  29.     }  
  30.       
  31.     /** 
  32.      * 用于获取 
  33.      * @author 95 
  34.      * 
  35.      */  
  36.     private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String,String>> {  
  37.   
  38.         private ProgressDialog dialog;  
  39.   
  40.   
  41.         @Override  
  42.         protected void onPreExecute() {  
  43.             dialog = ProgressDialog.show(context, "提示""正在获取预支付订单...");  
  44.         }  
  45.   
  46.         @Override  
  47.         protected void onPostExecute(Map<String,String> result) {  
  48.             if (dialog != null) {  
  49.                 dialog.dismiss();  
  50.             }  
  51.             resultunifiedorder=result;  
  52.             genPayReq();  
  53.               
  54.         }  
  55.   
  56.         @Override  
  57.         protected void onCancelled() {  
  58.             super.onCancelled();  
  59.         }  
  60.   
  61.         @Override  
  62.         protected Map<String,String>  doInBackground(Void... params) {  
  63.   
  64.             String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");  
  65.             String entity = genProductArgs();  
  66.   
  67.             Log.e("orion",entity);  
  68.   
  69.             byte[] buf = httpPost(url, entity);  
  70.   
  71.             String content = new String(buf);  
  72.             Log.e("orion", content);  
  73.             Map<String,String> xml=decodeXml(content);  
  74.   
  75.             return xml;  
  76.         }  
  77.     }  
  78.       
  79.       
  80.     private void genPayReq() {  
  81.   
  82.         req.appId = ParameterConfig.WX_APP_ID;  
  83.         req.partnerId = ParameterConfig.WX_MCH_ID;  
  84.         req.prepayId = resultunifiedorder.get("prepay_id");  
  85.         req.packageValue = "prepay_id="+resultunifiedorder.get("prepay_id");  
  86.         req.nonceStr = genNonceStr();  
  87.         req.timeStamp = String.valueOf(genTimeStamp());  
  88.   
  89.   
  90.         List<NameValuePair> signParams = new LinkedList<NameValuePair>();  
  91.         signParams.add(new BasicNameValuePair("appid", req.appId));  
  92.         signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));  
  93.         signParams.add(new BasicNameValuePair("package", req.packageValue));  
  94.         signParams.add(new BasicNameValuePair("partnerid", req.partnerId));  
  95.         signParams.add(new BasicNameValuePair("prepayid", req.prepayId));  
  96.         signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));  
  97.           
  98.         req.sign = genAppSign(signParams);  
  99.         Log.e("orion", signParams.toString());  
  100.         sendPayReq();  
  101.     }  
  102.     private void sendPayReq() {  
  103.         api.registerApp(ParameterConfig.WX_APP_ID);  
  104.         api.sendReq(req);  
  105.           
  106.     }  
  107.       
  108.     private String genProductArgs() {  
  109.         StringBuffer xml = new StringBuffer();  
  110.   
  111.         try {  
  112.             String  nonceStr = genNonceStr();  
  113.             xml.append("</xml>");  
  114.            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();  
  115.             packageParams.add(new BasicNameValuePair("appid", ParameterConfig.WX_APP_ID));  
  116.             packageParams.add(new BasicNameValuePair("body", order.productname));  
  117.             packageParams.add(new BasicNameValuePair("mch_id", ParameterConfig.WX_MCH_ID));  
  118.             packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));  
  119.             packageParams.add(new BasicNameValuePair("notify_url", ParameterConfig.WX_notifyUrl));  
  120.             packageParams.add(new BasicNameValuePair("out_trade_no",genOutTradNo()));  
  121.             packageParams.add(new BasicNameValuePair("spbill_create_ip","127.0.0.1"));  
  122.             packageParams.add(new BasicNameValuePair("total_fee", (int)(order.totalamount*100)+""));  
  123.             packageParams.add(new BasicNameValuePair("trade_type""APP"));  
  124.   
  125.   
  126.             String sign = genPackageSign(packageParams);  
  127.             packageParams.add(new BasicNameValuePair("sign", sign));  
  128.               
  129.               
  130.   
  131.            String xmlstring =toXml(packageParams);  
  132.            return new String(xmlstring.toString().getBytes(), "ISO8859-1");  
  133.             //return xmlstring;  
  134.   
  135.         } catch (Exception e) {  
  136.             Log.e(TAG, "genProductArgs fail, ex = " + e.getMessage());  
  137.             return null;  
  138.         }  
  139.           
  140.   
  141.     }  
  142.       
  143.     private String genAppSign(List<NameValuePair> params) {  
  144.         StringBuilder sb = new StringBuilder();  
  145.   
  146.         for (int i = 0; i < params.size(); i++) {  
  147.             sb.append(params.get(i).getName());  
  148.             sb.append('=');  
  149.             sb.append(params.get(i).getValue());  
  150.             sb.append('&');  
  151.         }  
  152.         sb.append("key=");  
  153.         sb.append(ParameterConfig.WX_API_KEY);  
  154.   
  155.           
  156.         String appSign = getMessageDigest(sb.toString().getBytes());  
  157.         Log.e("orion",appSign);  
  158.         return appSign;  
  159.     }  
  160.       
  161.       
  162.     private  HttpClient getNewHttpClient() {   
  163.            try {   
  164.                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());   
  165.                trustStore.load(nullnull);   
  166.   
  167.                SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);   
  168.                sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);   
  169.   
  170.                HttpParams params = new BasicHttpParams();   
  171.                HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);   
  172.                HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);   
  173.   
  174.                SchemeRegistry registry = new SchemeRegistry();   
  175.                registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));   
  176.                registry.register(new Scheme("https", sf, 443));   
  177.   
  178.                ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);   
  179.   
  180.                return new DefaultHttpClient(ccm, params);   
  181.            } catch (Exception e) {   
  182.                return new DefaultHttpClient();   
  183.            }   
  184.         }  
  185.     private class SSLSocketFactoryEx extends SSLSocketFactory {        
  186.             
  187.         SSLContext sslContext = SSLContext.getInstance("TLS");        
  188.             
  189.         public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {        
  190.             super(truststore);        
  191.             
  192.             TrustManager tm = new X509TrustManager() {        
  193.             
  194.                 public X509Certificate[] getAcceptedIssuers() {        
  195.                     return null;        
  196.                 }        
  197.             
  198.                 @Override  
  199.                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {  
  200.                 }  
  201.   
  202.                 @Override  
  203.                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {  
  204.                 }    
  205.             };        
  206.             
  207.             sslContext.init(nullnew TrustManager[] { tm }, null);        
  208.         }        
  209.             
  210.         @Override  
  211.         public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {  
  212.             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);  
  213.         }  
  214.   
  215.         @Override  
  216.         public Socket createSocket() throws IOException {  
  217.             return sslContext.getSocketFactory().createSocket();  
  218.         }   
  219.     }    
  220.     public  byte[] httpPost(String url, String entity) {  
  221.         if (url == null || url.length() == 0) {  
  222.             Log.e(TAG, "httpPost, url is null");  
  223.             return null;  
  224.         }  
  225.           
  226.         HttpClient httpClient = getNewHttpClient();  
  227.         HttpPost httpPost = new HttpPost(url);  
  228.           
  229.         try {  
  230.             httpPost.setEntity(new StringEntity(entity));  
  231.             httpPost.setHeader("Accept""application/json");  
  232.             httpPost.setHeader("Content-type""application/json");  
  233.               
  234.             HttpResponse resp = httpClient.execute(httpPost);  
  235.             if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {  
  236.                 Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());  
  237.                 return null;  
  238.             }  
  239.   
  240.             return EntityUtils.toByteArray(resp.getEntity());  
  241.         } catch (Exception e) {  
  242.             Log.e(TAG, "httpPost exception, e = " + e.getMessage());  
  243.             e.printStackTrace();  
  244.             return null;  
  245.         }  
  246.     }  
  247.       
  248.     private String genOutTradNo() {  
  249.         Random random = new Random();  
  250.         return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());  
  251.     }  
  252.       
  253.     public Map<String,String> decodeXml(String content) {  
  254.   
  255.         try {  
  256.             Map<String, String> xml = new HashMap<String, String>();  
  257.             XmlPullParser parser = Xml.newPullParser();  
  258.             parser.setInput(new StringReader(content));  
  259.             int event = parser.getEventType();  
  260.             while (event != XmlPullParser.END_DOCUMENT) {  
  261.   
  262.                 String nodeName=parser.getName();  
  263.                 switch (event) {  
  264.                     case XmlPullParser.START_DOCUMENT:  
  265.   
  266.                         break;  
  267.                     case XmlPullParser.START_TAG:  
  268.   
  269.                         if("xml".equals(nodeName)==false){  
  270.                             //实例化student对象  
  271.                             xml.put(nodeName,parser.nextText());  
  272.                         }  
  273.                         break;  
  274.                     case XmlPullParser.END_TAG:  
  275.                         break;  
  276.                 }  
  277.                 event = parser.next();  
  278.             }  
  279.   
  280.             return xml;  
  281.         } catch (Exception e) {  
  282.             Log.e("orion",e.toString());  
  283.         }  
  284.         return null;  
  285.   
  286.     }  
  287.   
  288.     private String genNonceStr() {  
  289.         Random random = new Random();  
  290.         return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());  
  291.     }  
  292.       
  293.     private long genTimeStamp() {  
  294.         return System.currentTimeMillis() / 1000;  
  295.     }  
  296.       
  297.     public  String getMessageDigest(byte[] buffer) {  
  298.         char hexDigits[] = { '0''1''2''3''4''5''6''7''8''9''a''b''c''d''e''f' };  
  299.         try {  
  300.             MessageDigest mdTemp = MessageDigest.getInstance("MD5");  
  301.             mdTemp.update(buffer);  
  302.             byte[] md = mdTemp.digest();  
  303.             int j = md.length;  
  304.             char str[] = new char[j * 2];  
  305.             int k = 0;  
  306.             for (int i = 0; i < j; i++) {  
  307.                 byte byte0 = md[i];  
  308.                 str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
  309.                 str[k++] = hexDigits[byte0 & 0xf];  
  310.             }  
  311.             return new String(str);  
  312.         } catch (Exception e) {  
  313.             return null;  
  314.         }  
  315.     }  
  316.       
  317.     /** 
  318.      生成签名 
  319.      */  
  320.   
  321.     private String genPackageSign(List<NameValuePair> params) {  
  322.         StringBuilder sb = new StringBuilder();  
  323.           
  324.         for (int i = 0; i < params.size(); i++) {  
  325.             sb.append(params.get(i).getName());  
  326.             sb.append('=');  
  327.             sb.append(params.get(i).getValue());  
  328.             sb.append('&');  
  329.         }  
  330.         sb.append("key=");  
  331.         sb.append(ParameterConfig.WX_API_KEY);  
  332.           
  333.   
  334.         String packageSign = getMessageDigest(sb.toString().getBytes()).toUpperCase();  
  335.         Log.e("orion",packageSign);  
  336.         return packageSign;  
  337.     }  
  338.       
  339.     private String toXml(List<NameValuePair> params) {  
  340.         StringBuilder sb = new StringBuilder();  
  341.         sb.append("<xml>");  
  342.         for (int i = 0; i < params.size(); i++) {  
  343.             sb.append("<"+params.get(i).getName()+">");  
  344.   
  345.   
  346.             sb.append(params.get(i).getValue());  
  347.             sb.append("</"+params.get(i).getName()+">");  
  348.         }  
  349.         sb.append("</xml>");  
  350.   
  351.         Log.e("orion",sb.toString());  
  352.         return sb.toString();  
  353.     }  
  354. }  
AlipayUtil.java
[java]  view plain  copy
  1. public class AlipayUtil {  
  2.   
  3.     private Activity context;  
  4.     private OrderInfo order;  
  5.     private Handler mhandler;  
  6.     private static final int SDK_PAY_FLAG = 1;  
  7.       
  8.       
  9.       
  10.     public AlipayUtil(Activity context, OrderInfo order,Handler mhandler) {  
  11.         this.context=context;  
  12.         this.order=order;  
  13.         this.mhandler=mhandler;  
  14.         pay();  
  15.     }  
  16.       
  17.       
  18.     private void pay() {  
  19.         //判断是否注册商户到支付宝  
  20.         if (TextUtils.isEmpty(ParameterConfig.PARTNER) || TextUtils.isEmpty(ParameterConfig.RSA_PRIVATE) || TextUtils.isEmpty(ParameterConfig.SELLER)) {  
  21.             new AlertDialog.Builder(context).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER\n请到ParameterConfig.java里配置")  
  22.                     .setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  23.                         public void onClick(DialogInterface dialoginterface, int i) {  
  24.                             //  
  25.                             ((Activity)context).finish();  
  26.                         }  
  27.                     }).show();  
  28.             return;  
  29.         }  
  30.           
  31.         String orderInfo = getOrderInfo(order);  
  32.           
  33.         /** 
  34.          * 特别注意,这里的签名逻辑需要放在服务端,切勿将私钥泄露在代码中! 
  35.          */  
  36.         String sign = sign(orderInfo);  
  37.         try {  
  38.             /** 
  39.              * 仅需对sign 做URL编码 
  40.              */  
  41.             sign = URLEncoder.encode(sign, "UTF-8");  
  42.         } catch (UnsupportedEncodingException e) {  
  43.             e.printStackTrace();  
  44.         }  
  45.           
  46.         /** 
  47.          * 完整的符合支付宝参数规范的订单信息 
  48.          */  
  49.         final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();  
  50.   
  51.         Runnable payRunnable = new Runnable() {  
  52.   
  53.             @Override  
  54.             public void run() {  
  55.                 // 构造PayTask 对象  
  56.                 PayTask alipay = new PayTask(context);  
  57.                 // 调用支付接口,获取支付结果  
  58.                 String result = alipay.pay(payInfo, true);  
  59.                   
  60.                 Message msg = new Message();  
  61.                 msg.what = SDK_PAY_FLAG;  
  62.                 msg.obj = result;  
  63.                 mHandler.sendMessage(msg);  
  64.             }  
  65.         };  
  66.           
  67.         // 必须异步调用  
  68.         Thread payThread = new Thread(payRunnable);  
  69.         payThread.start();  
  70.     }  
  71.       
  72.     @SuppressLint("HandlerLeak")  
  73.     private Handler mHandler = new Handler() {  
  74.         @SuppressWarnings("unused")  
  75.         public void handleMessage(Message msg) {  
  76.             switch (msg.what) {  
  77.             case SDK_PAY_FLAG: {  
  78.                 PayResult payResult = new PayResult((String) msg.obj);  
  79.                 /** 
  80.                  * 同步返回的结果必须放置到服务端进行验证(验证的规则请看https://doc.open.alipay.com/doc2/ 
  81.                  * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665& 
  82.                  * docType=1) 建议商户依赖异步通知 
  83.                  */  
  84.                 String resultInfo = payResult.getResult();// 同步返回需要验证的信息  
  85.   
  86.                 String resultStatus = payResult.getResultStatus();  
  87.                 // 判断resultStatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档  
  88.                 if (TextUtils.equals(resultStatus, "9000")) {  
  89.                     mhandler.sendEmptyMessage(9000);  
  90.                     //Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();  
  91.                 } else {  
  92.                     // 判断resultStatus 为非"9000"则代表可能支付失败  
  93.                     // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态)  
  94.                     if (TextUtils.equals(resultStatus, "8000")) {  
  95.                         Toast.makeText(context, "支付结果确认中", Toast.LENGTH_SHORT).show();  
  96.   
  97.                     } else {  
  98.                         // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误  
  99.                         Toast.makeText(context, "支付宝支付失败", Toast.LENGTH_SHORT).show();  
  100.   
  101.                     }  
  102.                     mhandler.sendEmptyMessage(8000);  
  103.                 }  
  104.                 break;  
  105.             }  
  106.             default:  
  107.                 break;  
  108.             }  
  109.         };  
  110.     };  
  111.     /** 
  112.      * create the order info. 创建订单信息 
  113.      *  
  114.      */  
  115.     private String getOrderInfo(OrderInfo order) {  
  116.   
  117.         // 签约合作者身份ID  
  118.         String orderInfo = "partner=" + "\"" + ParameterConfig.PARTNER + "\"";  
  119.   
  120.         // 签约卖家支付宝账号  
  121.         orderInfo += "&seller_id=" + "\"" +ParameterConfig.SELLER + "\"";  
  122.   
  123.         // 商户网站唯一订单号  
  124.         orderInfo += "&out_trade_no=" + "\"" + order.outtradeno + "\"";  
  125.   
  126.         // 商品名称  
  127.         orderInfo += "&subject=" + "\"" + order.productname + "\"";  
  128.   
  129.         // 商品详情  
  130.         orderInfo += "&body=" + "\"" + order.desccontext + "\"";  
  131.   
  132.         // 商品金额  
  133.         orderInfo += "&total_fee=" + "\"" +  order.totalamount + "\"";  
  134.   
  135.         // 服务器异步通知页面路径  
  136.         orderInfo += "¬ify_url=" + "\"" + ParameterConfig.aliPay_notifyURL + "\"";  
  137.   
  138.         // 服务接口名称, 固定值  
  139.         orderInfo += "&service=\"mobile.securitypay.pay\"";  
  140.   
  141.         // 支付类型, 固定值  
  142.         orderInfo += "&payment_type=\"1\"";  
  143.   
  144.         // 参数编码, 固定值  
  145.         orderInfo += "&_input_charset=\"utf-8\"";  
  146.   
  147.         // 设置未付款交易的超时时间  
  148.         // 默认30分钟,一旦超时,该笔交易就会自动被关闭。  
  149.         // 取值范围:1m~15d。  
  150.         // m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。  
  151.         // 该参数数值不接受小数点,如1.5h,可转换为90m。  
  152.         orderInfo += "&it_b_pay=\"30m\"";  
  153.   
  154.         // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付  
  155.         // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";  
  156.   
  157.         // 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空  
  158.         orderInfo += "&return_url=\"m.alipay.com\"";  
  159.   
  160.         // 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用)  
  161.         // orderInfo += "&paymethod=\"expressGateway\"";  
  162.   
  163.         return orderInfo;  
  164.     }  
  165.   
  166.       
  167.       
  168.     /** 
  169.      * sign the order info. 对订单信息进行签名 
  170.      *  
  171.      * @param content 
  172.      *            待签名订单信息 
  173.      */  
  174.     private String sign(String content) {  
  175.         return SignUtils.sign(content, ParameterConfig.RSA_PRIVATE);  
  176.     }  
  177.       
  178.     /** 
  179.      * get the sign type we use. 获取签名方式 
  180.      *  
  181.      */  
  182.     private String getSignType() {  
  183.         return "sign_type=\"RSA\"";  
  184.     }  
  185. }  
[java]  view plain  copy
  1. 微信的回调actvity  
WXPayEntryActivity.java

[java]  view plain  copy
  1. package com.gan.mypay.wxapi;  
  2. import com.gan.mypay.ParameterConfig;  
  3. import com.gan.mypay.R;  
  4. import com.gan.mypay.SelectPayTypeActivity;  
  5. import com.tencent.mm.sdk.constants.ConstantsAPI;  
  6. import com.tencent.mm.sdk.modelbase.BaseReq;  
  7. import com.tencent.mm.sdk.modelbase.BaseResp;  
  8. import com.tencent.mm.sdk.openapi.IWXAPI;  
  9. import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;  
  10. import com.tencent.mm.sdk.openapi.WXAPIFactory;  
  11.   
  12. import android.app.Activity;  
  13. import android.app.AlertDialog;  
  14. import android.content.Intent;  
  15. import android.os.Bundle;  
  16. import android.util.Log;  
  17. import android.widget.Toast;  
  18.   
  19. public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{  
  20.       
  21.     private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";  
  22.       
  23.     private IWXAPI api;  
  24.    // private TextView reulttv;  
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.wx_pay_result);  
  29.         api = WXAPIFactory.createWXAPI(this, ParameterConfig.WX_APP_ID);  
  30.         api.handleIntent(getIntent(), this);  
  31.     }  
  32.   
  33.     @Override  
  34.     protected void onNewIntent(Intent intent) {  
  35.         super.onNewIntent(intent);  
  36.         setIntent(intent);  
  37.         api.handleIntent(intent, this);  
  38.     }  
  39.   
  40.     @Override  
  41.     public void onReq(BaseReq req) {  
  42.           
  43.     }  
  44.   
  45.     @Override  
  46.     public void onResp(BaseResp resp) {  
  47.         Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);  
  48.           
  49.         if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {  
  50.             AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  51.             builder.setTitle("提示");  
  52.             //builder.setMessage(getString(R.string.pay_result_callback_msg, String.valueOf(resp.errCode)));  
  53.             builder.show();  
  54.             Intent intent;  
  55.             int code = resp.errCode;  
  56.             switch (code) {  
  57.             case 0:  
  58.                 Toast.makeText(this"支付成功",0).show();  
  59.                 intent=new Intent(this,SelectPayTypeActivity.class);  
  60.                 intent.putExtra("result"0);  
  61.                 startActivity(intent);  
  62.                 finish();  
  63.                 break;  
  64.             case -1:  
  65.                 Toast.makeText(this"支付失败",0).show();  
  66.                 intent=new Intent(this,SelectPayTypeActivity.class);  
  67.                 intent.putExtra("result", -1);  
  68.                 startActivity(intent);  
  69.                 finish();  
  70.                 break;  
  71.             case -2:  
  72.                 Toast.makeText(this"支付取消",0).show();  
  73.                 intent=new Intent(this,SelectPayTypeActivity.class);  
  74.                 intent.putExtra("result", -2);  
  75.                 startActivity(intent);  
  76.                 finish();  
  77.                 break;  
  78.             default:  
  79.                 break;  
  80.             }  
  81.         }  
  82.     }  
  83. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值