美文网首页
微信/支付宝 第三方支付相关

微信/支付宝 第三方支付相关

作者: 扶云九霄 | 来源:发表于2018-04-18 16:19 被阅读15次

支付宝

  • 无客户端时,可调用网页支付
 <activity
            android:name="com.alipay.sdk.app.H5PayActivity"
            android:configChanges="orientation|keyboardHidden|navigation"
            android:exported="false"
            android:screenOrientation="behind"
            android:windowSoftInputMode="adjustResize|stateHidden" >
 </activity>
  • 支付结果
 public class AliPayResult  {
    private String resultStatus;
    private String result;
    private String memo;

    public AliPayResult(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;
    }
}
  • 发起支付
public class AliPayUtils {
    private static AliPayUtils aliPayUtils = null;

    private AliPayUtils(){

    }

    public static AliPayUtils getInstance(){
        if (aliPayUtils == null)
            aliPayUtils = new AliPayUtils();
        return aliPayUtils;
    }

    public void alipay_v2(final String orderInfo, final IPayCallback callback){
        new RxJavaUtils<String>().handleDataByThread(new RxScheduler<String>() {
            @Override
            public String doInThread() {
                PayTask alipay = new PayTask(ThirdPayUtils.mActivity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());
                AliPayResult payResult = new AliPayResult(result);
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();
                return resultStatus;
            }

            @Override
            public void doInUI(String resultCode) {
                if(callback != null)
                    callback.onResult(resultCode);
            }
        });
    }
}

微信

  • 回调接收类 (包名目录下wxapi.WXPayEntryActivity)
public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
    private static final String TAG = WXPayEntryActivity.class.getSimpleName();
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, "wx4f6d2f117e3724ec");
        api.handleIntent(getIntent(), this);
    }

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

    @Override
    public void onReq(BaseReq baseReq) {
    }

    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            L.i("onResp:" + baseResp.errCode);
            if (ThirdPayUtils.mCallbackContext != null && ThirdPayUtils.mWxPayResp != null) {
                try {
                    JSONObject respJson = new JSONObject();
                    respJson.put("resultCode", String.valueOf(baseResp.errCode));
                    respJson.put("payType", ThirdPayUtils.mWxPayResp.payType);
                    respJson.put("orderId", ThirdPayUtils.mWxPayResp.orderId);
                    respJson.put("tradeNo", ThirdPayUtils.mWxPayResp.tradeNo);
                    L.i(TAG, "wxPay callback--->" + respJson.toString());
                    ThirdPayUtils.mCallbackContext.success(respJson);
                    ThirdPayUtils.mWxPayResp = null;
                    ThirdPayUtils.mCallbackContext = null;
                    finish();
                } catch (JSONException e) {

                }
            }
        }
    }
}
  • 清单配置
 <activity
            android:name=".wxapi.WXPayEntryActivity"
            android:theme="@style/AppStartLoadTheme"
            android:exported="true"
            android:launchMode="singleTop" />

<activity-alias
            android:name="${applicationId}.wxapi.WXPayEntryActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:targetActivity=".wxapi.WXPayEntryActivity"/>
  • 发起支付
