ios swift java_支付宝登录接入(Android/IOS(swift)/Java后台)

客户端的签名代码用的是客户端jar包,服务器端用的服务器jar包,且服务器根本没有签名示例代码。

为此楼主只有强行将客户端部分代码照搬至服务器端,不管是否规范,至少签名在服务器这边处理是做到了。代码如下(代码真心多,但是为了一个类完成所有功能,只能勉强放一起了。):

import com.alipay.api.AlipayApiException;

import com.alipay.api.AlipayClient;

import com.alipay.api.DefaultAlipayClient;

import com.alipay.api.domain.AlipayTradeAppPayModel;

import com.alipay.api.domain.AlipayTradePrecreateModel;

import com.alipay.api.internal.util.AlipaySignature;

import com.alipay.api.request.*;

import com.alipay.api.response.*;

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.security.KeyFactory;

import java.security.PrivateKey;

import java.security.Security;

import java.security.spec.PKCS8EncodedKeySpec;

import java.util.*;

public class AliPayUtils {

private static final String APP_ID = "";//这个就不强调了,这个都找不到相比开发难度很大,我这文笔很难帮到你了。

private static final String PID = "";//在开放平台内点击右上角那里点击密钥管理,然后点击左边mapi网关产品密钥就能看到pid了。

private static final String APP_PRIVATE_KEY = "";//下面的这些信息在应用信息里边基本能看到,有些可能需要上传设置。

private static final String RSA2_PRIVATE = "";//rsa2私钥

private static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzG+wSFicJ1BAP+/51vY8Zn4ZVNMgWuJCTAvfUh48QjixfJwYdr0lX8aOOHVLiC4zOBMdKi0Ale/R/myl1duCnWhCz9XgxMG/x5MpuxESU0SY6HZimW wQGxoRmKsM3ICa7zmBa58nOig0cKY1ipJ6VXmTGSeiwF7TReKAGU8PeyYTZvnTgmIKofD7L8oAQF2xom3RlFbtzkjf4UaYbr+7m52dktPp6t7PwVKbbAiqDfVIoswrBaAPDmBWrf1Uaj8kt3KVzsiJzpN1xT0oRFikKj9KuMbIMI+ESpDr1674ToJa46AjI+0O8WxfQrebMuE/ xkUCG0WaQCXllLjtRXc7wIDAQAB";

private static final String CHARSET = "UTF-8";

public static boolean alipayCallBack(Map requestParams) {

Boolean isPay = false;

// 获取支付宝POST过来反馈信息

Map params = new HashMap<>();

for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {

String name = (String) iter.next();

String[] values = requestParams.get(name);

String valueStr = "";

for (int i = 0; i < values.length; i++) {

valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";

}

params.put(name, valueStr);

}

try {

boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, "RSA2");

if (flag) {

String tradeStatus = params.get("trade_status");

if ("TRADE_SUCCESS".equals(tradeStatus)

|| "TRADE_FINISHED".equals(tradeStatus)) {

String outTradeNo = params.get("out_trade_no");// 商户订单号

String tradeNo = params.get("trade_no");// 商户订单号

String gmtPayment = params.get("gmt_payment");// 支付时间

String gmtCreate = params.get("gmt_create");// 创建时间

}

}

} catch (AlipayApiException e) {

e.printStackTrace();

}

return false;

}

public static AlipayTradeQueryResponse getPayInfo(String outTradeNo, String tradeNo) {

AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do"

, APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");

AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

request.setBizContent("{" +

"\"out_trade_no\":\"" + outTradeNo + "\"," +

"\"trade_no\":\"" + tradeNo + "\"," +

"\"org_pid\":\"" + PID + "\"" +

" }");

try {

return alipayClient.execute(request);

} catch (AlipayApiException e) {

return null;

}

}

