美文网首页
[手把手教] 三方支付宝支付

[手把手教] 三方支付宝支付

作者: 崽子猪 | 来源:发表于2019-06-13 15:07 被阅读0次

    GitHub三方支付宝Deom
    先上效果图

    拉起支付界面
    支付完成

    开发前准备

    首先进入蚂蚁金服开放平台,使用手机端支付宝App扫描二维码进入主页.
    第一步
    找到开发中心进入创建应用 ---> 网页应用 ---> 确认创建 ---> 选择开发中你所需要的功能并且同意协议

    选择功能

    第二步找到开放设置

    设置应用公钥
    设置公钥
    支付宝密钥生成器
    下载zip包解压到[ 无中文目录 (图一) ]
    打开解压出来的 (rsa_public_key.pem) [ 图二 ]
    将公钥复制粘贴到设置公钥里点击验证公钥正确性 [ 图三 ]
    解压后点击配置私钥的bat(这时候需要我们刚才配置RSA里面的私有密钥) [ 图四 rsa_private_key_pkcs8.pem ]
    将这串私钥粘贴后生成签名复制出来验证 [ 图五 图六 ]
    验证成功后点击保存
    点击查找支付宝公钥保存到本地 [ 图七 ]

    第三步
    同意协议之后提交审核 嘟嘟嘟 就完成啦

    图一
    图二
    图三
    图四
    图五
    图六
    图七

    继承三方支付

    我们先看一下支付流程图 [ 图九 ]


    图九

    目将volley.jar导入进libs目录下并且引入Studio[ 图十 图十一 ]

    图十
    图十一

    将三方支付宝所下载的arr导入libs下并且在项目级别下的gradle里添加

    flatDir{
                dirs 'libs'
     }
    

    在依赖里添加 PS: alipaySdk-15.6.2-20190416165036 换成自己arr的名字

    implementation(name: 'alipaySdk-15.6.2-20190416165036', ext: 'aar')
    

    在清单文件里加入权限

    <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
        <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    

    MainActivity代码 里面有注释

    public class MainActivity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String> {
    
        private static final String TAG = "MainActivity";
    
        private static final int SDK_PAY_FLAG = 10;
        private Button payFor;
        //post请求,token,金额,应用版本号,操作系统系统
        private String mUrl = "http://api.banmi.com/api/app/v3/payments/alipay";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            iniper();
            initView();
        }
    
        private void iniper() {
            String[] per = {Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
    
            ActivityCompat.requestPermissions(this,per,100);
        }
    
        private void initView() {
            payFor = (Button) findViewById(R.id.payFor);
            payFor.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    aliPay();
                    Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
                }
            });
        }
    
        private void aliPay() {
    
            // 1.请求自己家的服务器 商品id 用户id 商品价格 商品数量
            RequestQueue queue = Volley.newRequestQueue(this); //请求队列
            StringRequest request = new StringRequest(Request.Method.POST, mUrl, this, this){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    ArrayMap<String, String> map = new ArrayMap<>();
                    map.put("amount","1.0");
                    map.put("token","mKVoQRrXlMvmfWbgWzyDYHF1KOUN5e4bwWrOiab9tZ8sWIQAZmg48lSa2NOORqpko6V0l4cYCs1Uip23M6MglE6Xp6LvHKO9RUNP4m8pHjp1zHb8nmK1bU1pvRp2LFkwA");
                    map.put("version","3.3.3");
                    map.put("os","android");
                    return map;
                }
            };
            queue.add(request); // ☆ 发起请求
    
        }
    
        // 成功回调
        @Override
        public void onResponse(String s) {
            Log.i(TAG, "onErrorResponse: "+s);
            // 2.解析自己服务器返回的数据 拿到支付串码
            Gson gson = new Gson();
            AliPayBean aliPayBean = gson.fromJson(s, AliPayBean.class);
    
                    // 3.调用支付宝的SKD,拉起支付界面
             callAliSdk(aliPayBean);
    
    
        }
    
        private void callAliSdk(AliPayBean aliPayBean) {
            final String orderInfo = aliPayBean.getResult().getSign();   // 订单信息
    
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayTask alipay = new PayTask(MainActivity.this);
                    Map<String,String> result = alipay.payV2(orderInfo,true);
    
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    
        //4.处理支付宝app返回的支付结果
        @SuppressLint("HandlerLeak")
        private Handler mHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SDK_PAY_FLAG: {
                        @SuppressWarnings("unchecked")
                        PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                        /**
                         * 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            // 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
                            showToast("支付成功:"+payResult);
                            Log.d(TAG, "支付成功: "+payResult+",resultInfo:"+resultInfo);
                        } else {
                            // 该笔订单真实的支付结果,需要依赖服务端的异步通知。
                            showToast("支付失败:"+payResult);
                            Log.d(TAG, "支付失败: "+payResult+",resultInfo:"+resultInfo);
                        }
                        break;
                    }
    
                    default:
                        break;
                }
            };
        };
    
        // 失败回调
        @Override
        public void onErrorResponse(VolleyError volleyError) {
    
        }
    
        public void showToast(String msg){
            Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
        }
    
    }
    
    

    把Bean类和接口回调也给大家

    AliPayBean

    public class AliPayBean {
    
        /**
         * code : 0
         * desc :
         * result : {"sign":"app_id=2017071807800448&method=alipay.trade.app.pay&version=1.0&format=JSON&charset=utf8&sign_type=RSA2&timestamp=2019-06-04%2010%3A53%3A22&notify_url=https%3A%2F%2Fapi.banmi.com%2Fapi%2Fapp%2Fv3%2Fpayments%2Falibaba&biz_content=%7B%22subject%22%3A%22%E4%BC%B4%E7%B1%B3%E6%97%85%E8%A1%8C%22%2C%22out_trade_no%22%3A%22APP1559616802973ALIPAY321072%22%2C%22total_amount%22%3A%221.00%22%2C%22timeout_express%22%3A%2215m%22%7D&sign=Li%2FBFrL1OH3txIRs3yGNsY%2FWrKv9vB%2BF3gg4rakf5RuGZpqRuksr1Mf7AOySylLE809n4%2BjI3Rt3dbwxzg0AtAjuGP3%2BbQ4FAqj%2B6vaIbRIdiZhKoYTimVsdAFgpt93i3mdfl7B6x7jPfBLPyMmRAmJxwYcdZRreqT0oJiihs7LsfIrwDqjlQ9pJllmOE4AiZNuGEgBgPFNlqOiRQCplcfYNTCcw5bJGHJSiKAGOr5EpClQTJFzk28L%2BgOLZkKtXHgu62aQ1ZYxmeio8nXHfiaa0vv9D0FlTKWkFQErHcwub%2Bys5JkCwnkc%2FNiyLSlN%2BtDaMI6H9%2FRI6k6QEGyedsQ%3D%3D","id":10572}
         */
    
        private int code;
        private String desc;
        private ResultBean result;
    
        public int getCode() {
            return code;
        }
    
        public void setCode(int code) {
            this.code = code;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public void setDesc(String desc) {
            this.desc = desc;
        }
    
        public ResultBean getResult() {
            return result;
        }
    
        public void setResult(ResultBean result) {
            this.result = result;
        }
    
        public static class ResultBean {
            /**
             * sign : app_id=2017071807800448&method=alipay.trade.app.pay&version=1.0&format=JSON&charset=utf8&sign_type=RSA2&timestamp=2019-06-04%2010%3A53%3A22&notify_url=https%3A%2F%2Fapi.banmi.com%2Fapi%2Fapp%2Fv3%2Fpayments%2Falibaba&biz_content=%7B%22subject%22%3A%22%E4%BC%B4%E7%B1%B3%E6%97%85%E8%A1%8C%22%2C%22out_trade_no%22%3A%22APP1559616802973ALIPAY321072%22%2C%22total_amount%22%3A%221.00%22%2C%22timeout_express%22%3A%2215m%22%7D&sign=Li%2FBFrL1OH3txIRs3yGNsY%2FWrKv9vB%2BF3gg4rakf5RuGZpqRuksr1Mf7AOySylLE809n4%2BjI3Rt3dbwxzg0AtAjuGP3%2BbQ4FAqj%2B6vaIbRIdiZhKoYTimVsdAFgpt93i3mdfl7B6x7jPfBLPyMmRAmJxwYcdZRreqT0oJiihs7LsfIrwDqjlQ9pJllmOE4AiZNuGEgBgPFNlqOiRQCplcfYNTCcw5bJGHJSiKAGOr5EpClQTJFzk28L%2BgOLZkKtXHgu62aQ1ZYxmeio8nXHfiaa0vv9D0FlTKWkFQErHcwub%2Bys5JkCwnkc%2FNiyLSlN%2BtDaMI6H9%2FRI6k6QEGyedsQ%3D%3D
             * id : 10572
             */
    
            private String sign;
            private int id;
    
            public String getSign() {
                return sign;
            }
    
            public void setSign(String sign) {
                this.sign = sign;
            }
    
            public int getId() {
                return id;
            }
    
            public void setId(int id) {
                this.id = id;
            }
        }
    }
    

    PayResult

    public class PayResult {
        private String resultStatus;
        private String result;
        private String memo;
    
        public PayResult(Map<String, String> rawResult) {
            if (rawResult == null) {
                return;
            }
    
            for (String key : rawResult.keySet()) {
                if (TextUtils.equals(key, "resultStatus")) {
                    resultStatus = rawResult.get(key);
                } else if (TextUtils.equals(key, "result")) {
                    result = rawResult.get(key);
                } else if (TextUtils.equals(key, "memo")) {
                    memo = rawResult.get(key);
                }
            }
        }
    
        @Override
        public String toString() {
            return "resultStatus={" + resultStatus + "};memo={" + memo
                    + "};result={" + result + "}";
        }
    
        /**
         * @return the resultStatus
         */
        public String getResultStatus() {
            return resultStatus;
        }
    
        /**
         * @return the memo
         */
        public String getMemo() {
            return memo;
        }
    
        /**
         * @return the result
         */
        public String getResult() {
            return result;
        }
    }
    

    此处圈重点

    如果你是安卓9.0的用户 需要在清单文件中加入

    <application
            ....
        //加xml文件
            android:networkSecurityConfig="@xml/network_security_config"
            android:theme="@style/AppTheme">
            .....
    </application>
    

    @xml/network_security_config

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
    </network-security-config>
    

    相关文章

      网友评论

          本文标题:[手把手教] 三方支付宝支付

          本文链接:https://www.haomeiwen.com/subject/qwmrfctx.html