1. 程式人生 > >Android 整合微信支付步驟詳解

Android 整合微信支付步驟詳解

Android開發要點說明 整合之前的步驟不能省,下面引用官網步驟

1、後臺設定
商戶在微信開放平臺申請開發應用後,微信開放平臺會生成APP的唯一標識APPID。由於需要保證支付安全,需要在開放平臺繫結商戶應用包名和應用簽名,設定好後才能正常發起支付。設定介面在【開放平臺】中的欄目【管理中心 / 修改應用 / 修改開發資訊】裡面,如圖紅框內所示。


應用包名:是在APP專案配置檔案AndroidManifest.xml中宣告的package值,例如DEMO中的package="net.sourceforge.simcpux"。

2.Android  開始整合支付程式碼

首先導包  

compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'

非同步任務獲取支付引數

import android.content.Intent;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.Bind;
import butterknife.OnClick;

public class PayActivity extends BaseActivity {
    @Bind(R.id.top_title)
    TextView top_title;
    @Bind(R.id.count_down)
    RushBuyCountDownTimerView count_down;

    @Bind(R.id.price)
    TextView price;
    @Bind(R.id.image_zfb)
    ImageView image_zfb;
    @Bind(R.id.iamge_wechat)
    ImageView iamge_wechat;
    @Bind(R.id.order_num)
    TextView order_num;
    @Bind(R.id.order_name)
    TextView order_name;
    @Bind(R.id.order_time)
    TextView order_time;
    @Bind(R.id.order_money)
    TextView order_money;
    @Bind(R.id.pay_total)
    TextView pay_total;

    private int select = 1;
    private OrderEntity mPerson;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    public void initView() {
        super.initView();
        mPerson = (OrderEntity) getIntent().getSerializableExtra("body");
        if (mPerson != null) {
            price.setText("¥" + mPerson.getOrder_total());
            order_num.setText("訂單號:" + mPerson.getOrder_sn());
            order_name.setText("產品名稱:" + mPerson.getName());
            order_time.setText("遊玩時間:" + mPerson.getUse_date());
            order_money.setText("訂單金額:" + mPerson.getOrder_total() + "(線上支付)");
            pay_total.setText("¥" + mPerson.getOrder_total());
            long time = 1000 * 60 * 30;
            count_down.setTime(time);
            count_down.start();
        }
        top_title.setText("訂單支付");
    }

    @Override
    public void initData() {
        super.initData();
    }