public static String getPayStr(String totalAmount, String subject, String outTradeNo) {

AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do"

, APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");

AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();

AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

model.setSubject(subject);

model.setOutTradeNo(outTradeNo);

model.setTimeoutExpress("10m");

model.setTotalAmount(totalAmount);

model.setProductCode("QUICK_MSECURITY_PAY");

request.setBizModel(model);

request.setNotifyUrl("");//这里记得放支付回调地址

try {

AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);

if (response.isSuccess()) {

return response.getBody();

} else {

throw new BaseException(BaseResultEnum.ALIPAY_SIGN_ERROR);

}

} catch (AlipayApiException e) {

throw new BaseException(BaseResultEnum.ALIPAY_SIGN_ERROR);

}

}

public static AlipayUserInfoShareResponse signAuthStr(String authCode) throws AlipayApiException {

AlipayClient alipayClient = new DefaultAlipayClient(

"https://openapi.alipay.com/gateway.do", APP_ID

, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY

, "RSA2");

AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();

request.setGrantType("authorization_code");

request.setCode(authCode);

AlipayUserInfoShareRequest userInfoRequest = new AlipayUserInfoShareRequest();

AlipaySystemOauthTokenResponse response =

alipayClient.execute(request);

if (response.isSuccess()) {

AlipayUserInfoShareResponse userInfoResponse

= alipayClient.execute(userInfoRequest, response.getAccessToken());

if (userInfoResponse.isSuccess()) {

return userInfoResponse;

}

System.out.println("signAuthStr调用成功");

} else {

System.out.println("signAuthStr 调用失败");

}

return null;

}

public static String getAuthStr() {

Map authInfoMap = buildAuthInfoMap();

String info = buildOrderParam(authInfoMap);

String sign = getSign(authInfoMap, RSA2_PRIVATE, true);

return info + "&" + sign;

}

private static String buildOrderParam(Map map) {

List keys = new ArrayList(map.keySet());

StringBuilder sb = new StringBuilder();

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();

}

private static Map buildAuthInfoMap() {

Map keyValues = new HashMap();

keyValues.put("app_id", APP_ID);

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");

keyValues.put("target_id", String.valueOf(System.currentTimeMillis())

+ new Random().nextInt(10000));

keyValues.put("auth_type", "AUTHACCOUNT");

keyValues.put("sign_type", "RSA2");

return keyValues;

}

private static String getSign(Map map, String rsaKey

, boolean rsa2) {

List keys = new ArrayList(map.keySet());

Collections.sort(keys);

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("&");

}

String tailKey = keys.get(keys.size() - 1);

String tailValue = map.get(tailKey);

authInfo.append(buildKeyValue(tailKey, tailValue, false));

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

String encodedSign = "";

try {

encodedSign = URLEncoder.encode(oriSign, "UTF-8");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return "sign=" + encodedSign;

}

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();

}

private static final String ALGORITHM = "RSA";

private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

private static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA";

private static final String DEFAULT_CHARSET = "UTF-8";

private static String getAlgorithms(boolean rsa2) {

return rsa2 ? SIGN_SHA256RSA_ALGORITHMS : SIGN_ALGORITHMS;

}

