微信支付

·  阅读 221

微信支付步骤

private IWXAPI api;

复制代码
api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID);
api.registerApp(Constant.WX_APP_ID);
复制代码
mWXPay.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "发起支付", Toast.LENGTH_SHORT).show();
        PayReq req = new PayReq();
        //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
        req.appId			= appId;
        req.partnerId		= "partnerId";
        req.prepayId		= prepayId;
        req.nonceStr		= nonceStr;
        req.timeStamp		= timeStamp;
        req.packageValue	= "Sign=WXPay";
        req.sign			= sign;
        //req.extData			= "app data"; // optional
        Toast.makeText(MainActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
        // 在支付之前,如果应用没有注册到微信,应该先调用IWXMsg.registerApp将应用注册到微信

        api.sendReq(req);
    }
});
复制代码

4.获取回调activity

package 应用包名.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import android.widget.Toast;

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 cn.zhiup.mobile.Constant;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler
{
	private IWXAPI api;
	public static final String wxPayAction = "wx_pay_success";
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID);
		api.handleIntent(getIntent(), this);
	}

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

	@Override
	public void onReq(BaseReq arg0) {}

	@Override
	public void onResp(BaseResp arg0) {
		if (arg0.getType() == ConstantsAPI.COMMAND_PAY_BY_WX)
		{
			if(arg0.errCode == 0){
				Intent intent = new Intent();
				intent.setAction(wxPayAction);
				sendBroadcast(intent);
				Toast.makeText(this,"微信支付成功",Toast.LENGTH_LONG).show();
			}else if(arg0.errCode == -1){
				Toast.makeText(this,"微信支付失败"+arg0.errStr+arg0.transaction+arg0.openId,Toast.LENGTH_LONG).show();
			}else if(arg0.errCode == -2){
				Toast.makeText(this,"微信支付取消",Toast.LENGTH_LONG).show();
			}
		}
//		WXPayEntryActivity.this.finish();
	}
}
复制代码
收藏成功!
已添加到「」, 点击更改