美文网首页
支付宝条码支付

支付宝条码支付

作者: 一young的宠爱 | 来源:发表于2018-07-16 17:23 被阅读0次

1.首先找到自己所需功能的开发文档,通过文档进行

2.例如,查看条码支付文档,创建自己的应用;https://docs.open.alipay.com/194/106039

3.配置此应用的公私钥,以及签约功能(个人是不可以签约的);

4.我们也可以通过沙箱环境进行测试(遇到错误,可以通过技术文档或者沙箱环境的错误集锦);

https://sandbox.alipaydev.com/user/accountDetails.htm?currentBar=1

5.编写代码:

(1)可以直接使用支付宝的SDK(下载sdk,最好也下载源码,方便查看);
  //获得初始化的AlipayClient
       AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APPID, RSA_PRIVATE, "json", "gbk", ALIPAY_PUBLIC_KEY, "RSA2");
               //创建API对应的request类
  AlipayTradePayRequest request = new AlipayTradePayRequest();
               request.setBizContent("{" +
                       "    \"out_trade_no\":\"" + getOutTradeNo() + "\"," +
                       "    \"scene\":\"bar_code\"," +
                       "    \"auth_code\":\"" + authCode + "\"," +
                       "    \"subject\":\"Iphone6 16G\"," +
                       "    \"store_id\":\"NJ_001\"," +
                       "    \"timeout_express\":\"2m\"," +
                       "    \"total_amount\":\"0.01\"" +
                       "  }"); //设置业务参数
               Runnable payRunnable = new Runnable() {

                   @Override
                   public void run() {
                       try {
                           Log.e("www", "request = " + request.getApiVersion());
                           AlipayTradePayResponse response = alipayClient.execute(request);
                           Log.e("www", "response = " + response.getBody());
                       } catch (AlipayApiException e) {
                           e.printStackTrace();
                       }
                   }
               };
               Thread payThread = new Thread(payRunnable);
               payThread.start();
(2)使用http请求,可以通过查看之前的demo项目作为参考,
                boolean rsa = true;
               //构造支付订单参数列表
               Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa,authCode);
               //构造支付订单参数信息
               String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
               Log.e("www", "orderParam = " + orderParam);
               //对支付参数信息进行签名
               String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE, rsa);
               //订单信息
               final String orderInfo = orderParam + "&" + sign;
               Log.e("www", "orderInfo = " + orderInfo);
               AlipayApi alipayApi = new AlipayApi(this, orderInfo);
               alipayApi.getOkttpResponse();
               alipayApi.setOnHttpResponseListener(new AlipayApi.OnHttpResponseListener() {
                   @Override
                   public void onHttpResponseListener(String response) {
                       parseGson(response);
                   }
               });
OrderInfoUtil2_0类
package com.lijian.alipay;

import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;


public class OrderInfoUtil2_0 {
    