private static String sign(String content, String privateKey, boolean rsa2) {

try {

PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(

Base64.getDecoder().decode(privateKey));

Security.addProvider(

new org.bouncycastle.jce.provider.BouncyCastleProvider());

KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, "BC");

PrivateKey priKey = keyFactory.generatePrivate(priPKCS8);

java.security.Signature signature = java.security.Signature

.getInstance(getAlgorithms(rsa2));

signature.initSign(priKey);

signature.update(content.getBytes(DEFAULT_CHARSET));

byte[] signed = signature.sign();

return Base64.getEncoder().encodeToString(signed);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

贴完代码可能会有人代码报错,很正常,因为里边用到了官方没有说的代码(原始代码用的Android的jdk没问题,但是服务器端的部分jdk代码和客户端有差异,所以就报错了),解决方案:

# gradle用户在build.gardle加入:

"org.bouncycastle:bcprov-jdk16:1.45",

# mvn用户在pom.xml加入:

org.bouncycastle

bcprov-jdk16

1.45

这样服务器端签名代码就写好(只是签名字符串),调用getAuthStr()方法就能返回了。

首先将获得的realResult上传至服务器。然后我这边贴下服务器端的处理代码(首先是getAlipayAuthCode()方法,传入的是realResult,返回的是authCode,让后将获得的authCode传入signAuthStr()方法就获得了用户信息了,具体的信息可以参考官方文档):

private final String ALIPAY_AUTH_CODE_START = "auth_code=";

private final String ALIPAY_AUTH_CODE_END = "&";

private String getAlipayAuthCode(String response) {

String result = response.substring(response.indexOf(ALIPAY_AUTH_CODE_START)

+ ALIPAY_AUTH_CODE_START.length(), response.length() - 1);

return result.substring(0, result.indexOf(ALIPAY_AUTH_CODE_END));

}

public static AlipayUserInfoShareResponse signAuthStr(String authCode) throws AlipayApiException {

AlipayClient alipayClient = new DefaultAlipayClient(

"https://openapi.alipay.com/gateway.do", APP_ID

, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY

, "RSA2");

AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();

request.setGrantType("authorization_code");

request.setCode(authCode);

AlipayUserInfoShareRequest userInfoRequest = new AlipayUserInfoShareRequest();

AlipaySystemOauthTokenResponse response =

alipayClient.execute(request);

if (response.isSuccess()) {

AlipayUserInfoShareResponse userInfoResponse

= alipayClient.execute(userInfoRequest, response.getAccessToken());

if (userInfoResponse.isSuccess()) {

return userInfoResponse;

}

System.out.println("signAuthStr调用成功");

} else {

System.out.println("signAuthStr 调用失败");

}

return null;

}

获得了支付宝用户信息整个登录流程也基本结束了,剩下的就是自己业务逻辑的处理了,因为整个流程实在太复杂,写的可能有很多不详细的地方,还望谅解,发现不对的地方还望及时指正,有问题也可以评论指出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS Swift中连接扫描枪的代码主要分为两个部分:Bluetooth连接和接收扫描数据。 首先,需要在应用中引入CoreBluetooth库。在ViewController中创建一个BLEManager类,并像下面这样定义其属性和方法: ```swift class BLEManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate { var centralManager: CBCentralManager? var peripheral: CBPeripheral? var characteristic:CBCharacteristic? override init() { super.init() centralManager = CBCentralManager(delegate: self, queue: nil) } func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOn { central.scanForPeripherals(withServices:nil, options: nil) print("Scanning started") } else { print("Bluetooth not available.") } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { if (peripheral.name == "Your peripheral name") { self.centralManager?.stopScan() self.peripheral = peripheral self.peripheral?.delegate = self self.centralManager?.connect(self.peripheral!, options: nil) } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { if peripheral == self.peripheral { peripheral.discoverServices(nil) print("Connected to your peripheral") } } func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { for service in peripheral.services! { peripheral.discoverCharacteristics(nil, for: service) } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { for characteristic in service.characteristics! { if characteristic.uuid == CBUUID(string: "Your characteristic UUID") { self.characteristic = characteristic peripheral.setNotifyValue(true, for: characteristic) print("Characteristic found") } } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if characteristic == self.characteristic { if let data = characteristic.value { let string = String(data: data, encoding: .utf8)! print("Scanned barcode is: \(string)") } } } } ``` 接着,在ViewController中初始化BLEManager并调用centralManager的方法: ```swift var bleManager: BLEManager? override func viewDidLoad() { super.viewDidLoad() bleManager = BLEManager() } ``` 最后,需要将扫描枪的UUID和特征UUID替换为自己的。这样,应用就能连接扫描枪并接收扫描数据了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值