// 从服务器获取加密后的相关支付参数
JSONObject aliPayJson = args.getJSONObject(0);
                L.i(TAG, "aliPayJson:" + aliPayJson);
                final String payType = aliPayJson.getString("payType");
                final String orderId = aliPayJson.getString("orderId");
                final String tradeNo = aliPayJson.getString("tradeNo");
                String orderInfo = aliPayJson.getString("sign");
                AliPayUtils.getInstance().alipay_v2(orderInfo, new IPayCallback() {
                    @Override
                    public void onResult(String resultCode) {
                        try {
                            JSONObject respJson = new JSONObject();
                            respJson.put("resultCode", resultCode);
                            respJson.put("payType", payType);
                            respJson.put("orderId", orderId);
                            respJson.put("tradeNo", tradeNo);
                            L.i(TAG, "aliPay callback--->" + respJson.toString());
                            //回调给页面
                            callbackContext.success(respJson);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
  • 支付工具类
public class WXPayUtils {
    private IWXAPI iwxapi; //微信支付api

    private WXPayBuilder builder;

    private WXPayUtils(WXPayBuilder builder) {
        this.builder = builder;
    }

    /**
     * 调起微信支付的方法,不需要在客户端签名
     **/
    public void toWXPayNotSign(Context context, String appid) {
        iwxapi = WXAPIFactory.createWXAPI(context, null); //初始化微信api
        iwxapi.registerApp(appid); //注册appid  appid可以在开发平台获取

       if (!isInstallWx(context))
           return;

        Runnable payRunnable = new Runnable() {  //这里注意要放在子线程
            @Override
            public void run() {
                PayReq request = new PayReq(); //调起微信APP的对象
                //下面是设置必要的参数,也就是前面说的参数,这几个参数从何而来请看上面说明
                request.appId = builder.getAppId();
                request.partnerId = builder.getPartnerId();
                request.prepayId = builder.getPrepayId();
                request.packageValue = builder.getPackageValue();
                request.nonceStr = builder.getNonceStr();
                request.timeStamp = builder.getTimeStamp();
                request.sign = builder.getSign();
                L.i("MyPlugin", "wxPay sendReq--->appid:" + request.appId +
                        " nonceStr:" + request.nonceStr + " sign:" + request.sign);
                iwxapi.sendReq(request);//发送调起微信的请求
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 调起微信支付的方法,需要在客户端签名
     **/
    public void toWXPayAndSign(Context context, String appid,final String key) {
        iwxapi = WXAPIFactory.createWXAPI(context, null); //初始化微信api
        iwxapi.registerApp(appid); //注册appid  appid可以在开发平台获取

        if (!isInstallWx(context))
            return;

        Runnable payRunnable = new Runnable() {  //这里注意要放在子线程
            @Override
            public void run() {
                if (TextUtils.isEmpty(builder.getAppId())
                        ||TextUtils.isEmpty(builder.getPartnerId())
                        ||TextUtils.isEmpty(builder.getPrepayId())){
                    Log.e("chx", "toWXPayAndSign: "+"必须在builder中设置appId、PartnerId、PrepayId");
                    return;
                }
                PayReq request = new PayReq(); //调起微信APP的对象
                //下面是设置必要的参数,也就是前面说的参数,这几个参数从何而来请看上面说明
                request.appId = builder.getAppId();
                request.partnerId = builder.getPartnerId();
                request.prepayId = builder.getPrepayId();
                request.packageValue = "Sign=WXPay";
                request.nonceStr = genNonceStr();
                request.timeStamp = String.valueOf(genTimeStamp());
                request.sign = builder.getSign();
                //签名
                LinkedHashMap<String, String> signParams = new LinkedHashMap<>();
                signParams.put("appid", request.appId);
                signParams.put("noncestr", request.nonceStr);
                signParams.put("package", request.packageValue);
                signParams.put("partnerid", request.partnerId);
                signParams.put("prepayid", request.prepayId);
                signParams.put("timestamp", request.timeStamp);
                request.sign = genPackageSign(signParams,key);
                iwxapi.sendReq(request);//发送调起微信的请求
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private boolean isInstallWx(Context context){
        if (iwxapi.isWXAppInstalled() && iwxapi.isWXAppSupportAPI()) {
            return true;
        }
        Toast.makeText(context.getApplicationContext(),"您未安装最新版本微信," +
                "不支持微信支付,请安装或升级微信版本",Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
     * 调起微信APP支付,签名
     * 生成签名
     */
    private   String genPackageSign(LinkedHashMap<String, String> params,String key) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String,String> entry: params.entrySet()) {
            sb.append(entry.getKey());
            sb.append('=');
            sb.append(entry.getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(key);

        String packageSign = getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return packageSign;
    }

    /**
     * md5加密
     * @param buffer
     * @return
     */
    private String getMessageDigest(byte[] buffer) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取随机数
     *
     * @return
     */
    private String genNonceStr() {
        Random random = new Random();
        return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }


    /**
     * 获取时间戳
     *
     * @return
     */
    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    public static class WXPayBuilder {
        public String appId;
        public String partnerId;
        public String prepayId;
        public String packageValue;
        public String nonceStr;
        public String timeStamp;
        public String sign;

        public WXPayUtils build() {
            return new WXPayUtils(this);
        }

        public String getAppId() {
            return appId;
        }

        public WXPayBuilder setAppId(String appId) {
            this.appId = appId;
            return this;
        }

        public String getPartnerId() {
            return partnerId;
        }

        public WXPayBuilder setPartnerId(String partnerId) {
            this.partnerId = partnerId;
            return this;
        }

        public String getPrepayId() {
            return prepayId;
        }

        public WXPayBuilder setPrepayId(String prepayId) {
            this.prepayId = prepayId;
            return this;
        }

        public String getPackageValue() {
            return packageValue;
        }

        public WXPayBuilder setPackageValue(String packageValue) {
            this.packageValue = packageValue;
            return this;
        }

        public String getNonceStr() {
            return nonceStr;
        }

        public WXPayBuilder setNonceStr(String nonceStr) {
            this.nonceStr = nonceStr;
            return this;
        }

        public String getTimeStamp() {
            return timeStamp;
        }

        public WXPayBuilder setTimeStamp(String timeStamp) {
            this.timeStamp = timeStamp;
            return this;
        }

        public String getSign() {
            return sign;
        }

        public WXPayBuilder setSign(String sign) {
            this.sign = sign;
            return this;
        }
    }
}
  • 支付结果
/**
 * Created by Administrator on 2018/1/25.
 * {"ReturnCode":100,
 * "appid":"wxdf2cabf1061e6fc2",
 * "partnerid":"1497030692",
 * "PrepayId":"wx20180125143653d8e8a085240910652449",
 * "package":"Sign=WXPay",
 * "noncestr":"QC9NQTB4NB8GTC6L6NKA",
 * "timestamp":"1516862216",
 * "sign":"219619027BE60F8B1E7CCC16979C233F"}
 */

public class WxPayResp {
    public int ReturnCode;
    public String appid;
    public String partnerid;
    public String PrepayId;
    public String noncestr;
    public String timestamp;
    public String sign;
    public String packageValue;
    public String payType;
    public String orderId;
    public String tradeNo;

    public WxPayResp(JSONObject wxPayJson){
        try {
            ReturnCode = wxPayJson.getInt("ReturnCode");
            appid = wxPayJson.getString("appid");
            partnerid = wxPayJson.getString("partnerid");
            PrepayId = wxPayJson.getString("PrepayId");
            noncestr = wxPayJson.getString("noncestr");
            timestamp = wxPayJson.getString("timestamp");
            sign = wxPayJson.getString("sign");
            packageValue = wxPayJson.getString("package");
            payType = wxPayJson.getString("payType");
            orderId = wxPayJson.getString("orderId");
            tradeNo = wxPayJson.getString("tradeNo");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

相关文章

  • 聚合支付

    一,什么是聚合支付? 1,微信,支付宝支付为第三方支付;基于并整合微信支付宝等多种第三方支付平台,并提供支付技术和...

  • 聚合支付

    一,什么是聚合支付? 1,微信,支付宝支付为第三方支付;基于并整合微信支付宝等多种第三方支付平台,并提供支付技术和...

  • 支付功能

    项目中集成的第三方支付如下: 支付宝支付及(支付宝多账户支付 )?支付宝花呗微信及微信多账户支付银联京东支付京东白...

  • 第三方支付

    支付宝 支付宝属于第三方支付(微信\新浪\百度) 第三方支付的流程 实现支付宝支付的准备工作 支付宝准入条件 计费模式

  • 支付宝微信抢占大半壁江山,聚合支付是如何存在的?

    如今,在移动支付市场上,支付宝和微信占移动市场份额高达95%,对于支付宝和微信来说,他们是第三方支付,那么聚合支付...

  • 第三方支付平台整理

    第三方支付平台详情 接入文档 支付宝微信支付 收费率 限额 大额支付平台

  • 第三方

    支付相关 1>支付宝 蚂蚁金服开放平台 2>微信 开通支付能力 微信开放平台 分享相关 1>友盟 获取分享...

  • 支付宝网关支付流程及注意事项

    在开发商城网站时需要使用第三方支付网关,业界以支付宝和微信支付更为可靠,支付宝属于第三方支付担保平台,提供了如支付...

  • iOS支付的配置

    iOS支付 iOS支付分为两类,第三方支付和应用内支付(内购)。 第三方支付包括:支付宝支付、微信支付、银联支付、...

  • iOS之支付

    iOS支付 iOS支付分为两类,第三方支付和应用内支付(内购)。 第三方支付包括:支付宝支付、微信支付、银联支付、...

网友评论

      本文标题:微信/支付宝 第三方支付相关

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