微信支付接入(Android/IOS(swift)/Java后台)

本文章仅作为个人笔记

接入方式可参考微信登录接入

  • IOS端(swift):

    • 主要接入和代码可参考微信登录接入
      • 本人使用HandyJSON框架方便json处理,用于实例化服务器返回对象

          	import HandyJSON
          	
          	class ResponseWX: HandyJSON {
          	
          	    var appid: String = "";
          	    var partnerid: String = "";
          	    var noncestr: String = "";
          	    var packageName: String = "";
          	    var prepayid: String = "";
          	    var timestamp: UInt32 = 0;
          	    var sign: String = "";
          	    var orderNumber: String = "";
          	
          	    required init() {
          	    }
          	
          	}
        
      • 创建支付回调类并实例化

          	struct WechatPayBack: HttpUtilsBack {
          	    func finish(result: String?, error: BaseError?) {
          	        if error == nil {
          	        	//支付成功
          	        } else {
          	        	//支付失败
          	        }
          	    }
          	}
          	//实例化支付回调及为AppDelegate的wechatPayBack赋值
          	appDelegate?.wechatPayBack = WechatPayBack()
        
      • 调起支付关键代码

          	//从服务器获取签名信息,这里只需要服务器处理即可。
          	let result: ResponseWX = getResultFromService()
          	//创建支付请求实例并调起支付。
          	let req = PayReq()
          	req.openID = result?.appid
          	req.partnerId = result?.partnerid
          	req.package = result?.packageName
          	req.prepayId = result?.prepayid
          	req.nonceStr = result?.noncestr
          	req.timeStamp = result!.timestamp
          	req.sign = result?.sign
          	WXApi.send(req)
        
  • Android端:

    • 主要接入和代码可参考微信登录接入
    • 除按照微信登录方式接入外还需进行如下操作:
      • 创建 包名.wxapi.WXPayEntryActivity 文件,保证内容如下(WechartUtils下面会给出):

          		import android.app.Activity;
          		import android.os.Bundle;
          		import android.util.Log;
          		
          		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.modelpay.PayResp;
          		import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
          		
          		public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
          		
          		    public static final String APP_ID = "";//填入自己的appid
          		    public static Back authBack;
          		
          		    public interface Back {
          		        public void onFiled(String errorMsg);
          		
          		        public void onSuccess(String code, String state);
          		    }
          		
          		    public static void registAuthBack(Back back) {
          		        authBack = back;
          		    }
          		
          		    public static void unregistAuthBack() {
          		        authBack = null;
          		    }
          		
          		    @Override
          		    protected void onCreate(Bundle savedInstanceState) {
          		        super.onCreate(savedInstanceState);
          		        WechartUtils.getInstance(this, APP_ID)
          		                .handleIntent(this, this);
          		    }
          		
          		    @Override
          		    public void onReq(BaseReq baseReq) {
          		        Log.e("-----1", "baseReq=" + baseReq);
          		    }
          		
          		    @Override
          		    public void onResp(BaseResp baseResp) {
          		        switch (baseResp.getType()) {
          		            case ConstantsAPI.COMMAND_PAY_BY_WX:
          		                if (authBack != null) {
          		                    // 0:成功; -1:错误; -2:用户取消;
          		                    PayResp payResp = (PayResp) baseResp;
          		                    if (payResp.errCode == 0) {
          		                        authBack.onSuccess(String.valueOf(payResp.errCode), payResp.prepayId);
          		                    } else {
          		                        authBack.onFiled(baseResp.errStr);
          		                    }
          		                }
          		                break;
          		        }
          		        finish();
          		    }
          		
          		    @Override
          		    protected void onDestroy() {
          		        super.onDestroy();
          		        WechartUtils.getInstance(this, APP_ID)
          		                .unregisterApp(this);
          		    }
          		
          		}
        
        • 创建WechartUtils文件用于公共处理支付

          		import android.app.Activity;
          		import android.util.Log;
          		
          		import com.tencent.mm.opensdk.modelmsg.SendAuth;
          		import com.tencent.mm.opensdk.modelpay.PayReq;
          		import com.tencent.mm.opensdk.openapi.IWXAPI;
          		import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
          		import com.tencent.mm.opensdk.openapi.WXAPIFactory;
          		
          		import java.util.concurrent.ConcurrentHashMap;
          		
          		public class WechartUtils {
          		
          		    private static final WechartUtils wechartUtils = new WechartUtils();
          		    private static final ConcurrentHashMap<String, IWXAPI> apis = new ConcurrentHashMap<>();
          		
          		    private WechartUtils() {
          		    }
          		
          		    public static WechartUtils getInstance(Activity activity, String appId) {
          		        if (activity != null
          		                && !apis.containsKey(activity.getLocalClassName())) {
          		            IWXAPI api = WXAPIFactory.createWXAPI(activity, appId, true);
          		            api.registerApp(appId);
          		            apis.put(activity.getLocalClassName(), api);
          		        }
          		        return wechartUtils;
          		    }
          		
          		    public WechartUtils handleIntent(Activity activity
          		            , IWXAPIEventHandler handler) {
          		        apis.get(activity.getLocalClassName())
          		                .handleIntent(activity.getIntent(), handler);
          		        return this;
          		    }
          		
          		    public void pay(Activity activity, String appId, String partnerId, String packageName
          		            , String prepayId, String nonceStr, String timeStamp, String sign) {
          		        if (activity == null) {
          		            return;
          		        }
          		        PayReq req = new PayReq();
          		        req.appId = appId;//appid
          		        req.partnerId = partnerId;//微信支付分配的商户号
          		        req.packageValue = packageName;//暂填写固定值Sign=WXPay
          		        req.prepayId = prepayId;//微信返回的支付交易会话ID
          		        req.nonceStr = nonceStr;//随机字符串
          		        req.timeStamp = timeStamp;//时间戳
          		        req.sign = sign;//签名
          		        IWXAPI api = apis.get(activity.getLocalClassName());
          		        if (api != null) {
          		            api.sendReq(req);
          		        }
          		    }
          		
          		    public void login(Activity activity) {
          		        if (activity == null) {
          		            return;
          		        }
          		        SendAuth.Req req = new SendAuth.Req();
          		        req.scope = "snsapi_userinfo";
          		        req.state = String.valueOf(System.currentTimeMillis());
          		        IWXAPI api = apis.get(activity.getLocalClassName());
          		        if (api != null) {
          		            api.sendReq(req);
          		        }
          		    }
          		
          		    public void unregisterApp(Activity activity) {
          		        if (activity == null) {
          		            return;
          		        }
          		        IWXAPI api = apis.get(activity.getLocalClassName());
          		        if (api != null) {
          		            api.unregisterApp();
          		            apis.remove(activity.getLocalClassName());
          		        }
          		    }
          		
          		}
          
        • 在AndroidManifest.xml文件内注册activity

          		<activity
          		    android:name=".wxapi.WXPayEntryActivity"
          		    android:exported="true"
          		    android:label="@string/app_name" />
          
        • 创建好工具文件后可以开始准备开发了,这里贴出主要使用伪代码。

          		public class DemoActivity extends Activity {
          		    private WechartUtils wechartUtils;
          		    @Override
          		    protected void onCreate(Bundle savedInstanceState) {
          		    	//初始化工具
          		        wechartUtils = WechartUtils.getInstance(this, WXPayEntryActivity.APP_ID);
          		        //注册微信支付回调
          		        WXPayEntryActivity.registAuthBack(new WXPayEntryActivity.Back() {
          		            @Override
          		            public void onFiled(String errorMsg) {
          		            	//支付失败回调
          		            }
          		
          		            @Override
          		            public void onSuccess(String code, String state) {
          		            	//失败成功回调
          		            }
          		        });
          		    }
          		
          		    //开始微信支付方法
          		    private void startWechatPay() {
          		    	//去服务器获取签名信息 具体返回的信息可查看后面的后台开发
          		    	WXResponse response = getWXResponse();
          		    	//调用wechartUtils的pay方法调起微信支付。
          		    	wechartUtils.pay(this, response.appid, response.partnerid
          		                	, response.packageName, response.prepayid, response.noncestr
          		                	, response.timestamp, response.sign);
          		    }
          		
          		    @Override
          		    protected void onDestroy() {
          		    	//取消注册
          		        wechartUtils.unregisterApp(this);
          		        WXPayEntryActivity.unregistAuthBack();
          		        super.onDestroy();
          		    }
          		
          		}
          
  • java后台:

    • 主要接入和代码可参考 微信登录接入

    • 用户获取支付签名信息只需要调用WechartUtils.getWXResponse()方法,返回对象即可。第一个参数为商品名称,第二个参数为商品描述,第三个参数为商品订单号,第四个参数为价格(这里的价格为分,所以加入为1元应给100,此参数无小数点),第五个参数为发起请求的客户端ip,可能有人不知道怎么获取ip,这里给出一个ip获取工具类,如果还是获取不到,可以评论或者加好友询问。

      		import org.slf4j.Logger;
      		import org.slf4j.LoggerFactory;
      		
      		import javax.servlet.http.HttpServletRequest;
      		
      		public class IPUtils {
      		
      		    private static final Logger log = LoggerFactory.getLogger(IPUtils.class);
      		    private static final String IP_SPLIT = "\\.";
      		    private static final String IP_ZERO = "0.0.0.0";
      		
      		    public static String getIP(HttpServletRequest request) {
      		        String ip = request.getHeader("x-real-ip");
      		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      		            ip = request.getHeader("x-forwarded-for");
      		        }
      		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      		            ip = request.getHeader("Proxy-Client-IP");
      		        }
      		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      		            ip = request.getHeader("WL-Proxy-Client-IP");
      		        }
      		        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      		            ip = request.getRemoteAddr();
      		        }
      		        if (ip != null && !ip.isEmpty()) {
      		            ip = ip.split(",")[0];
      		        }
      		        return ip;
      		    }
      		
      		
      		    public static int ip2Key(String ip) {
      		        int result = 0;
      		        if (ip != null && !ip.isEmpty()) {
      		            String[] parts = ip.split(IP_SPLIT);
      		            if (parts.length == 4) {
      		                try {
      		                    result = ((Integer.valueOf(parts[0]) % 256) << 16) + ((Integer.valueOf(parts[1]) % 256) << 8) + (Integer.valueOf(parts[2]) % 256);
      		                } catch (Exception e) {
      		                    log.error("e=" + e);
      		                }
      		            } else {
      		                log.error("parts.length=" + parts.length + ";ip=" + ip);
      		            }
      		        }
      		        return result;
      		    }
      		
      		    public static long ip2LIP(String ip) {
      		        long result = ip2Key(ip);
      		        if (result != 0) {
      		            try {
      		                result += Integer.valueOf(ip.split(IP_SPLIT)[3]);
      		            } catch (Exception e) {
      		                log.error("e=" + e);
      		            }
      		        }
      		        return result;
      		    }
      		
      		    public static boolean isIpMath(String ip) {
      		        return ip2LIP(ip) != 0 || IP_ZERO.equals(ip);
      		    }
      		
      		}
      
    • 客户端完成支付回调后可将商家订单号上传,用于去微信后台查验并进行相应业务处理。

      		//根据客户端上传的订单号orderNumber查询是否已经有订单,防止重复下单。
      		OrderHistory orderHistory = orderHistoryMapper.getOrderHistoryByOrderNumber(orderNumber);
      		if (orderHistory == null) {
      		    boolean isSuccess = false;
      		    for (int index = 0; !isSuccess && index < 3; index++) {
      		        if (index != 0) {//给微信3s时间处理订单,可自行调节
      		            Thread.sleep(1000);
      		        }
      		        isSuccess = WechartUtils.checkWXOrder(orderNumber);//判断订单是否完成支付
      		    }
      		    if (isSuccess) {
      		    	//如果支付成功进行业务处理
      		    }
      		} else {
      			//订单已存在
      		}
      
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页