Android支付接入(一):支付宝

本文档详细介绍了如何在Android应用中接入支付宝SDK,包括所需的权限设置、支付逻辑代码实现以及关键步骤解释。通过示例代码展示了从按钮点击到发起支付请求的完整过程,适用于快速集成到各种项目中。
摘要由CSDN通过智能技术生成
相信相同过App获取利润的都会需要接入计费SDK,下边就跟大家走一遍完整的支付宝SDK接入,支付系列均通过计费Button触发,计费所有代码均放到一个java文件实现,这样虽然会有点违背java面向对象及封装性,但这样做的一个好处是可以快速集成到不同的游戏中,将改动的文件降到最低,各有利弊吧,如果大家有什么更好的方法,望一起交流,好了,废话不多说了,开始干活。
PS:初次写博文,各方面还不够完善,看到此博文的朋友有什么意见或者建议请回复或者留言,你们的支持是我最大的动力。

注意事项:
1.添加android.permission.INTERNET权限和android.permission.ACCESS_NETWORK_STATE权限
2.代码中出现注释的地方重点看,没注释的地方可以不看
3.参考下边代码及附带demo足以让你完成支付宝支付,若想了解支付宝更多相关问题请参考附带文档,demo及文档下载地址:http://pan.baidu.com/share/link?shareid=421254&uk=473193131
4.想获取支付宝合作商户ID,及支付宝公钥请点击支付宝链接,生成密钥及PKCS8转码工具在文档中

好了,开始贴代码
MainActivity(程序入口文件)
package com.example.blogforzfb;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//拿到Fiap对象并传入容器
Fiap fiap = new Fiap(MainActivity.this);
//调用支付方法,并传入支付金额
fiap.android_pay(0.01);
}
});
}

}

Fiap.java(支付逻辑所在文件)
package com.example.blogforzfb;

// 支付宝应用支付
// 2012-09-20 14:41:47
// (c) 2012 Catcap

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.alipay.android.app.IAlixPay;
import com.alipay.android.app.IRemoteServiceCallback;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;


@SuppressLint ("HandlerLeak")
public class Fiap{
    Activity mActivity = null;
    
    // ===================================
    // JAVA 的接口
    // ===================================
   
    
    public Fiap(Activity activity){
   
    mActivity = activity;
   
    }
    
    //这里传过来的是想支付多少钱(最好定义成double的,方便调试,毕竟每次测试都支付几元大洋不是每个人都负担的起的)
    public void android_pay (double coin){
   
    //支付宝支付必须依赖网络,所以在这里必须加网络判定
        if (!is_can_internet (mActivity)){
       
            fiapHandler.sendEmptyMessage(1);
            return;
        }
        
        Message msg = new Message ();
        Bundle bundle = new Bundle();
        bundle.putDouble("coin", coin);
        msg.setData(bundle);
        msg.what = 1;
        fss.sendMessage (msg);
    }
    
    private Handler fiapHandler = new Handler(){
   
    public void handleMessage(Message msg) {
    if (msg.what == 1) {
    new AlertDialog.Builder (mActivity).setTitle ("提示").setMessage ("连接不到网络。").setPositiveButton ("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(
"android.settings.WIFI_SETTINGS");
mActivity.startActivity(intent);
}
}).create ().show ();
}
    };
    };
    
    // ===================================
    // 支付宝
    // ===================================
    public class PartnerConfig {

//以下配置涉及到公司内容,所以略去,需自己配置
        // 合作商户ID。用签约支付宝账号登录ms.alipay.com后,在账户信息页面获取。
        public static final String PARTNER = ""; 
        // 商户收款的支付宝账号
        public static final String SELLER = "";
        // 商户(RSA)私钥(注意一定要转PKCS8格式,否则在Android4.0及以上系统会支付失败)
        public static final String RSA_PRIVATE = "";
        // 支付宝(RSA)公钥 用签约支付宝账号登录ms.alipay.com后,在密钥管理页面获取。
        public static final String RSA_ALIPAY_PUBLIC = "";
    }
    
    
    private ProgressDialog mProgress = null;
    
    
    public static class AlixOnCancelListener implements DialogInterface.OnCancelListener {
        Activity mcontext;
        
        
        AlixOnCancelListener (Activity context){
            mcontext = context;
        }
        
        
        public void onCancel (DialogInterface dialog){
            mcontext.onKeyDown (KeyEvent.KEYCODE_BACK, null);
        }
    }
    
    
    private Handler fss = new Handler (){
        @SuppressWarnings ("deprecation")
        public void handleMessage (Message msg){
            MobileSecurePayHelper mspHelper = new MobileSecurePayHelper (mActivity);
            boolean isMobile_spExist = mspHelper.detectMobile_sp ();
            if (!isMobile_spExist)
                return;
            // 根据订单信息开始进行支付
            try{
                // 准备订单信息
                Bundle bundle = msg.getData();
                double _coin = bundle.getDouble("coin");
                String orderInfo = getOrderInfo(_coin);
                // 这里根据签名方式对订单信息进行签名
                String signType = getSignType ();
                String strsign = sign (signType, orderInfo);
                // 对签名进行编码
                strsign = URLEncoder.encode (strsign);
                // 组装好参数
                String info = orderInfo + "&sign=" + """ + strsign + """ + "&" + getSignType ();
                // 调用pay方法进行支付
                MobileSecurePayer msp = new MobileSecurePayer ();
                boolean bRet = msp.pay (info, mHandler, AlixId.RQF_PAY, mActivity);
                if (bRet){
                    // 显示“正在支付”进度条
                    closeProgress ();
                    mProgress = BaseHelper.showProgress (mActivity, null, "正在支付", false, true);
                }
            } catch (Exception ex){
                ex.printStackTrace ();
            }
        }
    };
    
    private Handler mHandler = new Handler (){
        public void handleMessage (Message msg){
            try{
                String strRet = (String) msg.obj;
                switch (msg.what){
                    case AlixId.RQF_PAY:{
                        //
                        closeProgress ();
                        // 处理交易结果
                        try{
                            // 获取交易状态码,具体状态代码请参看文档
                            String tradeStatus = "resultStatus={";
                            int imemoStart = strRet.indexOf ("resultStatus=");
                            imemoStart += tradeStatus.length ();
                            int imemoEnd = strRet.indexOf ("};memo=");
                            tradeStatus = strRet.substring (imemoStart, imemoEnd);
                            //先验签通知
                            ResultChecker resultChecker = new ResultChecker (strRet);
                            int retVal = resultChecker.checkSign ();
                            if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED){
                                BaseHelper.showDialog (mActivity, "提示", "您的订单信息已被非法篡改。", android.R.drawable.ic_dialog_alert);
                            } else{
                                if (tradeStatus.equals ("9000")){
                               
                                    //程序到这里表示支付已经成功了,想干什么就在这里干吧 -v-
                                Toast.makeText(mActivity, "支付成功",Toast.LENGTH_LONG).show();
                                Log.i("result of this pay:", "successful");
                                
                                } else if (!tradeStatus.equals ("4000")){
                               
                                //程序到这里表示此次支付失败,查看具体原因可以从这里打印个log
                                Toast.makeText(mActivity, "支付失败,交易状态码为:" + tradeStatus, Toast.LENGTH_LONG).show();
                                Log.e("result of this pay", "falied");
                                }
                            }
                        } catch (Exception e){
                            e.printStackTrace ();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值