    /**
     * 构造授权参数列表
     * 
     * @param pid
     * @param app_id
     * @param target_id
     * @return
     */
    public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id, boolean rsa2) {
        Map<String, String> keyValues = new HashMap<String, String>();

        // 商户签约拿到的app_id,如:2013081700024223
        keyValues.put("app_id", app_id);

        // 商户签约拿到的pid,如:2088031559016493
        keyValues.put("pid", pid);

        // 服务接口名称, 固定值
        keyValues.put("apiname", "com.alipay.account.auth");

        // 商户类型标识, 固定值
        keyValues.put("app_name", "mc");

        // 业务类型, 固定值
        keyValues.put("biz_type", "openservice");

        // 产品码, 固定值
        keyValues.put("product_id", "APP_FAST_LOGIN");

        // 授权范围, 固定值
        keyValues.put("scope", "kuaijie");

        // 商户唯一标识,如:kkkkk091125
        keyValues.put("target_id", target_id);

        // 授权类型, 固定值
        keyValues.put("auth_type", "AUTHACCOUNT");

        // 签名类型
        keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA");

        return keyValues;
    }

    /**
     * 构造支付订单参数列表
     * @param
     * @param
     * @param
     * @return
     */
    public static Map<String, String> buildOrderParamMap(String app_id, boolean rsa2,String auth_code) {
        Map<String, String> keyValues = new HashMap<String, String>();

        keyValues.put("app_id", app_id);

        keyValues.put("biz_content",
                "{\"out_trade_no\":\"" + getOutTradeNo() + "\"," +
                        "    \"scene\":\"bar_code\"," +
                        "    \"auth_code\":\""+ auth_code + "\"," +
                        "    \"subject\":\"Iphone6 16G\"," +
                        "    \"store_id\":\"NJ_001\"," +
                        "    \"timeout_express\":\"2m\"," +
                        "    \"total_amount\":0.01" +
                        "  }");
        
        keyValues.put("charset", "utf-8");

        keyValues.put("method", "alipay.trade.pay");

        keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA");

        keyValues.put("timestamp", "2016-07-29 16:55:53");

        keyValues.put("version", "1.0");
        
        return keyValues;
    }
    /**
     * 构造支付订单参数信息
     * 
     * @param map
     * 支付订单参数
     * @return
     */
    public static String buildOrderParam(Map<String, String> map) {
        List<String> keys = new ArrayList<>(map.keySet());

        StringBuilder sb = new StringBuilder();
        sb.append("https://openapi.alipay.com/gateway.do?");
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            sb.append(buildKeyValue(key, value, true));
            sb.append("&");
        }

        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        sb.append(buildKeyValue(tailKey, tailValue, true));

        return sb.toString();
    }
    
    /**
     * 拼接键值对
     * 
     * @param key
     * @param value
     * @param isEncode
     * @return
     */
    private static String buildKeyValue(String key, String value, boolean isEncode) {
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        if (isEncode) {
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                sb.append(value);
            }
        } else {
            sb.append(value);
        }
        return sb.toString();
    }
    
    /**
     * 对支付参数信息进行签名
     * 
     * @param map
     *            待签名授权信息
     * 
     * @return
     */
    public static String getSign(Map<String, String> map, String rsaKey, boolean rsa2) {
        List<String> keys = new ArrayList<String>(map.keySet());
        // key排序
        Collections.sort(keys);
        Log.e("www", "keys = " + keys.toString());
        StringBuilder authInfo = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            authInfo.append(buildKeyValue(key, value, false));
            authInfo.append("&");
        }
        Log.e("www", "authInfo = " + authInfo);
        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        authInfo.append(buildKeyValue(tailKey, tailValue, false));

        String oriSign = SignUtils.sign(authInfo.toString(), rsaKey, rsa2);
        String encodedSign = "";

        try {
            encodedSign = URLEncoder.encode(oriSign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "sign=" + encodedSign;
    }
    
    /**
     * 要求外部订单号必须唯一。
     * @return
     */
    public static String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key +(r.nextInt(10));
        key = key.substring(0, 15);
        Log.e("www", "TradeNo = " + key);
        return key;
    }

}

AlipayApi类(我使用的是okhttpclient协议,AndroidStudio 可以直接添加依赖,Gson解析类)

compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.11.0'
compile 'com.google.code.gson:gson:2.8.0'

package com.lijian.alipay;

import android.content.Context;
import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Description:
 * Date       : 2018/7/11 16:04
 */

public class AlipayApi {
    private Context mContext;
    private String url;
    private OnHttpResponseListener listener;
    public AlipayApi(Context mContext,String url) {
        this.mContext = mContext;
        this.url = url;
    }

    public void getOkttpResponse() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("www", "onFailure = " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String strResponse = response.body().string();
                Log.e("www", "response = " + strResponse);
                listener.onHttpResponseListener(strResponse);
            }
        });
    }

    public void setOnHttpResponseListener(OnHttpResponseListener listener) {
        this.listener = listener;
    }
    public interface OnHttpResponseListener{
        void onHttpResponseListener(String response);
    }
}

添加权限
<!--支付宝支付权限-->
    <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" />     
可能会存在下列问题
java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
解决办法:

https://blog.csdn.net/shuxiangxingkong/article/details/51332221
Google官方出的分包方案,采用MultiDex支持库
1,配置Modle的building.gradle,开启MultiDex

android {
    defaultConfig {
        multiDexEnabled true
    }
}

dependencies{
    compile'com.android.support:multidex:1.0.0'
}

2,配置应用
方法1:在AndroidManifest.xml的application中声明

android.support.multidex.MultiDexApplication;

package="com.example.android.multidex.myapplication">
      ...
   android:name="android.support.multidex.MultiDexApplication">

        ...

方法2:让你自己的Application类继承MultiDexApplication

方法3:让你自己的Application类重写attachBaseContext

方法,

@Override

protected voidattachBaseContext(Context base) {

super.attachBaseContext(base);

MultiDex.install(this);

}

相关文章

网友评论

      本文标题:支付宝条码支付

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