微信支付实用实战

开发流程

1 :去找你们产品要微信开放平台的账号密码。

2 :去微信官方文档下载一个 **签名生成工具 **: 签名生成工具下载地址

3 : 签名工具安装到手机上之后,把你们的 项目打包 打一个 release 包安装到手机上,( 切记 :“打包要打个release包不要打debug包,也不是让你run运行到手机上面,因为你上线的时候用的是正式包(release包)上线的”),安装到手机上之后,打开你上一步下载的“签名生成工具”),把你项目的 包名 放在“输入框”里面,点击按钮“Get Signature”会在按钮下面生成一串绿色签名,保存起来一会要用到(如图)。(此刻,一定有童鞋会说我怎么没有看到生成绿色的一串签名?怎么提示“NameNotFoundExcption signs is null”(),正如其报错,肯定是你包名写错啦,或者就是你手机上忘记安装你们的App啦…)
4 :这时候肯定有童鞋会问生成的这个签名是干嘛的有什么用?生成的签名是你们App的一个唯一标识,拿着这个标识(签名)去微信开放平台的管理中心 / 修改应用 / 修改开发信息,给Android的开发信息给填写一下(如图),签名 包名填写完保存一下。

5 : 流程的最后一步:到微信开放平台的 管理中心 / 应用中心 把你们的AppSecret和AppID保存起来。

 //微信支付
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'

App支付集成代码

package com.dogotsn.duojia4android.app.utils;

import android.content.Context;

import com.jess.arms.utils.ArmsUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.security.MessageDigest;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

import timber.log.Timber;

public class WXPayUtils {
    private IWXAPI iwxapi;
    //微信支付api
    private WXPayBuilder builder;

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

    /**
     * 调起微信支付的方法,不需要在客户端签名
     **/
    public void toWXPayNotSign(Context context) {
        iwxapi = WXAPIFactory.createWXAPI(context, null);
        //初始化微信api
        iwxapi.registerApp(builder.getAppId());
        //注册appid  appid可以在开发平台获取
        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();
//                request.extData = "app data"; // optional
                iwxapi.sendReq(request);
                boolean b = request.checkArgs();
                //发送调起微信的请求
            }
        };
        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(builder.getAppId());
        //注册appid  appid可以在开发平台获取
        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 = "Sign=WXPay";
//                request.nonceStr = genNonceStr();
//                request.timeStamp = String.valueOf(genTimeStamp());
                request.nonceStr = builder.getNonceStr();
                request.timeStamp = builder.getTimeStamp();
//                request.sign = builder.getSign();
                //签名
                LinkedHashMap<String, String> signParams = new LinkedHashMap<>();
                signParams.put("appid", request.appId);
                signParams.put("noncestr", request.nonceStr);
                signParams.put("package", "Sign=WXPay");
                signParams.put("partnerid", request.partnerId);
                signParams.put("prepayid", request.prepayId);
                signParams.put("timestamp", request.timeStamp);
                request.sign = genPackageSign(signParams, key);
                boolean b = iwxapi.sendReq(request);
                //发送调起微信的请求
                Timber.d("b:" + b);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
        if (!iwxapi.isWXAppInstalled()) {
            ArmsUtils.makeText(context, "请安装微信!");
        }
    }

    /**
     * 调起微信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;
        }
    }
}

WXPayEntryActivity

WXPayEntryActivity 要放在 wxapi 包下

packagecom.xyxy.app.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

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.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.cocos2dx.wolf.MyApplication;
import org.cocos2dx.wolf.utils.ShareUtils;

import java.util.HashMap;
import java.util.Map;


/**
*
* 2018/12/5
*
* W
*
* */


public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;
    private String AppID=;//微信开放平台AppID
   
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       api = WXAPIFactory.createWXAPI(this, AppID);
       api.handleIntent(getIntent(), this);
   }

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


   @Override
   public void onResp(BaseResp resp) {
       Log.d("WXPayEntryActivity", "微信返回错误码:" + resp.errCode);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
           if (resp.errCode == 0) {
               Toast.makeText(this, "支付成功", Toast.LENGTH_LONG).show();
           } else {
               Log.e("java", "onResp: " + resp.errCode);
               Toast.makeText(this, "取消支付", Toast.LENGTH_LONG).show();
           }
           finish();
       }
   }

   @Override
   public void onReq(BaseReq baseReq) {

   }
}

MainActivity

Android代码调用

String appid = data.getAppid();
IWXAPI wxapi = WXAPIFactory.createWXAPI(app,appid,false);//初始化微信api
wxapi.registerApp(data.getAppid());
WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
builder.setAppId(data.getAppid())
        .setPrepayId(data.getPrepayid())
        .setPackageValue(data.getPackageX())
        .setNonceStr(data.getNoncestr())
        .setTimeStamp(data.getTimestamp())
        .setSign(data.getSign())
        .build()
        .toWXPayNotSign(app);          

AndroidManifest.xml


  //微信支付
       <activity
           android:name=".wxapi.WXPayEntryActivity"
           android:configChanges="keyboardHidden|orientation|screenSize"
           android:exported="true"
           android:launchMode="singleInstance"
           android:screenOrientation="portrait"
           android:theme="@android:style/Theme.NoDisplay">
           <intent-filter>
               <action android:name="android.intent.action.VIEW" />

               <category android:name="android.intent.category.DEFAULT" />

               <data android:scheme="微信AppID"/>
           </intent-filter>
       </activity>
       

支付返回 “-1” 与 “闪屏”的原因解决

1,微信签名要用release包生成 测试的时候也要打release包安装到手机测试,不能run运行,否则 闪屏
2,AppID是否正确
3,AndroidManifest.xml的 name 固定是 name=".wxapi.WXPayEntryActivity"调用微信

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值