    @OnClick({R.id.top_left, R.id.zfb_rela, R.id.wechat_rela, R.id.submit})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_left:
                PayActivity.this.finish();
                break;
            case R.id.zfb_rela:
                if (select == 1) {
                    return;
                }
                select = 1;
                setview(select);
                break;
            case R.id.wechat_rela:
                if (select == 2) {
                    return;
                }
                select = 2;
                setview(select);
                break;
            case R.id.submit://購買
                if (mPerson != null) {
                    new PayOrderTask().execute();
                }
                break;
        }
    }


    private void setview(int index) {
        image_zfb.setImageResource(R.drawable.order_pay_gray_gou);
        iamge_wechat.setImageResource(R.drawable.order_pay_gray_gou);
        if (index == 1) {
            image_zfb.setImageResource(R.drawable.order_pay_red_gou);
        } else {
            iamge_wechat.setImageResource(R.drawable.order_pay_red_gou);
        }
    }


    /*
  *非同步從後臺獲取支付引數
  * */
    class PayOrderTask extends WorkTask<Void, Void, WeiChatBean> {
        @Override
        protected void onPrepare() {
            super.onPrepare();
            showAlert("..正在購買..", false);
        }

        @Override
        public WeiChatBean workInBackground(Void... voids) throws TaskException {
            //產品編號
            MapUtil.sharedInstance().putDefaultValue(Constants.PAY_PRODUCT_ID, mPerson.getOrder_sn());
            MapUtil.sharedInstance().putDefaultValue(Constants.ORDER_ID, mPerson.getOrder_id());
            //支付的金錢
            MapUtil.sharedInstance().putDefaultValue(Constants.PAY_MONEY, mPerson.getOrder_total());
            return SDK.newInstance(PayActivity.this).getPrePayOrder(mPerson.getName(), mPerson.getOrder_sn(), mPerson.getOrder_total());
        }

        @Override
        protected void onSuccess(WeiChatBean info) {
            super.onSuccess(info);
            dismissAlert();
            if (info.getBody() != null) {
                ToBuyUtils.lunchWeChat(PayActivity.this, Consts.PayType.Pay_Product_Buy, info.getBody());
            }
        }

        @Override
        protected void onFailure(TaskException exception) {
            super.onFailure(exception);
            dismissAlert();
            Toast.makeText(PayActivity.this, "" + exception.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }


}

調起微信支付類統一入口
import android.content.Context;
import android.text.TextUtils;
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;



/**
 * Created by lyj on 2017/8/1.
 */

public class ToBuyUtils {
    /**
     * 調起微信支付
     * @param info
     */
    public static void lunchWeChat(Context context, Consts.PayType payType, BRewardBean info){
        //獲取到打賞訂單等資訊
            IWXAPI msgApi = WXAPIFactory.createWXAPI(context,null);
            msgApi.registerApp(Constants.WE_CHAT_APP_ID);//微信開放平臺建立應用的appid
            PayReq req = ToBuyUtils.getWeChatPayReq(info);
            msgApi.sendReq(req);
        //存入訂單編號,供後面查詢訂單支付情況
        MapUtil.sharedInstance().putDefaultValue(Constants.ORDER_ID_KEY,info.getNoncestr());
        //存入微信支付型別
        MapUtil.sharedInstance().putDefaultValue(Constants.ORDER_TYPE,payType.getPayTypeName());
    }

    /**
     * 獲取微信支付的PayReq
     *
     * @param bean
     * @return
     */
    public static PayReq getWeChatPayReq(BRewardBean bean) {
        PayReq req = new PayReq();
        req.appId = bean.getAppid();//微信ID
        req.partnerId = bean.getPartnerid();//商戶ID
        req.prepayId = bean.getPrepayid();//預支付訂單編號
        req.packageValue =bean.getWechatPackage();
        req.nonceStr= bean.getNoncestr();
        req.timeStamp = bean.getTimestamp();
        req.sign = bean.getSign();
        return req;
    }

    /**
     * 判斷字串是否為空
     */
    public static boolean isEmpty(String data) {
        return data == null || data.trim().length() < 1 || "null".equals(data.toLowerCase()) || data.equals("false");
    }

    public static String formatString(String str, String defaultStr) {
        if (null == str || str.equals("") || str.length()<1) {
            return defaultStr;
        }
        return str;
    }

    public static String formatObject(Object object, String defaultStr) {
        if (object == null) {
            return defaultStr;
        }
        return object.toString();
    }

    public static int formatNum(String intStr, int defaultValue) {
        int value;
        if (TextUtils.isEmpty(intStr) || intStr.equals("") || intStr.equals("null"))
            return defaultValue;
        try {
            value = Integer.parseInt(intStr);
        } catch (Exception e) {
            value = defaultValue;
        }
        return value;
    }

    public static double formatDoubleNum(String intStr, double defaultValue) {
        double value;
        if (TextUtils.isEmpty(intStr) || intStr.equals("") || intStr.equals("null"))
            return defaultValue;
        try {
            value = Double.parseDouble(intStr);
        } catch (Exception e) {
            value = defaultValue;
        }
        return value;
    }

}

接下來就是微信支付狀態回調了WXPayEntryActivity.java ,注意:這個activity的路徑必須是 微信開放平臺填寫的包名加.wxapi下 ,

package 你的包名.wxapi;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.ArrayList;

/**
 * 微信支付返回
 */
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

    private TextView tvPayCallBack;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_result);
        api = WXAPIFactory.createWXAPI(this, Constants.WE_CHAT_APP_ID, true);
        api.handleIntent(getIntent(), this);
        tvPayCallBack = (TextView) findViewById(R.id.tvPayCallBack);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {

    }

    @Override
    public void onResp(final BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
          if (resp.errCode == 0) {
            //根據訂單號 查詢支付狀態   要以後臺查詢微信後臺的結果為準
          延時1.5秒再調後臺介面查詢
          
            } else if (resp.errCode == -2) {
                //使用者沒有操作
                this.finish();
            } else {
                TLog.log("tttt", "--支付失敗:" );
                dialog("簽名問題,支付失敗", resp.errCode + "");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MapUtil.sharedInstance().clear();
    }

    private void dialog(String title, String dex) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到構造器
        builder.setMessage(title + "==" + dex); //設定內容
        builder.setCancelable(false);
        builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { //設定確定按鈕
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //關閉dialog
                WXPayEntryActivity.this.finish();
            }
        });
        //引數都設定完成了,建立並顯示出來
        builder.create().show();
    }

    private void dialogs(String title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到構造器
        builder.setMessage(title); //設定內容
        builder.setCancelable(false);
        builder.setPositiveButton("確定", new DialogInterface.OnClickListener(){ //設定確定按鈕
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //關閉dialog
//                MapUtil.sharedInstance().getDefaultValue(Constants.PAY_PRODUCT_ID).toString();
                Intent intent=new Intent(WXPayEntryActivity.this,OrderDetailActivity.class);
                intent.putExtra("order_state", getResources().getString(R.string.personal_out_order));
                intent.putExtra("order_id",MapUtil.sharedInstance().getDefaultValue(Constants.ORDER_ID).toString());
                startActivity(intent);
                WXPayEntryActivity.this.finish();
            }
        });
        //引數都設定完成了,建立並顯示出來
        builder.create().show();
    }

}

整個Android端微信支付就到此完成了